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(stamphog): capture provenance trailers and familiarity in review events (#71586)

Georges-Antoine Assib49088aa600b
diff --git a/tools/pr-approval-agent/github.py b/tools/pr-approval-agent/github.py
index 61a354d5c9fd..5cb4c38b2d2b 100644
--- a/tools/pr-approval-agent/github.py
+++ b/tools/pr-approval-agent/github.py
@@ -5,6 +5,7 @@ else (PR metadata, reviews, comments, check runs) from the GitHub API.
Also handles team membership checks for the ownership gate.
"""
+import re
import json
import subprocess
from collections.abc import Callable
@@ -476,6 +477,85 @@ def ensure_commits(pr_number: int, head_sha: str, repo_root: Path) -> None:
)
+@dataclass(frozen=True)
+class CommitProvenance:
+ """Agent-authorship evidence parsed from the PR's commit-message trailers."""
+
+ commit_count: int
+ agent_commit_count: int
+ generated_by: tuple[str, ...]
+ task_ids: tuple[str, ...]
+
+ @property
+ def agent_authored(self) -> bool:
+ return self.agent_commit_count > 0
+
+
+# Record separator keeps multi-paragraph commit messages intact when splitting
+# `git log --format=%B%x1e` output back into one message per commit.
+_COMMIT_RECORD_SEPARATOR = "\x1e"
+
+_GENERATED_BY_RE = re.compile(r"^generated-by:[ \t]*(.+?)[ \t]*$", re.IGNORECASE | re.MULTILINE)
+_TASK_ID_RE = re.compile(r"^task-id:[ \t]*(.+?)[ \t]*$", re.IGNORECASE | re.MULTILINE)
+
+
+def parse_provenance_trailers(log_output: str) -> CommitProvenance:
+ """Parse `Generated-By:` / `Task-Id:` trailers out of `git log --format=%B%x1e` output.
+
+ Agent tooling stamps these trailers on every commit it authors, so any
+ commit carrying one marks the PR as agent-authored. Values are collected
+ de-duplicated in first-seen order.
+ """
+ messages = [m for m in (raw.strip() for raw in log_output.split(_COMMIT_RECORD_SEPARATOR)) if m]
+ agent_commits = 0
+ generated_by: list[str] = []
+ task_ids: list[str] = []
+ for message in messages:
+ generators = _GENERATED_BY_RE.findall(message)
+ ids = _TASK_ID_RE.findall(message)
+ if generators or ids:
+ agent_commits += 1
+ generated_by.extend(g for g in generators if g not in generated_by)
+ task_ids.extend(t for t in ids if t not in task_ids)
+ return CommitProvenance(
+ commit_count=len(messages),
+ agent_commit_count=agent_commits,
+ generated_by=tuple(generated_by),
+ task_ids=tuple(task_ids),
+ )
+
+
+def pr_provenance(base_sha: str, head_sha: str, repo_root: Path) -> CommitProvenance | None:
+ """Provenance trailers of the PR's own commits, or None when git fails.
+
+ Reads the head commits (base..head) from the local checkout — never the
+ squash-merge commit, which can drop or rewrite trailers depending on repo
+ settings. `ensure_commits` has already fetched the head objects by the
+ time this runs.
+ """
+ cmd = ["git", "log", f"{base_sha}..{head_sha}", f"--format=%B{_COMMIT_RECORD_SEPARATOR}"]
+ try:
+ result = subprocess.run(cmd, cwd=repo_root, capture_output=True, text=True, timeout=30)
+ except (OSError, subprocess.SubprocessError):
+ return None
+ if result.returncode != 0:
+ return None
+ return parse_provenance_trailers(result.stdout)
+
+
+def provenance_evidence(prov: CommitProvenance | None) -> dict | None:
+ """Serialize a CommitProvenance for the output JSON (or null)."""
+ if prov is None:
+ return None
+ return {
+ "agent_authored": prov.agent_authored,
+ "commit_count": prov.commit_count,
+ "agent_commit_count": prov.agent_commit_count,
+ "generated_by": list(prov.generated_by),
+ "task_ids": list(prov.task_ids),
+ }
+
+
def fetch_pr(pr_number: int, repo: str, repo_root: Path | None = None) -> PRData:
"""Fetch PR data: metadata from API, file stats from local git."""
pr = _gh_api(f"repos/{repo}/pulls/{pr_number}")
diff --git a/tools/pr-approval-agent/review_pr.py b/tools/pr-approval-agent/review_pr.py
index 6be9061ae629..838151ca461b 100644
--- a/tools/pr-approval-agent/review_pr.py
+++ b/tools/pr-approval-agent/review_pr.py
@@ -53,7 +53,16 @@ from gates import (
test_only,
)
from gateway import analytics_extra_properties
-from github import TRUSTED_REACTOR_BOTS, PRData, check_team_membership, fetch_pr, write_pr_diff
+from github import (
+ TRUSTED_REACTOR_BOTS,
+ CommitProvenance,
+ PRData,
+ check_team_membership,
+ fetch_pr,
+ pr_provenance,
+ provenance_evidence,
+ write_pr_diff,
+)
from manifest_risk import manifest_script_changes
from migration_risk import migration_check_pending, safe_migration_files
from policy import EffectivePolicy, ScopeBudget, _sanitize_untrusted, repo_root, resolve
@@ -190,6 +199,8 @@ class Pipeline:
self.verbose = verbose
self._wait_refetched_pr = False
self.pr: PRData | None = None
+ self.provenance: CommitProvenance | None = None
+ self.familiarity: AuthorFamiliarity | None = None
self.classification: dict = {}
self.effective_policy: EffectivePolicy | None = None
self._diff_path: Path | None = None
@@ -361,6 +372,7 @@ class Pipeline:
def _fetch(self) -> None:
print(_dim("Fetching PR data..."))
self.pr = fetch_pr(self.pr_number, self.repo, repo_root=REPO_ROOT)
+ self.provenance = pr_provenance(self.pr.base_sha, self.pr.head_sha, REPO_ROOT)
print(_dim(f" {self.pr.title}"))
print(
_dim(
@@ -446,9 +458,9 @@ class Pipeline:
"ownership": ownership,
"folder_policy_prose": self.effective_policy.folder_prose,
"assurance": self._summarize_assurance(),
- # Judgment-layer signal, filled in later only for the T1-agent path
- # (see _maybe_compute_familiarity). None here keeps every other path
- # - and the reviewer prompt - byte-identical to before.
+ # Judgment-layer signal for the reviewer prompt, attached later on
+ # the T1-agent path only (see _maybe_compute_familiarity). None here
+ # keeps the other paths' prompts byte-identical to before.
"familiarity": None,
}
@@ -496,15 +508,17 @@ class Pipeline:
}
def _maybe_compute_familiarity(self) -> None:
- """Attach the author-familiarity signal for the T1-agent path only.
+ """Compute the author-familiarity signal on every LLM-reviewed run.
Judgment layer only - never touches gates, and any failure leaves the
- signal absent (None) so behavior stays exactly as before. T0 skips the
- LLM and T2 is a deny, so neither benefits from the signal.
+ signal absent (None). The reviewer prompt receives it on the T1-agent
+ path only (T0 auto-approves and T2 is a deny, so their prompts stay
+ unchanged); telemetry captures it from every run so familiarity can be
+ trended per subsystem, not just where the reviewer consumes it.
"""
- if self.classification.get("tier") != "T1-agent":
- return
- self.classification["familiarity"] = self._compute_familiarity()
+ self.familiarity = self._compute_familiarity()
+ if self.classification.get("tier") == "T1-agent":
+ self.classification["familiarity"] = self.familiarity
def _compute_familiarity(self) -> AuthorFamiliarity | None:
pr = self.pr
@@ -780,6 +794,8 @@ class Pipeline:
cl = self.classification
pr = self.pr
+ fam = self.familiarity
+ prov = self.provenance
posthoganalytics.capture(
distinct_id=pr.author,
event="stamphog_review_completed",
@@ -803,6 +819,16 @@ class Pipeline:
"stamphog_lines_total": pr.lines_total,
"stamphog_pr_reactions_count": len(pr.pr_reactions),
"stamphog_title_scrutiny_flags": cl.get("title_scrutiny_flags", []),
+ "stamphog_owner_teams": (cl.get("ownership") or {}).get("teams", []),
+ "stamphog_familiarity_band": fam.band if fam else "",
+ "stamphog_familiarity_blame_overlap_pct": round(fam.blame_overlap_pct, 1) if fam else None,
+ "stamphog_familiarity_prior_prs_in_paths": fam.prior_prs_in_paths if fam else None,
+ "stamphog_familiarity_days_since_last_touch": fam.days_since_last_touch if fam else None,
+ "stamphog_agent_authored": prov.agent_authored if prov else None,
+ "stamphog_agent_commit_count": prov.agent_commit_count if prov else None,
+ "stamphog_commit_count": prov.commit_count if prov else None,
+ "stamphog_generated_by": list(prov.generated_by) if prov else [],
+ "stamphog_task_ids": list(prov.task_ids) if prov else [],
"stamphog_gate_verdict": gate_verdict,
"stamphog_llm_verdict": llm_verdict,
"stamphog_final_verdict": self.final_verdict,
@@ -891,8 +917,9 @@ class Pipeline:
"title_scrutiny_flags": self.classification.get("title_scrutiny_flags", []),
"safe_migration_files": self.classification.get("safe_migration_files", []),
"ownership": self.classification.get("ownership", {}),
- "familiarity": familiarity_evidence(self.classification.get("familiarity")),
+ "familiarity": familiarity_evidence(self.familiarity),
},
+ "provenance": provenance_evidence(self.provenance),
"gates": [
{"gate": g.gate, "passed": g.passed, "message": g.message} for g in self.gate_results if g is not None
],
diff --git a/tools/pr-approval-agent/test_github.py b/tools/pr-approval-agent/test_github.py
index 68364afacf62..f8996d0cd4f0 100644
--- a/tools/pr-approval-agent/test_github.py
+++ b/tools/pr-approval-agent/test_github.py
@@ -6,11 +6,13 @@ import pytest
import github
from github import (
+ CommitProvenance,
_normalize_discussion_for_prompt,
_normalize_reviews_for_prompt,
_reaction_emoji,
_trusted_reactor_predicate,
is_bot_author,
+ parse_provenance_trailers,
)
@@ -196,6 +198,70 @@ def test_is_bot_author(user: dict, expected: bool) -> None:
assert is_bot_author(user) is expected
+ "log_output,expected",
+ [
+ pytest.param(
+ "fix: resolve login redirect loop\n\n"
+ "Generated-By: PostHog Code\n"
+ "Task-Id: a95947d1-6e11-4565-9922-1f857cc6f6fe\n\x1e\n",
+ CommitProvenance(
+ commit_count=1,
+ agent_commit_count=1,
+ generated_by=("PostHog Code",),
+ task_ids=("a95947d1-6e11-4565-9922-1f857cc6f6fe",),
+ ),
+ id="single-agent-commit",
+ ),
+ pytest.param(
+ "fix: handle empty cohort\n\x1e\nchore: bump deps\n\x1e\n",
+ CommitProvenance(commit_count=2, agent_commit_count=0, generated_by=(), task_ids=()),
+ id="human-only-commits",
+ ),
+ pytest.param(
+ "feat: add export\n\nGenerated-By: PostHog Code\nTask-Id: task-1\n\x1e\n"
+ "fix: review feedback\n\x1e\n"
+ "fix: more feedback\n\nGenerated-By: PostHog Code\nTask-Id: task-2\n\x1e\n",
+ CommitProvenance(
+ commit_count=3,
+ agent_commit_count=2,
+ generated_by=("PostHog Code",),
+ task_ids=("task-1", "task-2"),
+ ),
+ id="mixed-commits-dedupe-generator-collect-task-ids",
+ ),
+ pytest.param(
+ "feat(insights): retention export (#71452)\n\n"
+ "* feat: first pass\n\n"
+ "Generated-By: PostHog Code\n"
+ "Task-Id: task-1\n\n"
+ "* fix: address review\n\x1e\n",
+ CommitProvenance(
+ commit_count=1, agent_commit_count=1, generated_by=("PostHog Code",), task_ids=("task-1",)
+ ),
+ id="squash-style-message-with-embedded-trailers",
+ ),
+ pytest.param(
+ "chore: retry task\n\ngenerated-by: posthog code\ntask-id: task-9\n\x1e\n",
+ CommitProvenance(
+ commit_count=1, agent_commit_count=1, generated_by=("posthog code",), task_ids=("task-9",)
+ ),
+ id="case-insensitive-trailers",
+ ),
+ pytest.param(
+ "",
+ CommitProvenance(commit_count=0, agent_commit_count=0, generated_by=(), task_ids=()),
+ id="empty-log-output",
+ ),
+ ],
+)
+def test_parse_provenance_trailers(log_output: str, expected: CommitProvenance) -> None:
+ # The provenance dimension (agent-authored % of PRs) is derived entirely
+ # from these trailers — a parsing regression zeroes it silently rather
+ # than failing anything, so the shapes git actually emits are locked here.
+ assert parse_provenance_trailers(log_output) == expected
+
+
def _worst_case_node_count(query: str) -> int:
# Mirrors GitHub's pre-execution node-limit check: each connection requests
# `first` nodes multiplied by the `first` of every ancestor connection.
diff --git a/tools/pr-approval-agent/test_review_pr.py b/tools/pr-approval-agent/test_review_pr.py
index 73ab379930b1..9cc0ceee7320 100644
--- a/tools/pr-approval-agent/test_review_pr.py
+++ b/tools/pr-approval-agent/test_review_pr.py
@@ -12,7 +12,8 @@ sys.modules.setdefault("claude_agent_sdk", MagicMock())
sys.modules.setdefault("claude_agent_sdk.types", MagicMock())
import review_pr # noqa: E402
-from github import PRData # noqa: E402
+from familiarity import AuthorFamiliarity # noqa: E402
+from github import CommitProvenance, PRData # noqa: E402
from review_pr import GateResult, Pipeline # noqa: E402
@@ -23,6 +24,9 @@ def _no_live_team_lookup(monkeypatch: pytest.MonkeyPatch) -> None:
# `gh api` mid-test - slow, network-dependent, and it trips tests that
# assert the pipeline never sleeps (subprocess waits sleep internally).
monkeypatch.setattr(review_pr, "check_team_membership", lambda *_a, **_k: False)
+ # Familiarity computes on every LLM-reviewed run and shells out to
+ # `gh pr list` / `git blame`; stub it for the same reasons as above.
+ monkeypatch.setattr(review_pr, "compute_familiarity", lambda **_k: None)
def _fake_pr(head_sha: str) -> PRData:
@@ -438,6 +442,109 @@ def test_wait_refetch_reclassifies_before_review(monkeypatch: pytest.MonkeyPatch
assert pipeline.classification["deny_categories"] == ["infra_cicd"]
+ "tier, expect_in_prompt",
+ [
+ pytest.param("T0-deterministic", False, id="t0-telemetry-only"),
+ pytest.param("T2-never", False, id="t2-telemetry-only"),
+ pytest.param("T1-agent", True, id="t1-prompt-and-telemetry"),
+ ],
+)
+def test_familiarity_computed_on_every_tier_but_prompted_only_on_t1(
+ monkeypatch: pytest.MonkeyPatch, tier: str, expect_in_prompt: bool
+) -> None:
+ # Reintroducing the old T1-only guard would silently zero the familiarity
+ # telemetry on T0/T2 runs — the per-subsystem trend data it exists for —
+ # while attaching it to non-T1 classifications would change those prompts.
+ fam = AuthorFamiliarity(
+ band="STRONG",
+ blame_overlap_pct=61.5,
+ modified_lines_owned=8,
+ modified_lines_total=13,
+ prior_prs_in_paths=4,
+ days_since_last_touch=12,
+ files_prev_count=2,
+ files_total=3,
+ capped=False,
+ top_prior_authors=(),
+ )
+ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")
+ pipeline.pr = _fake_pr(head_sha="abc123")
+ pipeline.classification = {"tier": tier, "familiarity": None}
+ monkeypatch.setattr(pipeline, "_compute_familiarity", lambda: fam)
+
+ pipeline._maybe_compute_familiarity()
+
+ assert pipeline.familiarity is fam
+ assert pipeline.classification["familiarity"] == (fam if expect_in_prompt else None)
+
+
+ "populated",
+ [
+ pytest.param(True, id="signals-present"),
+ pytest.param(False, id="signals-absent-on-early-exit-paths"),
+ ],
+)
+def test_capture_review_completed_includes_familiarity_and_provenance(
+ monkeypatch: pytest.MonkeyPatch, populated: bool
+) -> None:
+ # Downstream HogQL queries key on these property names and null/empty
+ # defaults; a rename or a crash on the early-exit paths (bot author, WAIT —
+ # familiarity and provenance still None) breaks the provenance and
+ # knowledge-trend dimensions silently.
+ fake_posthog = MagicMock()
+ monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", True)
+ monkeypatch.setattr(review_pr, "posthoganalytics", fake_posthog, raising=False)
+
+ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")
+ pipeline.pr = _fake_pr(head_sha="abc123")
+ if populated:
+ pipeline.classification = {
+ "ownership": {"teams": ["@PostHog/team-devex"], "team_count": 1, "individuals": [], "cross_team": False}
+ }
+ pipeline.familiarity = AuthorFamiliarity(
+ band="MODERATE",
+ blame_overlap_pct=12.34,
+ modified_lines_owned=2,
+ modified_lines_total=16,
+ prior_prs_in_paths=2,
+ days_since_last_touch=30,
+ files_prev_count=1,
+ files_total=3,
+ capped=False,
+ top_prior_authors=("Alice",),
+ )
+ pipeline.provenance = CommitProvenance(
+ commit_count=3,
+ agent_commit_count=2,
+ generated_by=("PostHog Code",),
+ task_ids=("task-1", "task-2"),
+ )
+
+ pipeline._capture_review_completed("PASSED", "APPROVE")
+
+ props = fake_posthog.capture.call_args.kwargs["properties"]
+ if populated:
+ assert props["stamphog_owner_teams"] == ["@PostHog/team-devex"]
+ assert props["stamphog_familiarity_band"] == "MODERATE"
+ assert props["stamphog_familiarity_blame_overlap_pct"] == 12.3
+ assert props["stamphog_familiarity_prior_prs_in_paths"] == 2
+ assert props["stamphog_familiarity_days_since_last_touch"] == 30
+ assert props["stamphog_agent_authored"] is True
+ assert props["stamphog_agent_commit_count"] == 2
+ assert props["stamphog_commit_count"] == 3
+ assert props["stamphog_generated_by"] == ["PostHog Code"]
+ assert props["stamphog_task_ids"] == ["task-1", "task-2"]
+ else:
+ assert props["stamphog_owner_teams"] == []
+ assert props["stamphog_familiarity_band"] == ""
+ assert props["stamphog_familiarity_blame_overlap_pct"] is None
+ assert props["stamphog_agent_authored"] is None
+ assert props["stamphog_generated_by"] == []
+ assert props["stamphog_task_ids"] == []
+
+
def test_capture_review_completed_merges_server_extras_base_wins(monkeypatch: pytest.MonkeyPatch) -> None:
# The hosted server stamps runtime/team context through STAMPHOG_EXTRA_PROPERTIES; the event's
# own props must win on collision so a stamped extra can never spoof e.g. the repo.