Skip to content

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

fix(tasks): don't protect a PR head branch as the signed-commit base (#65982)

Alessandro Pogliaghia4c5ca76c7f0
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index dede842c0e9c..9cacaa0f0912 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -732,6 +732,32 @@ class GitHubIntegrationBase:
return []
return [pr["html_url"] for pr in pulls if isinstance(pr, dict) and isinstance(pr.get("html_url"), str)]
+ def get_open_pr_base_for_head(self, repository: str, branch: str) -> str | None:
+ """Return the base branch of an OPEN pull request whose head is ``branch``, if one exists.
+
+ ``repository`` is ``owner/repo`` (or a bare repo, resolved against the org). Distinguishes
+ a branch that *heads* an open PR (work continues on it) from a branch used as a PR *base*.
+ Best-effort: returns None on a bad repo, non-200, no open PR, or any error.
+ """
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+ owner = repo_path.split("/", 1)[0]
+ response = self._installation_authenticated_get(
+ f"https://api.github.com/repos/{repo_path}/pulls",
+ endpoint="/repos/{owner}/{repo}/pulls",
+ params={"head": f"{owner}:{branch}", "state": "open", "per_page": 1},
+ )
+ if response is None or response.status_code != 200:
+ return None
+ try:
+ pulls = response.json()
+ except Exception:
+ logger.warning("GitHubIntegration: get_open_pr_base_for_head non-JSON response", repository=repo_path)
+ return None
+ if not isinstance(pulls, list) or not pulls or not isinstance(pulls[0], dict):
+ return None
+ base = (pulls[0].get("base") or {}).get("ref")
+ return base if isinstance(base, str) and base else None
+
_PR_SNAPSHOT_QUERY = """
query($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index cfabba5f8aba..091eadbc0d9e 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -937,6 +937,35 @@ class TestGitHubIntegrationModel(BaseTest):
assert result["success"] is False
assert result["status_code"] == 502
+ def test_get_open_pr_base_for_head_returns_base_ref_of_open_pr(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=200)
+ mock_response.json.return_value = [{"base": {"ref": "master"}, "head": {"ref": "posthog-code/fix"}}]
+ with patch.object(github, "_installation_authenticated_get", return_value=mock_response) as mock_get:
+ result = github.get_open_pr_base_for_head("PostHog/posthog", "posthog-code/fix")
+ assert result == "master"
+ # Query is scoped to open PRs whose head is the branch, in the repo owner's namespace.
+ assert mock_get.call_args.kwargs["params"] == {
+ "head": "PostHog:posthog-code/fix",
+ "state": "open",
+ "per_page": 1,
+ }
+
+ def test_get_open_pr_base_for_head_returns_none_when_no_open_pr(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=200)
+ mock_response.json.return_value = []
+ with patch.object(github, "_installation_authenticated_get", return_value=mock_response):
+ assert github.get_open_pr_base_for_head("PostHog/posthog", "master") is None
+
+ def test_get_open_pr_base_for_head_returns_none_on_error(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ with patch.object(github, "_installation_authenticated_get", return_value=None):
+ assert github.get_open_pr_base_for_head("PostHog/posthog", "posthog-code/fix") is None
+
def test_get_diff_truncates_oversized_diff(self):
from posthog.models.integration import _MAX_DIFF_CHARS
diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
index 6929fce8dbfa..6b4de8425593 100644
--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
@@ -5,6 +5,9 @@ from django.conf import settings
from temporalio import activity
+from posthog.models import Integration
+from posthog.models.integration import GitHubIntegration
+from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import asyncify
from posthog.temporal.oauth import PosthogMcpScopes
@@ -91,6 +94,43 @@ def _run_connectivity_diagnostics(ctx: TaskProcessingContext, sandbox: SandboxBa
logger.warning("Connectivity diagnostics failed (non-fatal)", error=str(e), run_id=ctx.run_id)
+def _resolve_protected_base_branch(ctx: TaskProcessingContext) -> str | None:
+ """The branch the agent must not commit directly onto (passed to the agent-server as --baseBranch).
+
+ The task's working branch is normally the PR base it was started from, so protecting it is correct.
+ But when the working branch itself heads an open PR — e.g. a quick action started on an existing
+ posthog-code/* branch the agent is meant to update — the agent must commit *to* that branch, so the
+ protected base is the PR's own base instead. Without this the signed-commit guard refuses the very
+ branch the run needs to update. Best-effort: any failure falls back to the working branch.
+ """
+ branch = ctx.branch
+ if not branch or not ctx.repository or not ctx.has_github_credentials:
+ return branch
+
+ try:
+ integration: GitHubIntegration | UserGitHubIntegration
+ if ctx.github_integration_id:
+ integration = GitHubIntegration(Integration.objects.get(id=ctx.github_integration_id))
+ if integration.access_token_expired():
+ integration.refresh_access_token()
+ else:
+ integration = UserGitHubIntegration(UserIntegration.objects.get(id=str(ctx.github_user_integration_id)))
+ pr_base = integration.get_open_pr_base_for_head(ctx.repository, branch)
+ except Exception:
+ logger.warning("resolve_protected_base_branch_failed", task_id=ctx.task_id, run_id=ctx.run_id, exc_info=True)
+ return branch
+
+ if pr_base and pr_base != branch:
+ emit_agent_log(
+ ctx.run_id,
+ "debug",
+ f"Working branch '{branch}' heads an open PR; protecting its base '{pr_base}' so commits to "
+ f"'{branch}' are allowed",
+ )
+ return pr_base
+ return branch
+
+
@dataclass
class StartAgentServerInput:
context: TaskProcessingContext
@@ -216,6 +256,8 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
f"Sandbox environment '{environment_name}' grants full network access; starting without agentsh restrictions",
)
+ protected_base_branch = _resolve_protected_base_branch(ctx)
+
try:
sandbox.start_agent_server(
repository=ctx.repository,
@@ -224,7 +266,7 @@ def start_agent_server(input: StartAgentServerInput) -> StartAgentServerOutput:
mode=ctx.mode,
create_pr=ctx.create_pr,
interaction_origin=ctx.interaction_origin,
- branch=ctx.branch,
+ branch=protected_base_branch,
runtime_adapter=ctx.runtime_adapter,
provider=ctx.provider,
model=ctx.model,
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
index eacfb735e9a1..839303b79318 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
@@ -1,22 +1,83 @@
+import pytest
+
from products.tasks.backend.temporal.process_task.activities.get_task_processing_context import TaskProcessingContext
from products.tasks.backend.temporal.process_task.activities.start_agent_server import (
StartAgentServerInput,
+ _resolve_protected_base_branch,
start_agent_server,
)
-def _context(*, sandbox_event_ingest_enabled: bool = False) -> TaskProcessingContext:
+def _context(
+ *,
+ sandbox_event_ingest_enabled: bool = False,
+ github_integration_id: int | None = None,
+ repository: str | None = None,
+ branch: str | None = None,
+) -> TaskProcessingContext:
return TaskProcessingContext(
task_id="task-id",
run_id="run-id",
team_id=1,
team_uuid="team-uuid",
organization_id="organization-id",
- github_integration_id=None,
- repository=None,
+ github_integration_id=github_integration_id,
+ repository=repository,
distinct_id="distinct-id",
sandbox_event_ingest_enabled=sandbox_event_ingest_enabled,
+ _branch=branch,
+ )
+
+
+def _mock_github_integration(mocker, pr_base: str | None):
+ integration = mocker.Mock()
+ integration.access_token_expired.return_value = False
+ integration.get_open_pr_base_for_head.return_value = pr_base
+ mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server.Integration.objects.get",
+ return_value=mocker.Mock(),
+ )
+ mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server.GitHubIntegration",
+ return_value=integration,
+ )
+ return integration
+
+
+ "pr_base,branch,expected",
+ [
+ # Quick action started on an existing PR head: protect the PR's base, not the head.
+ ("master", "posthog-code/ci-test-break", "master"),
+ # New task started off a base branch: keep protecting it (the agent branches off it).
+ (None, "release/direct-upload", "release/direct-upload"),
+ # No working branch: nothing to protect.
+ (None, None, None),
+ ],
+)
+def test_resolve_protected_base_branch(mocker, pr_base, branch, expected) -> None:
+ _mock_github_integration(mocker, pr_base=pr_base)
+ context = _context(github_integration_id=42, repository="PostHog/posthog", branch=branch)
+ assert _resolve_protected_base_branch(context) == expected
+
+
+def test_resolve_protected_base_skips_lookup_without_repository(mocker) -> None:
+ # Repo-less runs (e.g. Slack) must pass the branch through untouched, with no GitHub lookup.
+ get = mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server.Integration.objects.get",
+ )
+ context = _context(github_integration_id=42, repository=None, branch="some-branch")
+ assert _resolve_protected_base_branch(context) == "some-branch"
+ get.assert_not_called()
+
+
+def test_resolve_protected_base_falls_back_to_branch_on_error(mocker) -> None:
+ mocker.patch(
+ "products.tasks.backend.temporal.process_task.activities.start_agent_server.Integration.objects.get",
+ side_effect=RuntimeError("boom"),
)
+ context = _context(github_integration_id=42, repository="PostHog/posthog", branch="posthog-code/fix")
+ assert _resolve_protected_base_branch(context) == "posthog-code/fix"
async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(mocker) -> None: