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(signals): stop research runs claiming other people's PRs as the report's (#86477)

Andrew Maguire725b1e6f07cc
diff --git a/products/desktop/packages/agent/src/pr-url-detector.test.ts b/products/desktop/packages/agent/src/pr-url-detector.test.ts
index 90ca498f453e..196ef070023f 100644
--- a/products/desktop/packages/agent/src/pr-url-detector.test.ts
+++ b/products/desktop/packages/agent/src/pr-url-detector.test.ts
@@ -2,7 +2,9 @@ import { describe, expect, it } from "vitest";
import {
findPrUrl,
findPrUrls,
+ parsePrRepository,
wasCreatedByLogin,
+ wasCreatedByThisRun,
wasCreatedRecently,
} from "./pr-url-detector";
@@ -97,3 +99,110 @@ describe("wasCreatedRecently", () => {
expect(wasCreatedRecently("not-a-date", now, maxAge)).toBe(false);
});
});
+
+describe("parsePrRepository", () => {
+ it.each([
+ ["https://github.com/PostHog/posthog/pull/123", "posthog/posthog"],
+ ["https://github.com/PostHog/posthog.com/pull/1", "posthog/posthog.com"],
+ ["https://example.com/PostHog/posthog/pull/1", null],
+ ])("%s -> %s", (url, expected) => {
+ expect(parsePrRepository(url)).toBe(expected);
+ });
+});
+
+describe("wasCreatedByThisRun", () => {
+ const nowMs = new Date("2026-06-18T17:00:00Z").getTime();
+ const fresh = "2026-06-18T16:59:00Z";
+ const stale = "2026-06-18T12:00:00Z";
+ const ours = { repository: "posthog/posthog", branch: "run/branch" };
+ const base = {
+ createdAt: fresh,
+ nowMs,
+ author: "app/posthog",
+ ghLogin: null,
+ prRepository: "posthog/posthog",
+ headRefName: "run/branch",
+ isCrossRepository: false,
+ ownedBranches: [ours],
+ baseBranch: "master",
+ };
+
+ it.each([
+ ["fresh PR on a branch the run pushed", {}, true],
+ [
+ "fresh PR on another branch, run on master",
+ {
+ headRefName: "their/branch",
+ ownedBranches: [{ repository: "posthog/posthog", branch: "master" }],
+ },
+ false,
+ ],
+ [
+ "fresh PR whose head is the base branch",
+ {
+ headRefName: "master",
+ ownedBranches: [{ repository: "posthog/posthog", branch: "master" }],
+ },
+ false,
+ ],
+ ["fork PR with a matching branch name", { isCrossRepository: true }, false],
+ [
+ "same branch name in a different repository",
+ { prRepository: "posthog/posthog.com" },
+ false,
+ ],
+ [
+ "same branch name, run repository unknown",
+ { ownedBranches: [{ repository: null, branch: "run/branch" }] },
+ true,
+ ],
+ [
+ "branch pushed by signed commit, no checkout",
+ {
+ ownedBranches: [
+ { repository: "posthog/posthog", branch: "run/branch" },
+ ],
+ },
+ true,
+ ],
+ ["stale PR on the run's branch", { createdAt: stale }, false],
+ [
+ "fresh PR, no branches known, author matches login",
+ { headRefName: null, ownedBranches: [], ghLogin: "me", author: "me" },
+ true,
+ ],
+ [
+ "fresh PR, no branches known, author unknown",
+ { headRefName: null, ownedBranches: [] },
+ false,
+ ],
+ [
+ "fresh PR from another branch, author matches login",
+ { headRefName: "other/branch", ghLogin: "me", author: "me" },
+ false,
+ ],
+ [
+ "fresh PR, head known but no branches pushed, author matches login",
+ { ownedBranches: [], ghLogin: "me", author: "me" },
+ true,
+ ],
+ [
+ "fresh PR, only branches in other repositories known, author matches login",
+ {
+ ownedBranches: [
+ { repository: "posthog/posthog.com", branch: "run/branch" },
+ ],
+ ghLogin: "me",
+ author: "me",
+ },
+ true,
+ ],
+ [
+ "fresh fork PR, author matches login",
+ { isCrossRepository: true, ghLogin: "me", author: "me" },
+ false,
+ ],
+ ] as const)("%s -> %s", (_name, overrides, expected) => {
+ expect(wasCreatedByThisRun({ ...base, ...overrides })).toBe(expected);
+ });
+});
diff --git a/products/desktop/packages/agent/src/pr-url-detector.ts b/products/desktop/packages/agent/src/pr-url-detector.ts
index 621c1d415a4d..eadb62eec247 100644
--- a/products/desktop/packages/agent/src/pr-url-detector.ts
+++ b/products/desktop/packages/agent/src/pr-url-detector.ts
@@ -32,3 +32,62 @@ export function wasCreatedRecently(
if (Number.isNaN(createdAt.getTime())) return false;
return createdAt.getTime() >= nowMs - maxAgeMs;
}
+
+// A branch this run pushed, as `owner/name` (lowercased) plus branch. `repository`
+// is null when the run knows its branch but not which remote it points at.
+export interface OwnedBranch {
+ repository: string | null;
+ branch: string;
+}
+
+export interface PrOwnershipEvidence {
+ createdAt: string | null | undefined;
+ nowMs: number;
+ author: string | null | undefined;
+ ghLogin: string | null | undefined;
+ // `owner/name` of the repository the PR lives in, lowercased, from its URL.
+ prRepository: string | null;
+ headRefName: string | null | undefined;
+ // True when the PR head lives in a fork. A fork's branch name is chosen by the
+ // fork owner, so it can never prove this run opened the PR.
+ isCrossRepository: boolean | null | undefined;
+ ownedBranches: readonly OwnedBranch[];
+ baseBranch?: string | null;
+}
+
+const PR_REPOSITORY_REGEX =
+ /^https:\/\/github\.com\/([^/\s"]+\/[^/\s"]+)\/pull\/\d+/;
+
+export function parsePrRepository(prUrl: string): string | null {
+ const match = PR_REPOSITORY_REGEX.exec(prUrl);
+ return match ? match[1].toLowerCase() : null;
+}
+
+// Whether a PR URL seen in the agent's output is a PR this run opened, rather than
+// one it read while checking GitHub for in-flight work. Recency is necessary but
+// never sufficient on its own: a research run listing open PRs sees every PR the
+// repo opened in the last few minutes. A fork PR never qualifies, because its head
+// branch name is chosen by the fork owner, and neither does a head ref equal to
+// the base branch, because a run sitting on the base cannot own a same-repo PR.
+//
+// With branch evidence on both sides (the PR's head, and branches this run pushed
+// in that repository) the branch decides: a match is ownership, a mismatch is a PR
+// the run only read, even when the author is this run's own login. On a desktop
+// run the login is the person's, who authors most PRs in the repo, so a fresh PR
+// of theirs from another branch would otherwise be re-attributed, which is the
+// bug this gate exists to stop. The author match is the fallback only when branch
+// evidence is missing on either side.
+export function wasCreatedByThisRun(evidence: PrOwnershipEvidence): boolean {
+ if (!wasCreatedRecently(evidence.createdAt, evidence.nowMs)) return false;
+ if (evidence.isCrossRepository) return false;
+ const { headRefName, baseBranch, prRepository } = evidence;
+ if (headRefName && baseBranch && headRefName === baseBranch) return false;
+ const comparable = evidence.ownedBranches.filter(
+ (owned) =>
+ !owned.repository || !prRepository || owned.repository === prRepository,
+ );
+ if (headRefName && comparable.length > 0) {
+ return comparable.some((owned) => owned.branch === headRefName);
+ }
+ return wasCreatedByLogin(evidence.author, evidence.ghLogin);
+}
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.ts
index 675273bb27a4..c794c2881378 100644
--- a/products/desktop/packages/agent/src/server/agent-server.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts
@@ -4114,10 +4114,17 @@ describe("AgentServer HTTP Mode", () => {
p: JwtPayload,
u: Record<string, unknown> | undefined,
): void;
- fetchPrAttribution(
- url: string,
- ): Promise<{ createdAt: string | null; author: string | null }>;
+ fetchPrAttribution(url: string): Promise<{
+ createdAt: string | null;
+ author: string | null;
+ headRefName: string | null;
+ isCrossRepository: boolean | null;
+ }>;
fetchGhLogin(): Promise<string | null>;
+ getCurrentCheckout(): Promise<{
+ repository: string | null;
+ branch: string;
+ } | null>;
detectedPrUrl: string | null;
posthogAPI: {
getTaskRun: ReturnType<typeof vi.fn>;
@@ -4128,17 +4135,25 @@ describe("AgentServer HTTP Mode", () => {
const justNow = () => new Date().toISOString();
const longAgo = "2020-01-01T00:00:00Z";
const GH_LOGIN = "run-owner";
+ const RUN_BRANCH = "posthog-self-driving/fix-the-thing-ab12cd";
+ const RUN_REPOSITORY = "posthog/posthog.com";
+ const RUN_CHECKOUT = { repository: RUN_REPOSITORY, branch: RUN_BRANCH };
const setup = (
prCreatedAt: string | null,
prAuthor: string | null = GH_LOGIN,
+ prHeadRefName: string | null = RUN_BRANCH,
+ isCrossRepository: boolean | null = false,
): PrTestServer => {
const s = createServer() as unknown as PrTestServer;
s.fetchPrAttribution = vi.fn(async () => ({
createdAt: prCreatedAt,
author: prAuthor,
+ headRefName: prHeadRefName,
+ isCrossRepository,
}));
s.fetchGhLogin = vi.fn(async () => GH_LOGIN);
+ s.getCurrentCheckout = vi.fn(async () => RUN_CHECKOUT);
let storedOutput: Record<string, unknown> | null = null;
s.posthogAPI = {
getTaskRun: vi.fn(async () => ({ output: storedOutput })),
@@ -4214,6 +4229,8 @@ describe("AgentServer HTTP Mode", () => {
s.fetchPrAttribution = vi.fn(async (url: string) => ({
createdAt: url === PR_URL ? justNow() : longAgo,
author: GH_LOGIN,
+ headRefName: RUN_BRANCH,
+ isCrossRepository: false,
}));
s.maybeAttachCreatedPr(payload, terminalUpdate(PR_URL));
s.maybeAttachCreatedPr(payload, terminalUpdate(viewed));
@@ -4222,18 +4239,18 @@ describe("AgentServer HTTP Mode", () => {
expect(s.posthogAPI.updateTaskRun).toHaveBeenCalledTimes(1);
});
- it("does not attribute a fresh PR authored by someone else (merely viewed)", async () => {
- const s = setup(justNow(), "someone-else");
+ it("does not attribute a fresh PR authored by someone else from another branch (merely viewed)", async () => {
+ const s = setup(justNow(), "someone-else", "someone-elses-branch");
s.maybeAttachCreatedPr(payload, terminalUpdate(PR_URL));
await flush();
expect(s.posthogAPI.updateTaskRun).not.toHaveBeenCalled();
expect(s.detectedPrUrl).toBeNull();
});
- it("attributes a recent PR when the identity is a GitHub App installation (gh api user unavailable)", async () => {
+ it("attributes a recent PR on the run's branch when the identity is a GitHub App installation (gh api user unavailable)", async () => {
// Cloud runs authenticate with a GitHub App installation token, for which
// `gh api user` returns 403 → ghLogin is null. The PR is authored by the
- // app bot (e.g. "app/posthog"); recency alone must carry attribution.
+ // app bot (e.g. "app/posthog"); the head-branch match carries attribution.
const s = setup(justNow(), "app/posthog");
s.fetchGhLogin = vi.fn(async () => null);
s.maybeAttachCreatedPr(payload, terminalUpdate(PR_URL));
@@ -4244,6 +4261,74 @@ describe("AgentServer HTTP Mode", () => {
expect(s.detectedPrUrl).toBe(PR_URL);
});
+ it("does not attribute a fresh PR from another branch that a run on the base branch listed", async () => {
+ // A research run sits on master and runs `gh pr list` to look for in-flight
+ // work. Every PR opened in the last few minutes scrolls past it; none is its own.
+ const s = setup(justNow(), "app/posthog", "someone/feature-branch");
+ s.fetchGhLogin = vi.fn(async () => null);
+ s.getCurrentCheckout = vi.fn(async () => ({
+ repository: RUN_REPOSITORY,
+ branch: "master",
+ }));
+ s.maybeAttachCreatedPr(payload, terminalUpdate(PR_URL));
+ await flush();
+ expect(s.posthogAPI.updateTaskRun).not.toHaveBeenCalled();
+ expect(s.detectedPrUrl).toBeNull();
+ });
+
+ it("does not attribute a fresh PR when neither the branch nor the identity can be resolved", async () => {
+ const s = setup(justNow(), "app/posthog", null);
+ s.fetchGhLogin = vi.fn(async () => null);
+ s.getCurrentCheckout = vi.fn(async () => null);
+ s.maybeAttachCreatedPr(payload, terminalUpdate(PR_URL));
+ await flush();
+ expect(s.posthogAPI.updateTaskRun).not.toHaveBeenCalled();
+ });
+
+ it("does not attribute a fork PR whose head branch name matches the run's branch", async () => {
+ // A fork owner picks the branch name, so a matching name proves nothing.
+ const s = setup(justNow(), "someone-else", RUN_BRANCH, true);
+ s.fetchGhLogin = vi.fn(async () => null);
+ s.maybeAttachCreatedPr(payload, terminalUpdate(PR_URL));
+ await flush();
+ expect(s.posthogAPI.updateTaskRun).not.toHaveBeenCalled();
+ expect(s.detectedPrUrl).toBeNull();
+ });
+
+ it("attributes a PR on a branch the run pushed by signed commit when it has no checkout (no-repository mode)", async () => {
+ const s = setup(justNow(), "app/posthog");
+ s.fetchGhLogin = vi.fn(async () => null);
+ s.getCurrentCheckout = vi.fn(async () => null);
+ s.posthogAPI.getTaskRun = vi.fn(async () => ({
+ output: {
+ head_branches: [{ repository: RUN_REPOSITORY, branch: RUN_BRANCH }],
+ },
+ }));
+ s.maybeAttachCreatedPr(payload, terminalUpdate(PR_URL));
+ await flush();
+ expect(s.posthogAPI.updateTaskRun).toHaveBeenCalledTimes(1);
+ expect(s.detectedPrUrl).toBe(PR_URL);
+ });
+
+ it("does not attribute a fresh PR the run's own identity opened from a branch the run never pushed", async () => {
+ // On a desktop run the login is the person's, and they author most PRs in
+ // the repo. A known branch mismatch outranks the author match.
+ const s = setup(justNow(), GH_LOGIN, "another-branch-of-theirs");
+ s.maybeAttachCreatedPr(payload, terminalUpdate(PR_URL));
+ await flush();
+ expect(s.posthogAPI.updateTaskRun).not.toHaveBeenCalled();
+ expect(s.detectedPrUrl).toBeNull();
+ });
+
+ it("falls back to the author match when the run has no branch evidence", async () => {
+ const s = setup(justNow(), GH_LOGIN, "branch-we-cannot-see");
+ s.getCurrentCheckout = vi.fn(async () => null);
+ s.maybeAttachCreatedPr(payload, terminalUpdate(PR_URL));
+ await flush();
+ expect(s.posthogAPI.updateTaskRun).toHaveBeenCalledTimes(1);
+ expect(s.detectedPrUrl).toBe(PR_URL);
+ });
+
it("still rejects an old PR when the identity cannot be resolved (recency guards)", async () => {
const s = setup(longAgo, "app/posthog");
s.fetchGhLogin = vi.fn(async () => null);
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index 1e132cf5a377..8d52be087928 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -15,7 +15,7 @@ import {
} from "@agentclientprotocol/sdk";
import { type ServerType, serve } from "@hono/node-server";
import { execGh } from "@posthog/git/gh";
-import { getCurrentBranch } from "@posthog/git/queries";
+import { getCurrentBranch, getRemoteUrl } from "@posthog/git/queries";
import { ghTokenEnv } from "@posthog/git/signed-commit";
import {
type Adapter,
@@ -79,8 +79,9 @@ import {
} from "../posthog-exec-permission";
import {
findPrUrls,
- wasCreatedByLogin,
- wasCreatedRecently,
+ type OwnedBranch,
+ parsePrRepository,
+ wasCreatedByThisRun,
} from "../pr-url-detector";
import {
formatConversationForResume,
@@ -442,6 +443,56 @@ export function codexAuthFromGatewayEnv(env: GatewayEnv): {
return { apiBaseUrl: env.openaiBaseUrl, apiKey: env.openaiApiKey };
}
+interface PrAttribution {
+ createdAt: string | null;
+ author: string | null;
+ headRefName: string | null;
+ isCrossRepository: boolean | null;
+}
+
+const GITHUB_REMOTE_REGEX = /github\.com[:/]([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i;
+
+export function parseGithubRemoteRepository(
+ remoteUrl: string | null | undefined,
+): string | null {
+ if (!remoteUrl) return null;
+ const match = GITHUB_REMOTE_REGEX.exec(remoteUrl.trim());
+ return match ? match[1].toLowerCase() : null;
+}
+
+// Branches the run has pushed, as recorded on its task run by signed commits
+// (`output.head_branches`, per repository) and by the branch sync
+// (`output.head_branch`, repository unknown). This is what proves ownership when
+// the agent-server has no checkout of its own, as in no-repository mode.
+export function ownedBranchesFromOutput(
+ output: Record<string, unknown> | null | undefined,
+): OwnedBranch[] {
+ if (!output) return [];
+ const owned: OwnedBranch[] = [];
+ const listed = output.head_branches;
+ if (Array.isArray(listed)) {
+ for (const entry of listed) {
+ if (!entry || typeof entry !== "object") continue;
+ const { repository, branch } = entry as {
+ repository?: unknown;
+ branch?: unknown;
+ };
+ if (typeof branch !== "string" || !branch) continue;
+ owned.push({
+ repository:
+ typeof repository === "string" && repository
+ ? repository.trim().toLowerCase()
+ : null,
+ branch,
+ });
+ }
+ }
+ if (typeof output.head_branch === "string" && output.head_branch) {
+ owned.push({ repository: null, branch: output.head_branch });
+ }
+ return owned;
+}
+
export class AgentServer {
private config: AgentServerConfig;
private sessionReadyBootMs?: number;
@@ -4096,6 +4147,25 @@ ${commonInstructions}
}
}
+ // The checked-out branch and the GitHub repository its `origin` points at, or
+ // null without a checkout (no-repository mode) or on a detached HEAD.
+ private async getCurrentCheckout(): Promise<OwnedBranch | null> {
+ const branch = await this.getCurrentGitBranch();
+ if (!branch || !this.config.repositoryPath) return null;
+ let repository: string | null = null;
+ try {
+ repository = parseGithubRemoteRepository(
+ await getRemoteUrl(this.config.repositoryPath),
+ );
+ } catch (error) {
+ this.logger.debug("Failed to determine git origin", {
+ repositoryPath: this.config.repositoryPath,
+ error,
+ });
+ }
+ return { repository, branch };
+ }
+
private async syncCloudBranchMetadata(payload: JwtPayload): Promise<void> {
const branchName = await this.getCurrentGitBranch();
if (!branchName || branchName === this.lastReportedBranch) {
@@ -4786,12 +4856,19 @@ ${commonInstructions}
// Already the attributed PR (e.g. seeded from a Slack notification, or re-detected).
if (prUrl === this.detectedPrUrl) return;
- let attribution: { createdAt: string | null; author: string | null };
+ let attribution: PrAttribution;
let ghLogin: string | null;
+ let checkout: OwnedBranch | null;
+ let freshOutput: Record<string, unknown> | null;
try {
- [attribution, ghLogin] = await Promise.all([
+ [attribution, ghLogin, checkout, freshOutput] = await Promise.all([
this.fetchPrAttribution(prUrl),
this.fetchGhLogin(),
+ this.getCurrentCheckout(),
+ this.posthogAPI
+ .getTaskRun(payload.task_id, payload.run_id)
+ .then((run) => run.output ?? null)
+ .catch(() => null),
]);
} catch (err) {
this.logger.debug("PR attribution lookup failed", {
@@ -4802,21 +4879,45 @@ ${commonInstructions}
return;
}
- // Only attribute PRs created during this run — not ones the agent merely
- // viewed. GitHub App installation tokens (all cloud runs) can't read
- // `gh api user`, so ghLogin is null there; enforce the author match only when
- // we resolved our own identity, otherwise the recency gate alone scopes
- // attribution to PRs created during this run.
- if (!wasCreatedRecently(attribution.createdAt, Date.now())) return;
- if (ghLogin && !wasCreatedByLogin(attribution.author, ghLogin)) return;
+ const ownedBranches = [
+ ...(checkout ? [checkout] : []),
+ ...ownedBranchesFromOutput(freshOutput),
+ ];
+ // GitHub App installation tokens (all cloud runs) can't read `gh api user`, so
+ // ghLogin is null there and the head-branch match is what proves ownership.
+ const owned = wasCreatedByThisRun({
+ createdAt: attribution.createdAt,
+ nowMs: Date.now(),
+ author: attribution.author,
+ ghLogin,
+ prRepository: parsePrRepository(prUrl),
+ headRefName: attribution.headRefName,
+ isCrossRepository: attribution.isCrossRepository,
+ ownedBranches,
+ baseBranch: this.config.baseBranch ?? null,
+ });
+ if (!owned) {
+ // Info, not debug: a wrongly rejected PR leaves the run with no PR until the
+ // webhook backstop binds it, and this line is the only trace of why.
+ this.logger.info(
+ "PR seen in output is not this run's, skipping attribution",
+ {
+ runId: payload.run_id,
+ prUrl,
+ createdAt: attribution.createdAt,
+ author: attribution.author,
+ ghLogin,
+ headRefName: attribution.headRefName,
+ isCrossRepository: attribution.isCrossRepository,
+ ownedBranches,
+ },
+ );
+ return;
+ }
this.detectedPrUrl = prUrl;
try {
- const freshOutput = await this.posthogAPI
- .getTaskRun(payload.task_id, payload.run_id)
- .then((run) => run.output)
- .catch(() => null);
const urls = mergePrUrls(readPrUrls(freshOutput), [prUrl]);
await this.posthogAPI.updateTaskRun(payload.task_id, payload.run_id, {
output: buildPrOutput(freshOutput, urls),
@@ -4845,29 +4946,46 @@ ${commonInstructions}
return token === undefined ? undefined : ghTokenEnv(token);
}
- private async fetchPrAttribution(
- prUrl: string,
- ): Promise<{ createdAt: string | null; author: string | null }> {
+ private async fetchPrAttribution(prUrl: string): Promise<PrAttribution> {
+ const unknown: PrAttribution = {
+ createdAt: null,
+ author: null,
+ headRefName: null,
+ isCrossRepository: null,
+ };
const res = await execGh(
- ["pr", "view", prUrl, "--json", "createdAt,author"],
+ [
+ "pr",
+ "view",
+ prUrl,
+ "--json",
+ "createdAt,author,headRefName,isCrossRepository",
+ ],
{
cwd: this.config.repositoryPath,
timeoutMs: 10_000,
env: this.ghActorEnv(),
},
);
- if (res.exitCode !== 0) return { createdAt: null, author: null };
+ if (res.exitCode !== 0) return unknown;
try {
const data = JSON.parse(res.stdout) as {
createdAt?: string;
author?: { login?: string };
+ headRefName?: string;
+ isCrossRepository?: boolean;
};
return {
createdAt: data.createdAt ?? null,
author: data.author?.login ?? null,
+ headRefName: data.headRefName ?? null,
+ isCrossRepository:
+ typeof data.isCrossRepository === "boolean"
+ ? data.isCrossRepository
+ : null,
};
} catch {
- return { createdAt: null, author: null };
+ return unknown;
}
}
diff --git a/products/signals/backend/implementation_pr.py b/products/signals/backend/implementation_pr.py
index 6a7b6b282af0..352bed8de3ea 100644
--- a/products/signals/backend/implementation_pr.py
+++ b/products/signals/backend/implementation_pr.py
@@ -3,13 +3,19 @@
from dataclasses import dataclass
from typing import Literal, cast
+from django.db.models import Q
+
import structlog
from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.models.integration import GitHubIntegration
from products.signals.backend.models import SignalReport
-from products.signals.backend.task_run_artefacts import SIGNALS_PRODUCT, TASK_RUN_TYPE_IMPLEMENTATION
+from products.signals.backend.task_run_artefacts import (
+ NON_PR_BEARING_TASK_RUN_TYPES,
+ SIGNALS_PRODUCT,
+ TASK_RUN_TYPE_IMPLEMENTATION,
+)
from products.tasks.backend.facade import api as tasks_facade
logger = structlog.get_logger(__name__)
@@ -31,12 +37,17 @@ def fetch_implementation_pr_state_for_reports(report_ids: list[str]) -> dict[str
the facade then resolves the latest PR-bearing run for each task, so multiple runs of a task
collapse to the newest PR.
- Every signals task associated with the report is a candidate, not just the `implementation`
+ Every code-shipping signals task associated with the report is a candidate, not just the `implementation`
ones: a task started from the inbox's "Discuss" button runs the same agent against the same
repo, so it can push a branch and open a PR too, and that PR is the report's PR as much as an
auto-started one is. Implementation tasks are still consulted first, so a report that has both
surfaces exactly what it surfaced before.
+ Research, repo-selection, and scout runs are never candidates (`NON_PR_BEARING_TASK_RUN_TYPES`):
+ they read other people's PRs while checking for in-flight work, and a PR URL recorded on one of
+ them is a PR the agent saw, not one it opened. Surfacing it would label a stranger's PR as the
+ report's, and `close_implementation_pr_for_report` would then close it on dismissal.
+
A report can be associated with several tasks (retries, plus any discussion), but only one PR is
surfaced — the first candidate that has one. The merge flag is read from *that* task, so the URL
and its state always describe the same PR. Reading them independently would let a retry's merged
@@ -56,6 +67,7 @@ def fetch_implementation_pr_state_for_reports(report_ids: list[str]) -> dict[str
for report_id, runs in runs_by_report.items()
# Stable sort, so implementation tasks lead and each group keeps its oldest-first order.
for run in sorted(runs, key=lambda run: run.type != TASK_RUN_TYPE_IMPLEMENTATION)
+ if run.type not in NON_PR_BEARING_TASK_RUN_TYPES
]
if not pairs:
return {}
@@ -72,6 +84,19 @@ def fetch_implementation_pr_state_for_reports(report_ids: list[str]) -> dict[str
return result
+def pr_bearing_task_run_filter() -> Q:
+ """SQL counterpart of the `NON_PR_BEARING_TASK_RUN_TYPES` exclusion, as a `Q` on `tasks.TaskRun`.
+
+ The run type lives in artefact JSON the SQL path deliberately doesn't cast, so this keys on the
+ `state.ai_stage` stamp the pipeline writes at run creation, which carries the same names
+ (`research`, `repo_selection`, `scout:<skill>`). Runs without a stamp pass, matching the Python
+ path, where an unlabelled legacy association is a candidate.
+ """
+ return Q(state__ai_stage__isnull=True) | (
+ ~Q(state__ai_stage__in=sorted(NON_PR_BEARING_TASK_RUN_TYPES)) & ~Q(state__ai_stage__startswith="scout:")
+ )
+
+
def fetch_implementation_pr_urls_for_reports(report_ids: list[str]) -> dict[str, str]:
"""PR URL from the latest PR-bearing task run for each report, when available."""
return {report_id: pr.url for report_id, pr in fetch_implementation_pr_state_for_reports(report_ids).items()}
diff --git a/products/signals/backend/task_run_artefacts.py b/products/signals/backend/task_run_artefacts.py
index 136e10e00386..b32a46a9bfe9 100644
--- a/products/signals/backend/task_run_artefacts.py
+++ b/products/signals/backend/task_run_artefacts.py
@@ -63,6 +63,12 @@ _PIPELINE_TASK_RUN_TYPES = frozenset(
{TASK_RUN_TYPE_IMPLEMENTATION, TASK_RUN_TYPE_RESEARCH, TASK_RUN_TYPE_REPO_SELECTION, TASK_RUN_TYPE_SCOUT}
)
+# Pipeline runs that never open a PR for the report. Research and repo-selection runs sit on the
+# base branch and read other people's PRs while checking for in-flight work, so a PR URL on one of
+# their runs is something the agent looked at, not something it shipped. Kept as a denylist so a
+# new run type that does ship code (a report is expected to grow several PRs) counts by default.
+NON_PR_BEARING_TASK_RUN_TYPES = frozenset({TASK_RUN_TYPE_RESEARCH, TASK_RUN_TYPE_REPO_SELECTION, TASK_RUN_TYPE_SCOUT})
+
_TERMINAL_NO_PR_RUN_STATUSES = frozenset({"failed", "cancelled"})
_GITHUB_PR_URL_PREFIX = "https://github.com/"
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index a4567228f696..4d3d64f040d8 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -39,6 +39,9 @@ from products.signals.backend.signal_metadata import ReportSignalMeta
from products.signals.backend.task_run_artefacts import (
TASK_RUN_TYPE_DISCUSSION,
TASK_RUN_TYPE_IMPLEMENTATION,
+ TASK_RUN_TYPE_REPO_SELECTION,
+ TASK_RUN_TYPE_RESEARCH,
+ TASK_RUN_TYPE_SCOUT,
append_task_run_artefact,
record_implementation_task,
record_report_task,
@@ -586,6 +589,7 @@ class TestSignalReportListAPI(APIBaseTest):
pr_url: str | None = None,
output: dict | None = None,
relationship: str = TASK_RUN_TYPE_IMPLEMENTATION,
+ state: dict | None = None,
) -> "tuple[Task, TaskRun]":
Task = apps.get_model("tasks", "Task")
TaskRun = apps.get_model("tasks", "TaskRun")
@@ -607,6 +611,7 @@ class TestSignalReportListAPI(APIBaseTest):
task=task,
status=TaskRun.Status.COMPLETED,
output=run_output,
+ state=state or {},
)
return task, run
@@ -704,6 +709,51 @@ class TestSignalReportListAPI(APIBaseTest):
assert row["implementation_pr_url"] == expected_url
+ @parameterized.expand(
+ [
+ ("research", TASK_RUN_TYPE_RESEARCH, "research"),
+ ("repo_selection", TASK_RUN_TYPE_REPO_SELECTION, "repo_selection"),
+ ("scout", TASK_RUN_TYPE_SCOUT, "scout:some-skill"),
+ ]
+ )
+ def test_implementation_pr_url_ignores_pr_recorded_on_non_code_run(self, _name, relationship, ai_stage):
+ # A research run checks GitHub for in-flight work and the agent-server can record a PR it
+ # merely read as the run's own. That must never surface as the report's PR, on the list, the
+ # detail view, or the "has PR" filter the Pull requests tab counts.
+ report = self._create_report()
+ self._create_implementation_task_with_run(
+ report,
+ pr_url="https://github.com/o/r/pull/99",
+ relationship=relationship,
+ state={"ai_stage": ai_stage},
+ )
+
+ row = next(r for r in self.client.get(self._list_url()).json()["results"] if r["id"] == str(report.id))
+ detail = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{report.id}/").json()
+ with_pr = self.client.get(self._list_url(has_implementation_pr="true")).json()
+
+ assert row["implementation_pr_url"] is None
+ assert detail["implementation_pr_url"] is None
+ assert with_pr["count"] == 0
+
+ def test_implementation_pr_url_prefers_real_pr_over_one_read_by_research(self):
+ report = self._create_report()
+ self._create_implementation_task_with_run(
+ report,
+ pr_url="https://github.com/o/r/pull/99",
+ relationship=TASK_RUN_TYPE_RESEARCH,
+ state={"ai_stage": "research"},
+ )
+ self._create_implementation_task_with_run(
+ report, pr_url="https://github.com/o/r/pull/100", state={"ai_stage": "implementation"}
+ )
+
+ row = next(r for r in self.client.get(self._list_url()).json()["results"] if r["id"] == str(report.id))
+ with_pr = self.client.get(self._list_url(has_implementation_pr="true")).json()
+
+ assert row["implementation_pr_url"] == "https://github.com/o/r/pull/100"
+ assert with_pr["count"] == 1
+
@parameterized.expand(
[
# The badge reads this flag, so it must track the webhook's merge record rather than the
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index ed84d0482567..c6e1f2f2533a 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -94,6 +94,7 @@ from products.signals.backend.feedback_notes import forward_feedback_note
from products.signals.backend.implementation_pr import (
fetch_implementation_pr_state_for_reports,
fetch_implementation_pr_urls_for_reports,
+ pr_bearing_task_run_filter,
)
from products.signals.backend.models import (
ArtefactAttribution,
@@ -1002,7 +1003,9 @@ class SignalReportViewSet(
# `pr_url` and maps them to reports via the indexed `task_id` columns — instead of a correlated
# `Exists` over `tasks.TaskRun` evaluated once per candidate report (which made the inbox
# PR-tab count scan the whole `ready` set per PR'd run).
- return SignalReport.reports_for_task_ids_filter(tasks_facade.task_ids_with_pr_url_subquery(self.team.id))
+ return SignalReport.reports_for_task_ids_filter(
+ tasks_facade.task_ids_with_pr_url_subquery(self.team.id, pr_bearing_task_run_filter())
+ )
def _apply_signal_report_implementation_pr_filter(self, queryset):
# `has_implementation_pr=true|false` filters reports by whether a shipped
@@ -1248,10 +1251,12 @@ class SignalReportViewSet(
# task" to the one that opened the report's PR.
latest_impl_pr_url = tasks_facade.latest_task_run_pr_url_subquery(
SignalReport.associated_task_runs_filter(OuterRef(OuterRef("id"))),
+ pr_bearing_task_run_filter(),
)
# Resolved over the same run, so the merge flag always describes the PR URL alongside it.
latest_impl_pr_merged = tasks_facade.latest_task_run_pr_merged_subquery(
SignalReport.associated_task_runs_filter(OuterRef(OuterRef("id"))),
+ pr_bearing_task_run_filter(),
)
return queryset.annotate(
implementation_pr_url=latest_impl_pr_url,
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index a3dfe49b08a7..b34af8dcfa7f 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -892,8 +892,9 @@ def get_latest_pr_url_by_task(task_ids: Iterable[str | UUID]) -> dict[str, str]:
return {str(row["task_id"]): row["output_pr_url_text"] for row in rows if row["output_pr_url_text"]}
-def task_ids_with_pr_url_subquery(team_id: int) -> QuerySet[TaskRun, Any]:
- """A ``values('task_id')`` queryset of ``team_id``'s tasks that produced a non-empty ``output.pr_url``.
+def task_ids_with_pr_url_subquery(team_id: int, *conditions: Q) -> QuerySet[TaskRun, Any]:
+ """A ``values('task_id')`` queryset of ``team_id``'s tasks that produced a non-empty ``output.pr_url``,
+ narrowed by any extra ``Q`` ``conditions`` on the run.
For embedding in a caller's ``task_id__in=...`` lookup so the report→PR correlation can be
*decorrelated*: instead of a per-report ``Exists`` over runs, the caller drives off this small,
@@ -904,7 +905,7 @@ def task_ids_with_pr_url_subquery(team_id: int) -> QuerySet[TaskRun, Any]:
team's PR-bearing runs — associated runs are always same-team, so this drops no valid matches.
"""
return (
- TaskRun.objects.filter(team_id=team_id, output__pr_url__isnull=False)
+ TaskRun.objects.filter(*conditions, team_id=team_id, output__pr_url__isnull=False)
.exclude(output__pr_url="")
.values("task_id")
)