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): bind PRs from signed commit branches (#80502)

Alessandro Pogliaghia4cb2071b307
diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-commit.test.ts b/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-commit.test.ts
index 5502dacd3be7..0db78612d1e5 100644
--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-commit.test.ts
+++ b/products/desktop/packages/agent/src/adapters/local-tools/tools/signed-commit.test.ts
@@ -113,7 +113,9 @@ describe("signed-commit tool handler", () => {
expect(reportTaskRunBranch).toHaveBeenCalledWith({
taskId: "task-1",
taskRunId: "run-1",
+ repository: "x/y",
branch: "posthog-code/feature",
+ updateCheckoutBranch: true,
});
});
@@ -131,11 +133,13 @@ describe("signed-commit tool handler", () => {
expect(reportTaskRunBranch).toHaveBeenCalledWith({
taskId: "task-1",
taskRunId: "run-1",
+ repository: "x/y",
branch: "posthog-code/feature",
+ updateCheckoutBranch: true,
});
});
- it("does not persist a branch created in a sibling repository", async () => {
+ it("reports a sibling repository branch without changing the checkout branch", async () => {
await signedCommitTool.handler(
{
cwd: "/tmp/workspace/repos/posthog/code",
@@ -149,7 +153,13 @@ describe("signed-commit tool handler", () => {
},
);
- expect(reportTaskRunBranch).not.toHaveBeenCalled();
+ expect(reportTaskRunBranch).toHaveBeenCalledWith({
+ taskId: "task-1",
+ taskRunId: "run-1",
+ repository: "x/y",
+ branch: "posthog-code/feature",
+ updateCheckoutBranch: false,
+ });
});
it("returns the no-token error without invoking createSignedCommit", async () => {
diff --git a/products/desktop/packages/agent/src/adapters/signed-commit-shared.ts b/products/desktop/packages/agent/src/adapters/signed-commit-shared.ts
index 2cdd83eb7d24..3c898937c22b 100644
--- a/products/desktop/packages/agent/src/adapters/signed-commit-shared.ts
+++ b/products/desktop/packages/agent/src/adapters/signed-commit-shared.ts
@@ -184,13 +184,16 @@ export function runSignedCommitTool(
// repository on resume. A task can also commit to sibling repositories by
// passing `cwd`; persisting one of those branches here makes the next run
// try to clone the task repository at a branch that only exists elsewhere.
- if (ctx.cwd === ctx.taskRepositoryCwd) {
- await reportTaskRunBranch({
- taskId: ctx.taskId,
- taskRunId: ctx.taskRunId,
- branch: result.branch,
- });
- }
+ await reportTaskRunBranch({
+ taskId: ctx.taskId,
+ taskRunId: ctx.taskRunId,
+ repository: result.repository,
+ branch: result.branch,
+ // Only the task repository branch controls the next checkout. The
+ // reported head branch still lets PR webhooks bind commits made from a
+ // workspace root or a sibling repository to this run.
+ updateCheckoutBranch: ctx.cwd === ctx.taskRepositoryCwd,
+ });
// The "commit hook": every pushed commit becomes a `commit` artefact on the signal
// reports this task is associated with. Best-effort and awaited inside the tool's
// try/catch-free success path — reportCommitArtefacts never throws, so a failed
diff --git a/products/desktop/packages/agent/src/signed-commit-artefacts.test.ts b/products/desktop/packages/agent/src/signed-commit-artefacts.test.ts
index e05b2641530e..827796b09b79 100644
--- a/products/desktop/packages/agent/src/signed-commit-artefacts.test.ts
+++ b/products/desktop/packages/agent/src/signed-commit-artefacts.test.ts
@@ -372,6 +372,7 @@ describe("reportTaskRunBranch", () => {
await reportTaskRunBranch({
taskId: "task-1",
taskRunId: "run-1",
+ repository: "PostHog/PostHog",
branch: "posthog-code/fix-foo",
env: ENV,
envFilePath: NO_ENV_FILE,
@@ -387,7 +388,51 @@ describe("reportTaskRunBranch", () => {
method: "PATCH",
body: JSON.stringify({
branch: "posthog-code/fix-foo",
- output: { head_branch: "posthog-code/fix-foo" },
+ output: {
+ head_branch: "posthog-code/fix-foo",
+ head_branches: [
+ {
+ repository: "posthog/posthog",
+ branch: "posthog-code/fix-foo",
+ },
+ ],
+ },
+ }),
+ });
+ });
+
+ it("can report a PR head branch without changing the checkout branch", async () => {
+ fetchMock.mockResolvedValue(
+ new Response(JSON.stringify({}), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+
+ await reportTaskRunBranch({
+ taskId: "task-1",
+ taskRunId: "run-1",
+ repository: "PostHog/PostHog",
+ branch: "posthog-code/fix-foo",
+ updateCheckoutBranch: false,
+ env: ENV,
+ envFilePath: NO_ENV_FILE,
+ oauthEnvFilePath: TEST_OAUTH_ENV_FILE,
+ });
+
+ const [, init] = fetchMock.mock.calls[0];
+ expect(init).toMatchObject({
+ method: "PATCH",
+ body: JSON.stringify({
+ output: {
+ head_branch: "posthog-code/fix-foo",
+ head_branches: [
+ {
+ repository: "posthog/posthog",
+ branch: "posthog-code/fix-foo",
+ },
+ ],
+ },
}),
});
});
diff --git a/products/desktop/packages/agent/src/signed-commit-artefacts.ts b/products/desktop/packages/agent/src/signed-commit-artefacts.ts
index d5690d69489e..b5ce88a13085 100644
--- a/products/desktop/packages/agent/src/signed-commit-artefacts.ts
+++ b/products/desktop/packages/agent/src/signed-commit-artefacts.ts
@@ -141,7 +141,9 @@ export async function reportCommitArtefacts(opts: {
export async function reportTaskRunBranch(opts: {
taskId: string | undefined;
taskRunId: string | undefined;
+ repository: string;
branch: string;
+ updateCheckoutBranch?: boolean;
env?: Record<string, string | undefined>;
envFilePath?: string;
oauthEnvFilePath?: string;
@@ -159,8 +161,16 @@ export async function reportTaskRunBranch(opts: {
return;
}
await client.updateTaskRun(opts.taskId, opts.taskRunId, {
- branch: opts.branch,
- output: { head_branch: opts.branch },
+ ...(opts.updateCheckoutBranch !== false && { branch: opts.branch }),
+ output: {
+ head_branch: opts.branch,
+ head_branches: [
+ {
+ repository: opts.repository.trim().toLowerCase(),
+ branch: opts.branch,
+ },
+ ],
+ },
});
} catch (err) {
warn(`failed to attach branch ${opts.branch} to task run: ${err}`);
diff --git a/products/tasks/backend/pr_urls.py b/products/tasks/backend/pr_urls.py
index 26a4faf017b9..8ead88347405 100644
--- a/products/tasks/backend/pr_urls.py
+++ b/products/tasks/backend/pr_urls.py
@@ -9,9 +9,35 @@ def read_pr_urls(output: object) -> list[str]:
return list(dict.fromkeys(url for url in candidates if isinstance(url, str) and url))
+def read_head_branches(output: object) -> list[dict[str, str]]:
+ if not isinstance(output, dict):
+ return []
+
+ raw_branches = output.get("head_branches")
+ branches: list[object] = raw_branches if isinstance(raw_branches, list) else []
+ normalized: list[dict[str, str]] = []
+ seen: set[tuple[str, str]] = set()
+ for candidate in branches:
+ if not isinstance(candidate, dict):
+ continue
+ repository = candidate.get("repository")
+ branch = candidate.get("branch")
+ if not isinstance(repository, str) or not repository or not isinstance(branch, str) or not branch:
+ continue
+ pair = (repository.strip().lower(), branch)
+ if pair in seen:
+ continue
+ seen.add(pair)
+ normalized.append({"repository": pair[0], "branch": pair[1]})
+ return normalized
+
+
def merge_pr_output(existing: object, incoming: dict) -> dict:
current = existing if isinstance(existing, dict) else {}
merged = {**current, **incoming}
+ head_branches = [*read_head_branches(incoming), *read_head_branches(current)]
+ if head_branches:
+ merged["head_branches"] = read_head_branches({"head_branches": head_branches})
urls = list(dict.fromkeys([*read_pr_urls(incoming), *read_pr_urls(current)]))
if not urls:
return merged
diff --git a/products/tasks/backend/tests/test_pr_urls.py b/products/tasks/backend/tests/test_pr_urls.py
new file mode 100644
index 000000000000..60f6304b2bad
--- /dev/null
+++ b/products/tasks/backend/tests/test_pr_urls.py
@@ -0,0 +1,33 @@
+from products.tasks.backend.pr_urls import merge_pr_output, read_head_branches
+
+
+def test_merge_pr_output_preserves_distinct_head_branches() -> None:
+ existing = {
+ "head_branches": [{"repository": "posthog/posthog", "branch": "posthog-code/first"}],
+ }
+ incoming = {
+ "head_branches": [{"repository": "PostHog/Code", "branch": "posthog-code/second"}],
+ }
+
+ merged = merge_pr_output(existing, incoming)
+
+ assert merged["head_branches"] == [
+ {"repository": "posthog/code", "branch": "posthog-code/second"},
+ {"repository": "posthog/posthog", "branch": "posthog-code/first"},
+ ]
+
+
+def test_read_head_branches_deduplicates_normalized_pairs() -> None:
+ assert read_head_branches(
+ {
+ "head_branches": [
+ {"repository": " PostHog/PostHog ", "branch": "posthog-code/fix"},
+ {"repository": "posthog/posthog", "branch": "posthog-code/fix"},
+ {"repository": "posthog/posthog", "branch": "posthog-code/other"},
+ {"repository": "posthog/posthog"},
+ ]
+ }
+ ) == [
+ {"repository": "posthog/posthog", "branch": "posthog-code/fix"},
+ {"repository": "posthog/posthog", "branch": "posthog-code/other"},
+ ]
diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.py
index 8a7201af0440..afbcf88b6121 100644
--- a/products/tasks/backend/tests/test_webhooks.py
+++ b/products/tasks/backend/tests/test_webhooks.py
@@ -1101,6 +1101,43 @@ class TestFindTaskRun(TestCase):
result = find_task_run(branch="feature/my-branch", repository="posthog/posthog")
self.assertEqual(result, task_run)
+ def test_finds_by_signed_commit_head_branch(self):
+ task_run = TaskRun.objects.create(
+ task=self.task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ branch="master",
+ output={
+ "head_branch": "posthog-code/feature",
+ "head_branches": [{"repository": "posthog/posthog", "branch": "posthog-code/feature"}],
+ },
+ )
+ result = find_task_run(branch="posthog-code/feature", repository="posthog/posthog")
+ self.assertEqual(result, task_run)
+
+ def test_signed_commit_head_branch_requires_matching_repository(self):
+ TaskRun.objects.create(
+ task=self.task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ output={
+ "head_branch": "posthog-code/feature",
+ "head_branches": [{"repository": "posthog/posthog", "branch": "posthog-code/feature"}],
+ },
+ )
+ self.assertIsNone(find_task_run(branch="posthog-code/feature", repository="acme/other"))
+
+ def test_signed_commit_head_branch_requires_repository_pair(self):
+ TaskRun.objects.create(
+ task=self.task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ output={
+ "head_branches": [{"repository": "posthog/code", "branch": "posthog-code/feature"}],
+ },
+ )
+ self.assertIsNone(find_task_run(branch="posthog-code/feature", repository="posthog/posthog"))
+
def test_finds_multi_repository_run_from_snapshot(self):
self.task.repositories = ["posthog/posthog", "posthog/code"]
self.task.save(update_fields=["repositories"])
diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.py
index 6c1b74ebd43f..23bd3769c1b2 100644
--- a/products/tasks/backend/webhooks.py
+++ b/products/tasks/backend/webhooks.py
@@ -88,6 +88,22 @@ def find_task_run(
if task_run:
return task_run
+ # Signed commits report every pushed repository/branch pair separately
+ # from ``branch``. The latter controls provisioning's next checkout and
+ # cannot represent nested repositories or multiple PR branches.
+ head_branch = {"repository": repository.lower(), "branch": branch}
+ task_run = (
+ TaskRun.objects.filter(
+ _run_repository_filter(repository),
+ output__head_branches__contains=[head_branch],
+ state__wizard_head_branch__isnull=True,
+ )
+ .select_related(*TASK_RUN_SELECT_RELATED)
+ .first()
+ )
+ if task_run:
+ return task_run
+
# Wizard cloud runs push to a server-generated head branch stored in run state.
# The prefix check keeps this leg off the hot path for ordinary PR webhooks, and
# terminal runs are excluded so a reopened branch can't fire events on a dead run