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(signals): write an origin section into self-driving prs (#104017)

Julian Beza3386c380fa2
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index 8afed8e2e9cd..b923c78dcd93 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -1284,6 +1284,14 @@ Runs inside `maybe_autostart_implementation_task()` in `backend/auto_start.py`,
2. `record_implementation_task` writes the legacy `SignalReportTask` implementation gate row (in the same transaction) and appends an `implementation` `task_run` artefact
3. Errors are caught and logged but do not fail the report workflow
+**Origin section per pull request** (`backend/pr_origin.py`, always on).
+
+A reviewer needs to know where a self-driving pull request came from, not only the problem it fixes. The backend writes an `## Origin` section below the Problem section, so the agent cannot paraphrase it. The section lists the source types with PostHog entity links, the scout when it ships with PostHog, the first signal date, the inbox report, the likely cause commit from the newest `signal_finding` (linked only when the suggested reviewers carry it under the pull request's repository), and whether auto-start or a person started the run.
+
+Pull requests are often public, so the section renders an allowlist only. Signal content, ticket text, counts, sequential ticket numbers, custom scout names, and issue URLs outside the pull request's own repository never reach it. `fetch_origin_sources_for_report` aggregates in ClickHouse, so a large report returns a bounded result.
+
+The write edits only a pull request that the GitHub webhook confirmed in the run's `verified_pr_urls`, because a run's `output.pr_url` is writable through the API. An unconfirmed URL retries. HTML-comment markers per report let a retry replace the section in place, and an unmarked `## Origin` from a repository template stays untouched.
+
**Tracker issue per pull request** (`backend/tracker_issues.py`, off by default).
Some teams cannot merge a pull request unless a tracked work item points at it. `SignalTeamConfig.issue_tracking_integration` names the tracker (GitHub, GitLab, Linear, or Jira) and `issue_tracking_config` names the target inside it; a null integration means the team wants no tracker issues, so one field is both the switch and the target.
@@ -1292,7 +1300,7 @@ Some teams cannot merge a pull request unless a tracked work item points at it.
The create never raises. A provider failure is stored on the row as `status=failed` with a short reason, which the report surfaces next to the pull request, and the run opens its pull request either way.
-Once the pull request exists, `link_report_tracker_issues` (scheduled from the task-run PR sync receiver) appends the reference to the pull request body, behind an HTML-comment marker so the append happens once. GitHub gets `Closes #n`; the other providers get the issue link. A Linear issue also gets the pull request as an attachment, best effort, because the scope for it may not be granted.
+Once the pull request exists, `link_report_tracker_issues` (scheduled from the task-run PR sync receiver) writes the Origin section and then appends the reference to the pull request body, behind an HTML-comment marker so the append happens once. Both edits go through `edit_pull_request_body` in `backend/pull_request_body.py`, one after the other, so they never race on the body's etag. GitHub gets `Closes #n`; the other providers get the issue link. A Linear issue also gets the pull request as an attachment, best effort, because the scope for it may not be granted.
An irreversible end closes the tracker issue: a resolve asked for through the state API, a merged pull request (closed as done), or a deleted report. A suppressed or snoozed report keeps its issue open, because both come back, and so does a failed run, because its report stays in the inbox and the work item is still real.
diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.py
index 2a6dc7e08be0..02c32b74656a 100644
--- a/products/signals/backend/auto_start.py
+++ b/products/signals/backend/auto_start.py
@@ -237,6 +237,8 @@ _PR_DESCRIPTION_FORM_RULES = (
"- Cut what the diff shows, what the linked report already says, and all narration of how you "
"investigated. The report is the long form. What you tried and rejected goes under 'Agent "
"context', briefly.\n"
+ "- Do not write an 'Origin' section. PostHog adds one below Problem after the PR opens. When you "
+ "edit the description later, keep that section and its HTML comment markers exactly as they are.\n"
"- Before opening the PR, reread it: could a reviewer get the why, the what and the risk by "
"scanning it for about thirty seconds? If not, turn paragraphs into bullets and comparisons into "
"tables. Scannability is the target, not brevity, so a long body dense with tables and diagrams "
diff --git a/products/signals/backend/pr_origin.py b/products/signals/backend/pr_origin.py
new file mode 100644
index 000000000000..e85a26b609cd
--- /dev/null
+++ b/products/signals/backend/pr_origin.py
@@ -0,0 +1,408 @@
+"""The Origin section of a self-driving pull request.
+
+A self-driving pull request states the problem it fixes, but a reviewer also needs to know where
+the work came from: which error, ticket, or scout raised it, and whether a person or the automation
+started the run. The backend writes that section itself, below the Problem section, so that the
+agent cannot paraphrase it.
+
+Pull requests are often public. So the section carries only allowlisted facts: source types,
+entity links that need a PostHog login, dates, a commit hash, and the priority. It never carries
+signal content, ticket text, or volumes.
+"""
+
+from __future__ import annotations
+
+import re
+from bisect import bisect_right
+from datetime import date, datetime
+from typing import TypeVar
+
+from django.conf import settings
+
+import structlog
+from pydantic import BaseModel, ValidationError
+
+from posthog.dataclasses import frozen
+from posthog.models import Team
+
+from products.signals.backend.artefact_schemas import (
+ PriorityAssessment,
+ SignalFinding,
+ SuggestedReviewers,
+ TaskRunArtefact,
+)
+from products.signals.backend.enums import SIGNAL_SOURCE_PRODUCT_LABELS, SignalSourceProduct
+from products.signals.backend.models import SignalReportArtefact
+from products.signals.backend.pull_request_body import BodyEditOutcome, edit_pull_request_body
+from products.signals.backend.scout_harness.lazy_seed import canonical_skill_names
+from products.signals.backend.signal_metadata import (
+ OriginSource,
+ SignalSourceReference,
+ fetch_origin_sources_for_report,
+ fetch_source_references_for_report,
+)
+from products.tasks.backend.facade import api as tasks_facade
+
+logger = structlog.get_logger(__name__)
+
+ORIGIN_MARKER_PREFIX = "posthog-self-driving-origin"
+MAX_LINKS_PER_SOURCE = 5
+
+# Identifiers go into a URL path, so a signal with any other id keeps its source type but gets no link.
+_SOURCE_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
+_SOURCE_PRODUCT_RE = re.compile(r"^[a-z0-9_]{1,40}$")
+_COMMIT_SHA_RE = re.compile(r"^[0-9a-f]{7,40}$")
+_PROBLEM_HEADING_RE = re.compile(r"^##[ \t]+Problem[ \t]*$", re.MULTILINE | re.IGNORECASE)
+# A section ends at the next level-two heading, a horizontal rule, or a PostHog Origin block.
+_SECTION_END_RE = re.compile(rf"^(##[ \t]|---[ \t]*$|<!-- {ORIGIN_MARKER_PREFIX}:)", re.MULTILINE)
+
+# Linear and GitHub signals come from `fetch_source_references_for_report`, which already
+# validates their public links.
+_ISSUE_TRACKER_PRODUCTS = frozenset({"linear", "github"})
+
+ArtefactModel = TypeVar("ArtefactModel", bound=BaseModel)
+
+
+@frozen
+class EntityPage:
+ link_label: str
+ # Path under the project, with `{id}` for the entity.
+ path: str
+
+
+_ENTITY_PAGES: dict[str, EntityPage] = {
+ SignalSourceProduct.ERROR_TRACKING: EntityPage(link_label="issue", path="/error_tracking/{id}"),
+ SignalSourceProduct.SESSION_REPLAY: EntityPage(link_label="recording", path="/replay/{id}"),
+ SignalSourceProduct.CONVERSATIONS: EntityPage(link_label="ticket", path="/support/tickets/{id}"),
+}
+
+
+@frozen
+class OriginLink:
+ label: str
+ # None when only the label is safe to publish.
+ url: str | None
+
+ def render(self) -> str:
+ return f"[{self.label}]({self.url})" if self.url else self.label
+
+
+@frozen
+class OriginSourceLine:
+ label: str
+ links: tuple[OriginLink, ...]
+ has_more: bool
+
+ def render(self) -> str:
+ # Counts stay out, because the number of private recordings or tickets is itself private.
+ if not self.links:
+ return f"- {self.label}"
+ rendered = ", ".join(link.render() for link in self.links)
+ if self.has_more:
+ rendered = f"{rendered} and more"
+ return f"- {self.label}: {rendered}"
+
+
+def _source_label(source_product: str) -> str:
+ if source_product in SIGNAL_SOURCE_PRODUCT_LABELS:
+ return SIGNAL_SOURCE_PRODUCT_LABELS[SignalSourceProduct(source_product)]
+ if _SOURCE_PRODUCT_RE.match(source_product):
+ return source_product.replace("_", " ").capitalize()
+ return "Other"
+
+
+def _entity_link(team_id: int, source_product: str, entity_id: str, index: int, total: int) -> OriginLink | None:
+ page = _ENTITY_PAGES.get(source_product)
+ if page is None or not _SOURCE_ID_RE.match(entity_id):
+ return None
+ label = page.link_label if total == 1 else f"{page.link_label} {index}"
+ path = page.path.format(id=entity_id)
+ return OriginLink(label=label, url=f"{settings.SITE_URL}/project/{team_id}{path}")
+
+
+def _source_lines(team_id: int, sources: list[OriginSource]) -> list[OriginSourceLine]:
+ lines: list[OriginSourceLine] = []
+ for source in sources:
+ # A scout signal's source_id names the scout run, not an entity, so the scout line covers it.
+ if source.scout_name or source.source_product in _ISSUE_TRACKER_PRODUCTS:
+ continue
+ shown = source.entity_ids[:MAX_LINKS_PER_SOURCE]
+ links: list[OriginLink] = []
+ for index, entity_id in enumerate(shown, start=1):
+ link = _entity_link(team_id, source.source_product, entity_id, index, len(source.entity_ids))
+ if link is not None:
+ links.append(link)
+ lines.append(
+ OriginSourceLine(
+ label=_source_label(source.source_product),
+ links=tuple(links),
+ has_more=len(source.entity_ids) > len(shown),
+ )
+ )
+ return lines
+
+
+def _latest_artefact_as(
+ team_id: int,
+ report_id: str,
+ artefact_type: str,
+ model: type[ArtefactModel],
+ created_before: datetime | None = None,
+) -> ArtefactModel | None:
+ artefacts = SignalReportArtefact.objects.filter(team_id=team_id, report_id=report_id, type=artefact_type)
+ if created_before is not None:
+ artefacts = artefacts.filter(created_at__lte=created_before)
+ artefact = artefacts.order_by("-created_at", "-id").first()
+ if artefact is None:
+ return None
+ try:
+ return model.model_validate_json(artefact.content)
+ except ValidationError:
+ return None
+
+
+def _cause_commit(team_id: int, report_id: str, repository: str) -> OriginLink | None:
+ """The first commit of the newest finding, which the research prompt orders causative first.
+
+ A finding stores a short hash with no repository, so research into another repository could
+ produce a hash that does not exist here. The commit links only when the suggested reviewers
+ carry the same commit under this pull request's repository.
+ """
+ finding = _latest_artefact_as(team_id, report_id, SignalReportArtefact.ArtefactType.SIGNAL_FINDING, SignalFinding)
+ reviewers = _latest_artefact_as(
+ team_id, report_id, SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS, SuggestedReviewers
+ )
+ if finding is None or reviewers is None:
+ return None
+ commit_prefix = f"https://github.com/{repository}/commit/".lower()
+ # The stored URL is only evidence. The link is rebuilt from a validated hash, so no stored text reaches the body.
+ known_shas = [
+ full_sha
+ for reviewer in reviewers.root
+ for commit in reviewer.relevant_commits
+ if commit.url.lower().startswith(commit_prefix)
+ and _COMMIT_SHA_RE.match(full_sha := commit.url.lower().removeprefix(commit_prefix))
+ ]
+ for sha in finding.relevant_commit_hashes:
+ if not _COMMIT_SHA_RE.match(sha):
+ continue
+ for full_sha in known_shas:
+ if full_sha.startswith(sha.lower()):
+ return OriginLink(label=f"`{sha[:8]}`", url=f"https://github.com/{repository}/commit/{full_sha}")
+ return None
+
+
+@frozen
+class RunStart:
+ automatic: bool
+ # The priority when the run started. A later judgment did not trigger this run.
+ priority: str | None
+
+
+def _run_start(team_id: int, report_id: str, task_id: str) -> RunStart | None:
+ """How this run started. None when the report has no record of the run."""
+ artefacts = SignalReportArtefact.objects.filter(
+ team_id=team_id, report_id=report_id, type=SignalReportArtefact.ArtefactType.TASK_RUN, task_id=task_id
+ ).order_by("-created_at", "-id")
+ for artefact in artefacts:
+ try:
+ task_run = TaskRunArtefact.model_validate_json(artefact.content)
+ except ValidationError:
+ continue
+ judgment = _latest_artefact_as(
+ team_id,
+ report_id,
+ SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,
+ PriorityAssessment,
+ created_before=artefact.created_at,
+ )
+ return RunStart(
+ automatic=task_run.automation_branch is not None,
+ priority=judgment.priority.value if judgment else None,
+ )
+ return None
+
+
+def _scout_label(sources: list[OriginSource]) -> str | None:
+ """Name a scout only when it ships with PostHog. A custom scout's name comes from its creator and can be private."""
+ scout_name = next((source.scout_name for source in sources if source.scout_name), None)
+ if scout_name is None:
+ return None
+ return f"`{scout_name}`" if scout_name in canonical_skill_names() else "a custom scout"
+
+
+def _issue_link(reference: SignalSourceReference, repository: str) -> OriginLink:
+ """Link an issue only when it is as public as the pull request itself.
+
+ An issue in another repository or in Linear can be private, and its URL alone can name the
+ workspace or the title, so those keep a plain label.
+ """
+ same_repository = f"https://github.com/{repository}/issues/".lower()
+ if reference.source_product == "github":
+ if reference.url.lower().startswith(same_repository):
+ return OriginLink(label=reference.label, url=reference.url)
+ # A bare "#42" would render as a link to issue 42 of this pull request's repository.
+ return OriginLink(label="GitHub issue", url=None)
+ # A Linear identifier names a private team key and a sequential issue number.
+ return OriginLink(label="Linear issue", url=None)
+
+
+@frozen
+class PullRequestOrigin:
+ """Where a self-driving pull request came from, reduced to facts that are safe to publish."""
+
+ report_id: str
+ report_url: str
+ sources: tuple[OriginSourceLine, ...]
+ issue_references: tuple[OriginLink, ...]
+ scout_label: str | None
+ first_seen: date | None
+ cause_commit: OriginLink | None
+ run_start: RunStart | None
+
+ @classmethod
+ def for_report(cls, *, team: Team, report_id: str, task_id: str, repository: str) -> PullRequestOrigin:
+ sources = fetch_origin_sources_for_report(team, report_id)
+ return cls(
+ report_id=report_id,
+ report_url=f"{settings.SITE_URL}/project/{team.pk}/inbox/reports/{report_id}",
+ sources=tuple(_source_lines(team.pk, sources)),
+ issue_references=tuple(
+ _issue_link(reference, repository) for reference in fetch_source_references_for_report(team, report_id)
+ ),
+ scout_label=_scout_label(sources),
+ first_seen=min(source.first_seen for source in sources).date() if sources else None,
+ cause_commit=_cause_commit(team.pk, report_id, repository),
+ run_start=_run_start(team.pk, report_id, task_id),
+ )
+
+ def _started_line(self) -> str | None:
+ if self.run_start is None:
+ return None
+ if not self.run_start.automatic:
+ return "- Task started by: a person, from the inbox"
+ if self.run_start.priority:
+ return (
+ f"- Task started by: auto-start, after the report was rated {self.run_start.priority} and ready to fix"
+ )
+ return "- Task started by: auto-start, after the report was rated ready to fix"
+
+ def render(self) -> str:
+ lines = [source.render() for source in self.sources]
+ if self.issue_references:
+ lines.append(f"- Issues: {', '.join(link.render() for link in self.issue_references)}")
+ if self.scout_label:
+ lines.append(f"- Scout: {self.scout_label}")
+ if self.first_seen:
+ lines.append(f"- First signal: {self.first_seen.isoformat()}")
+ lines.append(f"- Inbox report: [open]({self.report_url})")
+ if self.cause_commit:
+ lines.append(f"- Likely cause: {self.cause_commit.render()}")
+ started = self._started_line()
+ if started:
+ lines.append(started)
+
+ body = "\n".join(lines)
+ return (
+ f"<!-- {ORIGIN_MARKER_PREFIX}:{self.report_id} -->\n"
+ f"## Origin\n\n{body}\n"
+ f"<!-- /{ORIGIN_MARKER_PREFIX}:{self.report_id} -->"
+ )
+
+
+@frozen
+class TextSpan:
+ start: int
+ end: int
+
+
+def _fenced_spans(body: str) -> list[TextSpan]:
+ """Find fenced code blocks in one pass, because a heading or rule inside one is code, not structure.
+
+ Follows the CommonMark fence rules: up to three spaces of indent, a closing fence at least as
+ long as the opener, and an unclosed fence that runs to the end of the body.
+ """
+ spans: list[TextSpan] = []
+ offset = 0
+ fence_char = ""
+ fence_length = 0
+ fence_start = 0
+ for line in body.splitlines(keepends=True):
+ text = line.strip()
+ indent = len(line) - len(line.lstrip(" "))
+ if indent <= 3 and text[:3] in ("```", "~~~"):
+ char = text[0]
+ run = len(text) - len(text.lstrip(char))
+ if not fence_char:
+ fence_char, fence_length, fence_start = char, run, offset
+ elif char == fence_char and run >= fence_length and not text.strip(char):
+ spans.append(TextSpan(start=fence_start, end=offset + len(line)))
+ fence_char = ""
+ offset += len(line)
+ if fence_char:
+ spans.append(TextSpan(start=fence_start, end=len(body)))
+ return spans
+
+
+def _first_outside(pattern: re.Pattern[str], body: str, position: int, fenced: list[TextSpan]) -> re.Match[str] | None:
+ # The spans are sorted and do not overlap, so a binary search finds the only span that can hold a match.
+ starts = [span.start for span in fenced]
+ for match in pattern.finditer(body, position):
+ index = bisect_right(starts, match.start()) - 1
+ if index < 0 or match.start() >= fenced[index].end:
+ return match
+ return None
+
+
+def _splice(body: str, position: int, section: str) -> str:
+ before, after = body[:position].rstrip(), body[position:].strip()
+ return "\n\n".join(part for part in (before, section, after) if part) + "\n"
+
+
+def place_origin_section(body: str, *, report_id: str, section: str) -> str:
+ """Put the section below the Problem section, replacing an earlier copy for the same report.
+
+ Only a block inside this report's markers is ever replaced. An unmarked Origin section can be
+ part of the repository's own template, so it stays. A body without a Problem section, as in a
+ repository with another template, gets the section appended.
+ """
+ start = f"<!-- {ORIGIN_MARKER_PREFIX}:{report_id} -->"
+ end = f"<!-- /{ORIGIN_MARKER_PREFIX}:{report_id} -->"
+ start_index = body.find(start)
+ end_index = body.find(end, start_index)
+ if start_index != -1 and end_index != -1:
+ return body[:start_index] + section + body[end_index + len(end) :]
+
+ fenced = _fenced_spans(body)
+ problem = _first_outside(_PROBLEM_HEADING_RE, body, 0, fenced)
+ if problem is None:
+ return _splice(body, len(body), section)
+ section_end = _first_outside(_SECTION_END_RE, body, problem.end(), fenced)
+ return _splice(body, section_end.start() if section_end else len(body), section)
+
+
+def write_origin_section(*, team_id: int, report_id: str, task_id: str, pr_url: str) -> BodyEditOutcome:
+ """Write or refresh the Origin section of a pull request.
+
+ Never raises: a missing section must not stop the tracker cross-link that runs beside it.
+ """
+ try:
+ # Anyone who controls the task can write a run's pr_url, so only a webhook-confirmed PR gets edited.
+ # The webhook usually lands after the agent reports the URL, so this is a retry, not a skip.
+ if not tasks_facade.is_verified_task_pr_url(task_id=task_id, team_id=team_id, pr_url=pr_url):
+ logger.info("signals.pr_origin_unverified_pr", report_id=report_id, pr_url=pr_url)
+ return BodyEditOutcome.FAILED
+ team = Team.objects.get(pk=team_id)
+
+ def add_origin(body: str, repository: str) -> str:
+ origin = PullRequestOrigin.for_report(
+ team=team, report_id=report_id, task_id=task_id, repository=repository
+ )
+ return place_origin_section(body, report_id=report_id, section=origin.render())
+
+ return edit_pull_request_body(
+ team_id=team_id, report_id=report_id, pr_url=pr_url, edit=add_origin, log_event="signals.pr_origin"
+ )
+ except Exception:
+ logger.exception("signals.pr_origin_unexpected_error", report_id=report_id, team_id=team_id)
+ return BodyEditOutcome.FAILED
diff --git a/products/signals/backend/pull_request_body.py b/products/signals/backend/pull_request_body.py
new file mode 100644
index 000000000000..01f3ebfeeb77
--- /dev/null
+++ b/products/signals/backend/pull_request_body.py
@@ -0,0 +1,65 @@
+"""Backend edits to a self-driving pull request's description.
+
+The agent writes the description, and the backend then adds sections it must not paraphrase, such
+as the tracker issue reference and the Origin section. Every such edit reads the current body and
+writes it back under the body's etag, so an edit never overwrites a change the agent made in between.
+"""
+
+from collections.abc import Callable
+from enum import StrEnum
+
+import structlog
+
+from posthog.models.github_integration_base import GitHubIntegrationBase
+from posthog.models.integration import GitHubIntegration
+
+logger = structlog.get_logger(__name__)
+
+
+class BodyEditOutcome(StrEnum):
+ WRITTEN = "written"
+ # Nothing to write, or the URL is not a GitHub pull request. A retry cannot change that.
+ SKIPPED = "skipped"
+ # GitHub refused, the repository access check failed, or the body changed after the read.
+ # A retry can succeed.
+ FAILED = "failed"
+
+
+def edit_pull_request_body(
+ *, team_id: int, report_id: str, pr_url: str, edit: Callable[[str, str], str | None], log_event: str
+) -> BodyEditOutcome:
+ """Apply `edit` to a pull request body and write the result back when it changed.
+
+ `edit` receives the body and the `owner/repo` of the pull request. It returns the new body, or
+ None when it has nothing to write. A body that `edit` returns unchanged counts as written.
+ """
+ parsed = GitHubIntegrationBase.parse_pull_request_url(pr_url)
+ if parsed is None:
+ return BodyEditOutcome.SKIPPED
+ github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)
+ if github is None:
+ # The lookup also returns None when the access check hits a transient GitHub error.
+ logger.info(f"{log_event}_no_integration", report_id=report_id, pr_url=pr_url)
+ return BodyEditOutcome.FAILED
+
+ pull_request = github.get_pull_request(parsed.repository, parsed.number)
+ if not pull_request.get("success"):
+ logger.warning(
+ f"{log_event}_pr_fetch_failed", report_id=report_id, pr_url=pr_url, error=pull_request.get("error")
+ )
+ return BodyEditOutcome.FAILED
+
+ body = pull_request.get("body") or ""
+ updated = edit(body, parsed.repository)
+ if updated is None:
+ return BodyEditOutcome.SKIPPED
+ if updated == body:
+ return BodyEditOutcome.WRITTEN
+
+ outcome = github.update_pull_request_body(
+ parsed.repository, parsed.number, updated, expected_etag=pull_request.get("etag")
+ )
+ if not outcome.get("success"):
+ logger.warning(f"{log_event}_pr_update_failed", report_id=report_id, pr_url=pr_url, error=outcome.get("error"))
+ return BodyEditOutcome.FAILED
+ return BodyEditOutcome.WRITTEN
diff --git a/products/signals/backend/signal_metadata.py b/products/signals/backend/signal_metadata.py
index 46189e9548c4..8bf54fefe293 100644
--- a/products/signals/backend/signal_metadata.py
+++ b/products/signals/backend/signal_metadata.py
@@ -9,6 +9,7 @@ keeps that import graph acyclic.
import re
from dataclasses import dataclass
+from datetime import datetime
from posthog.schema import EmbeddingModelName
@@ -18,6 +19,7 @@ from posthog.hogql.database.database import Database
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.dataclasses import frozen
from posthog.models import Team
# The embedding model whose document rows constitute the signal store; every signals
@@ -329,6 +331,9 @@ def fetch_source_references_for_report(team: Team, report_id: str) -> list[Signa
WHERE NOT is_deleted
AND report_id = {report_id}
AND source_product IN ('linear', 'github')
+ ORDER BY source_product, url, html_url
+ LIMIT 1 BY source_product, url, html_url
+ LIMIT {row_cap}
"""
tag_queries(product=Product.SIGNALS, feature=Feature.QUERY)
@@ -339,6 +344,8 @@ def fetch_source_references_for_report(team: Team, report_id: str) -> list[Signa
placeholders={
"model_name": ast.Constant(value=EMBEDDING_MODEL.value),
"report_id": ast.Constant(value=report_id),
+ # Headroom over the reference cap for rows the URL checks below drop.
+ "row_cap": ast.Constant(value=_SOURCE_REFERENCE_CAP * 10),
},
)
@@ -357,3 +364,72 @@ def fetch_source_references_for_report(team: Team, report_id: str) -> list[Signa
references.sort(key=lambda ref: (ref.source_product, ref.label, ref.url))
return references[:_SOURCE_REFERENCE_CAP]
+
+
+# Enough ids to fill the capped link list plus one, so the caller can tell there are more.
+ORIGIN_ENTITY_ID_CAP = 6
+# One row per source product and scout, so a report can never return an unbounded result.
+_ORIGIN_SOURCE_ROW_CAP = 50
+
+
+@frozen
+class OriginSource:
+ """One source of a report's signals, without any of their content."""
+
+ source_product: str
+ # The authoring scout's skill slug, or "" for pipeline signals.
+ scout_name: str
+ first_seen: datetime
+ # At most ORIGIN_ENTITY_ID_CAP entity ids, sorted. A support ticket keeps its uuid, because its
+ # sequential ticket number would reveal the team's ticket volume.
+ entity_ids: tuple[str, ...]
+
+
+def fetch_origin_sources_for_report(team: Team, report_id: str) -> list[OriginSource]:
+ """Summarize where a report's non-deleted signals came from, earliest source first.
+
+ Aggregates in ClickHouse, so the result stays small however many signals the report holds.
+ The signal `content` never leaves ClickHouse here, because the caller writes the result into
+ a public pull request.
+ """
+ ch_query = f"""
+ SELECT
+ source_product,
+ scout_name,
+ min(timestamp) as first_seen,
+ groupUniqArray({ORIGIN_ENTITY_ID_CAP})(entity_id) as entity_ids
+ FROM (
+ SELECT
+ JSONExtractString(metadata, 'source_product') as source_product,
+ JSONExtractString(metadata, 'extra', 'skill_name') as scout_name,
+ JSONExtractString(metadata, 'source_id') as entity_id,
+ timestamp
+ FROM ({_deduped_signals_subquery(include_content=False, candidate_document_filter="JSONExtractString(metadata, 'report_id') = {report_id}")})
+ WHERE JSONExtractString(metadata, 'report_id') = {{report_id}}
+ AND NOT JSONExtractBool(metadata, 'deleted')
+ )
+ GROUP BY source_product, scout_name
+ ORDER BY first_seen ASC
+ LIMIT {_ORIGIN_SOURCE_ROW_CAP}
+ """
+
+ tag_queries(product=Product.SIGNALS, feature=Feature.QUERY)
+ result = execute_hogql_query(
+ query_type="SignalsFetchOriginSourcesForReport",
+ query=ch_query,
+ team=team,
+ context=_signals_query_context(team),
+ placeholders={
+ "model_name": ast.Constant(value=EMBEDDING_MODEL.value),
+ "report_id": ast.Constant(value=report_id),
+ },
+ )
+ return [
+ OriginSource(
+ source_product=source_product or "",
+ scout_name=scout_name or "",
+ first_seen=first_seen,
+ entity_ids=tuple(sorted(entity_id for entity_id in entity_ids if entity_id)),
+ )
+ for source_product, scout_name, first_seen, entity_ids in result.results or []
+ ]
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index 0b13ac65751d..dac77583f512 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -37,6 +37,8 @@ from products.signals.backend.models import (
SignalScoutRun,
SignalScratchpad,
)
+from products.signals.backend.pr_origin import write_origin_section
+from products.signals.backend.pull_request_body import BodyEditOutcome
from products.signals.backend.report_generation.repo_activity import (
ACTIVITY_KEEP_WARM_WINDOW,
rebuild_repository_activity,
@@ -165,7 +167,11 @@ def close_report_tracker_issue(
)
@with_team_scope()
def link_report_tracker_issues(self, team_id: int, task_id: str, pr_url: str) -> None:
- """Cross-reference a task's new pull request with the tracker issue of every report it answers."""
+ """Write a task's new pull request body: the Origin section and the tracker issue cross-reference.
+
+ Both edits share this task so they run in sequence. Two tasks would race on the same body and
+ keep failing each other's etag check.
+ """
report_ids = (
SignalReport.objects.filter(team_id=team_id)
.filter(SignalReport.reports_for_task_filter(task_id))
@@ -173,6 +179,8 @@ def link_report_tracker_issues(self, team_id: int, task_id: str, pr_url: str) ->
)
retry_needed = False
for report_id in report_ids:
+ origin = write_origin_section(team_id=team_id, report_id=str(report_id), task_id=task_id, pr_url=pr_url)
+ retry_needed = retry_needed or origin == BodyEditOutcome.FAILED
linked = link_pull_request_to_tracker_issue(team_id=team_id, report_id=str(report_id), pr_url=pr_url)
if not linked:
retry_needed = (
diff --git a/products/signals/backend/test/test_pr_origin.py b/products/signals/backend/test/test_pr_origin.py
new file mode 100644
index 000000000000..ac08b60ad2e1
--- /dev/null
+++ b/products/signals/backend/test/test_pr_origin.py
@@ -0,0 +1,245 @@
+import json
+from datetime import UTC, datetime
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.models.integration import GitHubIntegration
+
+from products.signals.backend.models import SignalReport, SignalReportArtefact
+from products.signals.backend.pr_origin import (
+ PullRequestOrigin,
+ _scout_label,
+ place_origin_section,
+ write_origin_section,
+)
+from products.signals.backend.pull_request_body import BodyEditOutcome
+from products.signals.backend.signal_metadata import OriginSource, SignalSourceReference
+from products.signals.backend.task_run_artefacts import record_implementation_task
+
+# Task ORM model needed to build a cross-product fixture; the tasks facade exposes DTOs only.
+from products.tasks.backend.models import Task, TaskRun
+
+SECTION = "<!-- posthog-self-driving-origin:r1 -->\n## Origin\n\n- new\n<!-- /posthog-self-driving-origin:r1 -->"
+OTHER_REPORT = "<!-- posthog-self-driving-origin:r0 -->\n## Origin\n\n- other\n<!-- /posthog-self-driving-origin:r0 -->"
+
+
+class TestPlaceOriginSection(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "below_problem",
+ "## Problem\n\n- broken\n\n## Changes\n\n- fixed\n",
+ f"## Problem\n\n- broken\n\n{SECTION}\n\n## Changes\n\n- fixed\n",
+ ),
+ (
+ "replaces_earlier_copy",
+ "## Problem\n\n- broken\n\n<!-- posthog-self-driving-origin:r1 -->\n## Origin\n\n- old\n"
+ "<!-- /posthog-self-driving-origin:r1 -->\n\n## Changes\n",
+ f"## Problem\n\n- broken\n\n{SECTION}\n\n## Changes\n",
+ ),
+ (
+ "keeps_an_unmarked_origin_section",
+ "## Problem\n\n- broken\n\n## Origin\n\nRequired by the template.\n\n## Changes\n",
+ f"## Problem\n\n- broken\n\n{SECTION}\n\n## Origin\n\nRequired by the template.\n\n## Changes\n",
+ ),
+ (
+ "second_report_keeps_the_first",
+ f"## Problem\n\n- broken\n\n{OTHER_REPORT}\n\n## Changes\n",
+ f"## Problem\n\n- broken\n\n{SECTION}\n\n{OTHER_REPORT}\n\n## Changes\n",
+ ),
+ (
+ "fenced_heading_is_code",
+ "## Problem\n\n```\n## Origin\n---\n```\n\n## Changes\n",
+ f"## Problem\n\n```\n## Origin\n---\n```\n\n{SECTION}\n\n## Changes\n",
+ ),
+ (
+ "indented_fence_with_longer_close",
+ "## Problem\n\n ```\n## Origin\n `````\n\n## Changes\n",
+ f"## Problem\n\n ```\n## Origin\n `````\n\n{SECTION}\n\n## Changes\n",
+ ),
+ (
+ "appended_without_problem",
+ "Fixes the thing.\n",
+ f"Fixes the thing.\n\n{SECTION}\n",
+ ),
+ ]
+ )
+ def test_places_section(self, _name: str, body: str, expected: str) -> None:
+ assert place_origin_section(body, report_id="r1", section=SECTION) == expected
+
+
+class TestScoutLabel(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("canonical", "signals-scout-error-tracking", "`signals-scout-error-tracking`"),
+ ("custom", "signals-scout-acme-payment-incident", "a custom scout"),
+ ]
+ )
+ def test_names_only_shipped_scouts(self, _name: str, scout_name: str, expected: str) -> None:
+ source = OriginSource(
+ source_product="error_tracking",
+ scout_name=scout_name,
+ first_seen=datetime(2026, 9, 15, tzinfo=UTC),
+ entity_ids=("run:1:finding:2",),
+ )
+ assert _scout_label([source]) == expected
+
+
+class TestPullRequestOrigin(BaseTest):
+ def _priority(self, report: SignalReport, priority: str) -> None:
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,
+ content=json.dumps({"explanation": "a customer's private details", "priority": priority}),
+ )
+
+ def test_renders_only_allowlisted_facts(self) -> None:
+ report = SignalReport.objects.create(
+ team=self.team, status=SignalReport.Status.READY, title="t", summary="s", signal_count=3, total_weight=3.0
+ )
+ task = Task.objects.create(
+ team=self.team, title="task", description="desc", origin_product=Task.OriginProduct.SIGNAL_REPORT
+ )
+ self._priority(report, "P2")
+ record_implementation_task(
+ team_id=self.team.id,
+ report_id=str(report.id),
+ task_id=str(task.id),
+ automation_branch="posthog-self-driving/fix-abc123",
+ )
+ self._priority(report, "P0")
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content=json.dumps(
+ [
+ {
+ "github_login": "someone",
+ "relevant_commits": [
+ {
+ "reason": "added the capture",
+ "sha": "a59c3290",
+ "url": "https://github.com/acme/web/commit/a59c3290fe9bb4d4",
+ },
+ {
+ "reason": "injected",
+ "sha": "a59c3290",
+ "url": "https://github.com/acme/web/commit/a59c3290)\n\n## Injected",
+ },
+ {
+ "reason": "elsewhere",
+ "sha": "bbbbbbbb",
+ "url": "https://github.com/acme/other/commit/bbbbbbbbcccc",
+ },
+ ],
+ }
+ ]
+ ),
+ )
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SIGNAL_FINDING,
+ content=json.dumps(
+ {
+ "signal_id": "s1",
+ "relevant_code_paths": ["ee/api/vercel/webhooks.py"],
+ "relevant_commit_hashes": {
+ "not-a-sha": "junk",
+ "bbbbbbbb": "other repository",
+ "a59c3290": "added the capture",
+ },
+ "data_queried": "a customer's private details",
+ "verified": True,
+ }
+ ),
+ )
+ sources = [
+ OriginSource(
+ source_product="error_tracking",
+ scout_name="",
+ first_seen=datetime(2026, 9, 15, 7, 3, tzinfo=UTC),
+ entity_ids=("01a0a561-54a4", "zz/../settings?x=1"),
+ ),
+ OriginSource(
+ source_product="error_tracking",
+ scout_name="signals-scout-error-tracking",
+ first_seen=datetime(2026, 9, 16, tzinfo=UTC),
+ entity_ids=("run:1:finding:2",),
+ ),
+ ]
+
+ with (
+ patch("products.signals.backend.pr_origin.fetch_origin_sources_for_report", return_value=sources),
+ patch(
+ "products.signals.backend.pr_origin.fetch_source_references_for_report",
+ return_value=[
+ SignalSourceReference("github", "#12", "https://github.com/acme/web/issues/12"),
+ SignalSourceReference("github", "#3", "https://github.com/acme/private/issues/3"),
+ SignalSourceReference("linear", "ENG-1", "https://linear.app/acme/issue/ENG-1/secret-title"),
+ ],
+ ),
+ ):
+ section = PullRequestOrigin.for_report(
+ team=self.team, report_id=str(report.id), task_id=str(task.id), repository="acme/web"
+ ).render()
+
+ project = f"/project/{self.team.id}"
+ assert f"[issue 1](http://localhost:8010{project}/error_tracking/01a0a561-54a4)" in section
+ assert "settings?x=1" not in section
+ assert "run:1:finding:2" not in section
+ assert "- Scout: `signals-scout-error-tracking`" in section
+ assert "- First signal: 2026-09-15" in section
+ assert "[`a59c3290`](https://github.com/acme/web/commit/a59c3290fe9bb4d4)" in section
+ assert "bbbbbbbb" not in section
+ assert "Injected" not in section
+ assert "- Task started by: auto-start, after the report was rated P2 and ready to fix" in section
+ assert "- Issues: [#12](https://github.com/acme/web/issues/12), GitHub issue, Linear issue" in section
+ assert "private" not in section
+ assert "secret-title" not in section
+ assert "ENG-1" not in section
+
+ @parameterized.expand([("verified", True, BodyEditOutcome.WRITTEN), ("unverified", False, BodyEditOutcome.FAILED)])
+ def test_edits_only_a_webhook_confirmed_pull_request(
+ self, _name: str, verified: bool, expected: BodyEditOutcome
+ ) -> None:
+ pr_url = "https://github.com/acme/web/pull/7"
+ report = SignalReport.objects.create(
+ team=self.team, status=SignalReport.Status.READY, title="t", summary="s", signal_count=1, total_weight=1.0
+ )
+ task = Task.objects.create(
+ team=self.team, title="task", description="desc", origin_product=Task.OriginProduct.SIGNAL_REPORT
+ )
+ TaskRun.objects.create(
+ team=self.team,
+ task=task,
+ state={"verified_pr_urls": [pr_url] if verified else []},
+ output={"pr_url": pr_url},
+ )
+
+ with (
+ patch("products.signals.backend.pr_origin.fetch_origin_sources_for_report", return_value=[]),
+ patch("products.signals.backend.pr_origin.fetch_source_references_for_report", return_value=[]),
+ patch.object(
+ GitHubIntegration,
+ "first_for_team_repository",
+ return_value=GitHubIntegration.__new__(GitHubIntegration),
+ ),
+ patch.object(
+ GitHubIntegration, "get_pull_request", return_value={"success": True, "body": "", "etag": "e"}
+ ),
+ patch.object(GitHubIntegration, "update_pull_request_body", return_value={"success": True}) as update,
+ ):
+ outcome = write_origin_section(
+ team_id=self.team.id, report_id=str(report.id), task_id=str(task.id), pr_url=pr_url
+ )
+
+ assert outcome == expected
+ assert update.called is verified
diff --git a/products/signals/backend/test/test_signal_queries.py b/products/signals/backend/test/test_signal_queries.py
index bd01c13c5044..936289536e68 100644
--- a/products/signals/backend/test/test_signal_queries.py
+++ b/products/signals/backend/test/test_signal_queries.py
@@ -20,6 +20,7 @@ from products.signals.backend.signal_metadata import (
EMBEDDING_MODEL,
ReportSignalMeta,
SignalSourceReference,
+ fetch_origin_sources_for_report,
fetch_signal_stats_for_source_slice,
fetch_source_products_for_reports,
fetch_source_references_for_report,
@@ -269,6 +270,37 @@ class TestFetchSourceReferencesForReport(_SignalEmbeddingsTestBase):
]
+class TestFetchOriginSourcesForReport(_SignalEmbeddingsTestBase):
+ def test_summarizes_live_sources_of_the_report_earliest_first(self) -> None:
+ self._emit_version(document_id="later", report_id="r1", source_product="error_tracking", inserted_at=self.base)
+ self._emit_version(
+ document_id="scout",
+ report_id="r1",
+ source_product="error_tracking",
+ inserted_at=self.base - timedelta(hours=1),
+ skill_name="signals-scout-error-tracking",
+ )
+ self._emit_version(document_id="gone", report_id="r1", source_product="logs", inserted_at=self.base)
+ self._emit_version(
+ document_id="gone",
+ report_id="r1",
+ source_product="logs",
+ inserted_at=self.base + timedelta(minutes=1),
+ deleted=True,
+ )
+ self._emit_version(document_id="moved", report_id="r1", source_product="logs", inserted_at=self.base)
+ self._emit_version(
+ document_id="moved", report_id="r2", source_product="logs", inserted_at=self.base + timedelta(minutes=1)
+ )
+
+ sources = fetch_origin_sources_for_report(self.team, "r1")
+
+ assert [(s.source_product, s.scout_name, s.entity_ids) for s in sources] == [
+ ("error_tracking", "signals-scout-error-tracking", ("src-scout",)),
+ ("error_tracking", "", ("src-later",)),
+ ]
+
+
class TestFetchReportIdsForScoutNames(_SignalEmbeddingsTestBase):
def test_returns_only_reports_authored_by_the_named_scouts(self) -> None:
# Guards the nested `extra.skill_name` extraction driving the inbox scout filter — a broken
diff --git a/products/signals/backend/tracker_issues.py b/products/signals/backend/tracker_issues.py
index a134b4ce5f29..219b5b2d09db 100644
--- a/products/signals/backend/tracker_issues.py
+++ b/products/signals/backend/tracker_issues.py
@@ -20,7 +20,6 @@ import structlog
from rest_framework.exceptions import ValidationError as DRFValidationError
from posthog.dataclasses import frozen
-from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.models.integration import (
SUPPORTED_EXTERNAL_ISSUE_PROVIDERS,
GitHubIntegration,
@@ -33,6 +32,7 @@ from posthog.models.integration import (
from products.signals.backend.github_actor import github_mention_for_user
from products.signals.backend.models import SignalReport, SignalReportTrackerIssue, SignalTeamConfig
+from products.signals.backend.pull_request_body import BodyEditOutcome, edit_pull_request_body
logger = structlog.get_logger(__name__)
@@ -298,44 +298,25 @@ def link_pull_request_to_tracker_issue(*, team_id: int, report_id: str, pr_url:
if tracker is None or tracker.pr_linked_at is not None:
return False
- parsed = GitHubIntegrationBase.parse_pull_request_url(pr_url)
- if parsed is None:
- return False
- github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)
- if github is None:
- logger.info("signals.tracker_issue_link_no_integration", report_id=report_id, pr_url=pr_url)
- return False
-
- pull_request = github.get_pull_request(parsed.repository, parsed.number)
- if not pull_request.get("success"):
- logger.warning(
- "signals.tracker_issue_link_pr_fetch_failed",
- report_id=report_id,
- pr_url=pr_url,
- error=pull_request.get("error"),
- )
- return False
-
- body = pull_request.get("body") or ""
marker = f"{PR_BODY_MARKER}:{report_id} -->"
- if marker not in body:
- reference = _pr_body_reference(tracker, pr_repository=parsed.repository)
+
+ def add_reference(body: str, repository: str) -> str | None:
+ if marker in body:
+ return body
+ reference = _pr_body_reference(tracker, pr_repository=repository)
if reference is None:
- return False
- outcome = github.update_pull_request_body(
- parsed.repository,
- parsed.number,
- f"{body.rstrip()}\n\n{marker}\n{reference}\n",
- expected_etag=pull_request.get("etag"),
- )
- if not outcome.get("success"):
- logger.warning(
- "signals.tracker_issue_link_pr_update_failed",
- report_id=report_id,
- pr_url=pr_url,
- error=outcome.get("error"),
- )
- return False
+ return None
+ return f"{body.rstrip()}\n\n{marker}\n{reference}\n"
+
+ outcome = edit_pull_request_body(
+ team_id=team_id,
+ report_id=report_id,
+ pr_url=pr_url,
+ edit=add_reference,
+ log_event="signals.tracker_issue_link",
+ )
+ if outcome != BodyEditOutcome.WRITTEN:
+ return False
if tracker.provider == Integration.IntegrationKind.LINEAR and tracker.integration is not None:
# Best-effort: the description reference already links the two, and this attachment
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 6f2d912fb9cb..54e7205279cc 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -964,6 +964,15 @@ def get_task_id_for_run(run_id: str | UUID, team_id: int) -> UUID | None:
return TaskRun.objects.filter(id=run_id, team_id=team_id).values_list("task_id", flat=True).first()
+def is_verified_task_pr_url(*, task_id: str | UUID, team_id: int, pr_url: str) -> bool:
+ """Whether the GitHub webhook confirmed that a run of this task opened the pull request.
+
+ A run's `output.pr_url` is writable through the API. `verified_pr_urls` is server-owned, so a
+ caller that edits the pull request checks this before it trusts the URL.
+ """
+ return TaskRun.objects.filter(task_id=task_id, team_id=team_id, state__verified_pr_urls__contains=[pr_url]).exists()
+
+
def task_exists(task_id: str | UUID, team_id: int) -> bool:
"""Whether a (non-deleted) task exists for the team."""
return Task.objects.filter(id=task_id, team_id=team_id, deleted=False).exists()