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(devex): approve workflows paths in stamphog only for team-workflows (#112451)

Julian Bez80379fb40937
diff --git a/.stamphog/README.md b/.stamphog/README.md
index a4cd934db600..f8e1aebeaa19 100644
--- a/.stamphog/README.md
+++ b/.stamphog/README.md
@@ -14,6 +14,7 @@ It overrides `deny` and `allow`, and the differences are:
- `infra_cicd` also matches `.github/pr-deploy`.
- `stamphog_policy` also matches `products/stamphog/backend/logic/policy_defaults/`, `packages/owners-yaml/`, `owners.yaml` and `product.yaml`, because those are gate inputs here.
- `devex_guardrails` is an extra category. It matches the semgrep rules, ratchet baselines, invariant tests and lint code that guard the house patterns, so an edit to a guard always gets a human review.
+- `workflows_delivery` is an extra, owner-only category. It matches the CDP, Workflows and Messaging API, models and plugin-server worker code, and its `exempt_author_teams` lets stamphog approve there only for authors on `team-workflows`.
- `allow` also lists `.github/CODEOWNERS`.
- Every `rationale` records the false positives that shaped the rule in this repository.
diff --git a/.stamphog/policy.yml b/.stamphog/policy.yml
index 17bca26ab791..8c60f27410b8 100644
--- a/.stamphog/policy.yml
+++ b/.stamphog/policy.yml
@@ -159,6 +159,20 @@ deny:
- '^tools/hogli-commands/hogli_commands/(api_ratchet|projections|tach_lint)\.py$'
- '^tools/hogli-commands/hogli_commands/product_structure\.yaml$'
- '^tools/hogli-commands/hogli_commands/product/(baseline|checks|crossings|isolation|reverse_accessors)\.py$'
+ workflows_delivery:
+ description: 'CDP, Workflows and Messaging code that decides which customer configurations exist and what gets delivered.'
+ rationale: "Owner-only: stamphog approves team-workflows' own changes here and refuses everyone else's. Another team's change here breaks a customer silently: the API and models decide which of a tenant's rows get listed and updated, and the plugin-server worker decides what gets delivered. Teams usually edit these paths to carve out an exception for their own rows, their tests still pass, and existing customer configurations stop appearing or stop being delivered. Product frontends stay out, because a mistake there is visible. As in CODEOWNERS, only the API test directories and `*.test.ts` files stay out. Nothing else under the worker does: the template, legacy-plugin, legacy-webhook and segment directories hold live delivery code and mutable registries."
+ match:
+ paths:
+ - '^products/cdp/backend/(api|models)/'
+ - '^products/workflows/backend/(facade|presentation|models)/'
+ - '^products/messaging/backend/(api|models)/'
+ - '^nodejs/src/cdp/[\s\S]*(?<!\.test\.ts)\Z'
+ exempt_path_prefixes:
+ - 'products/cdp/backend/api/test/'
+ - 'products/messaging/backend/api/test/'
+ exempt_author_teams:
+ - 'team-workflows'
allow:
path_patterns:
- 'docs/'
diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.md
index 015542cc2a41..058b61eccd20 100644
--- a/products/stamphog/AGENTS.md
+++ b/products/stamphog/AGENTS.md
@@ -251,6 +251,8 @@ Inputs `review_pr.py` fetches over the network reach the sandbox through the con
dropping one is a silent behavior change rather than a missing section. `author_team_slugs` feeds
`author_on_owning_team`, which the reviewer prompt reads with a default of `True`, so an unset key
tells the reviewer that every author owns the code they touched.
+The same set decides a deny category's `exempt_author_teams`, and there an unset key fails closed: every author is denied, the owning team included.
+Never fill the set from anything the PR controls: it is the only thing that lets stamphog approve an owner-only path.
The sandbox checkout is shallow and holds no PR history, so a hosted context always carries `merge_base_sha` (the engine diffs `merge_base..head`) and `commit_messages` (the provenance trailers).
Without those keys (a manual `review_pr.py` run) the engine reads git history instead.
diff --git a/products/stamphog/backend/logic/github_client.py b/products/stamphog/backend/logic/github_client.py
index 275ed2a07c19..11a4989c710b 100644
--- a/products/stamphog/backend/logic/github_client.py
+++ b/products/stamphog/backend/logic/github_client.py
@@ -1493,28 +1493,23 @@ class StamphogGitHubClient:
)
return self._json(response, path)
- def get_user_team_slugs(self, org: str, login: str) -> list[str]:
- """Return the sorted GitHub team slugs ``login`` belongs to within ``org`` (GraphQL).
-
- Best-effort: this feeds digest audience routing, never a hard requirement, so every failure
- mode (HTTP error, GraphQL ``errors`` — typically the App installation missing the org's
- "Members: read" permission — or a null organization) logs a warning and returns ``[]`` instead
- of raising.
- """
+ def _team_lookup_page(self, org: str, login: str, after: str | None) -> dict | None:
+ """One page of the teams that ``login`` belongs to in ``org``, or None after logging a failure."""
query = (
- "query($org: String!, $login: String!) { "
- "organization(login: $org) { teams(first: 100, userLogins: [$login]) { nodes { slug } } } }"
+ "query($org: String!, $login: String!, $after: String) { "
+ "organization(login: $org) { teams(first: 100, after: $after, userLogins: [$login]) { "
+ "pageInfo { hasNextPage endCursor } nodes { slug } } } }"
)
try:
response = self._request(
"POST",
"/graphql",
endpoint="/graphql",
- json_body={"query": query, "variables": {"org": org, "login": login}},
+ json_body={"query": query, "variables": {"org": org, "login": login, "after": after}},
)
except Exception:
logger.warning("stamphog_github_team_lookup_request_failed", org=org, login=login, exc_info=True)
- return []
+ return None
if response.status_code != 200:
logger.warning(
@@ -1524,13 +1519,13 @@ class StamphogGitHubClient:
status_code=response.status_code,
body=response.text[:200],
)
- return []
+ return None
try:
data = self._json(response, "/graphql")
except StamphogGitHubError:
logger.warning("stamphog_github_team_lookup_non_json_response", org=org, login=login)
- return []
+ return None
if not isinstance(data, dict) or data.get("errors"):
logger.warning(
@@ -1539,15 +1534,39 @@ class StamphogGitHubClient:
login=login,
errors=(data or {}).get("errors") if isinstance(data, dict) else None,
)
- return []
+ return None
organization = (data.get("data") or {}).get("organization")
if not organization:
logger.warning("stamphog_github_team_lookup_null_organization", org=org, login=login)
- return []
+ return None
+ return organization.get("teams") or {}
- nodes = (organization.get("teams") or {}).get("nodes") or []
- return sorted({node["slug"] for node in nodes if isinstance(node, dict) and node.get("slug")})
+ def get_user_team_slugs(self, org: str, login: str) -> list[str]:
+ """Return the sorted GitHub team slugs ``login`` belongs to within ``org`` (GraphQL).
+
+ Every failure mode (HTTP error, GraphQL ``errors`` — typically the App installation missing the
+ org's "Members: read" permission — or a null organization) logs a warning and returns ``[]``
+ instead of raising. The engine reads ``[]`` as "on no team", which is the safe direction: the
+ reviewer treats the author as outside the owning team, and a deny category's
+ ``exempt_author_teams`` exempts nobody, so the owning team's PRs on those paths are refused.
+ The engine treats the list as complete, so every page is read.
+ """
+ slugs: set[str] = set()
+ after: str | None = None
+ for _ in range(_MAX_PAGES):
+ teams = self._team_lookup_page(org, login, after)
+ if teams is None:
+ return []
+ slugs.update(
+ node["slug"] for node in teams.get("nodes") or [] if isinstance(node, dict) and node.get("slug")
+ )
+ page_info = teams.get("pageInfo") or {}
+ if not page_info.get("hasNextPage") or not page_info.get("endCursor"):
+ return sorted(slugs)
+ after = page_info["endCursor"]
+ logger.warning("stamphog_github_team_lookup_page_cap", org=org, login=login, pages=_MAX_PAGES)
+ return sorted(slugs)
def _find_sticky_comment_id(self, repo: str, number: int) -> int | None:
"""Return the id of the App's own sticky comment on the PR, or ``None`` if there isn't one.
diff --git a/products/stamphog/backend/tests/test_logic.py b/products/stamphog/backend/tests/test_logic.py
index 2c993c0c5d19..50ec98bf2e19 100644
--- a/products/stamphog/backend/tests/test_logic.py
+++ b/products/stamphog/backend/tests/test_logic.py
@@ -4,7 +4,7 @@ import threading
import subprocess
from collections.abc import Callable
from pathlib import Path
-from typing import cast
+from typing import TypeVar, cast
import pytest
from unittest.mock import MagicMock, patch
@@ -47,6 +47,8 @@ from products.stamphog.backend.temporal.registry import ACTIVITIES
from products.stamphog.backend.tests import fakes
from products.stamphog.backend.tests.conftest import _generate_app_private_key
+T = TypeVar("T")
+
# The gate/policy engine lives in packages/pr-approval-agent, and its own suite covers it
# (test_gates.py, test_policy.py). The server runs it in a child process (the sandbox, or the
# worker's pre-check) and never ports it, so there is no copy to test here. Only the defensive
@@ -560,25 +562,52 @@ class DigestConfigFetchTests(SimpleTestCase):
_GH = "products.stamphog.backend.logic.github_client"
-class GetPrReviewThreadsTests(SimpleTestCase):
- def _fetch(self, *graphql_responses: fakes.FakeResponse) -> list[dict]:
- # Stub the network boundary (github_request): the access-token mint is answered so the client's
- # _request machinery runs for real, and /graphql calls consume the scripted responses in order
- # (the last one repeats, so single-response tests behave as before).
- remaining = list(graphql_responses)
+def _with_scripted_graphql(call: Callable[[StamphogGitHubClient], T], *graphql_responses: fakes.FakeResponse) -> T:
+ # Stub the network boundary (github_request): the access-token mint is answered so the client's
+ # _request machinery runs for real, and /graphql calls consume the scripted responses in order
+ # (the last one repeats, so single-response tests behave as before).
+ remaining = list(graphql_responses)
- def fake_request(method: str, url: str, **kwargs: object) -> fakes.FakeResponse:
- if url.endswith("/access_tokens"):
- return fakes.FakeResponse(201, json_data={"token": "t", "expires_at": "2999-01-01T00:00:00Z"})
- return remaining.pop(0) if len(remaining) > 1 else remaining[0]
+ def fake_request(method: str, url: str, **kwargs: object) -> fakes.FakeResponse:
+ if url.endswith("/access_tokens"):
+ return fakes.FakeResponse(201, json_data={"token": "t", "expires_at": "2999-01-01T00:00:00Z"})
+ return remaining.pop(0) if len(remaining) > 1 else remaining[0]
- with (
- override_settings(STAMPHOG_GITHUB_APP_ID="1", STAMPHOG_GITHUB_APP_PRIVATE_KEY=_generate_app_private_key()),
- patch(f"{_GH}.github_request", fake_request),
- patch(f"{_GH}.remember_observed_core_limit", lambda *a, **k: None),
- patch(f"{_GH}.raise_if_github_rate_limited", lambda *a, **k: None),
- ):
- return StamphogGitHubClient("123").get_pr_review_threads("acme/widgets", 5)
+ with (
+ override_settings(STAMPHOG_GITHUB_APP_ID="1", STAMPHOG_GITHUB_APP_PRIVATE_KEY=_generate_app_private_key()),
+ patch(f"{_GH}.github_request", fake_request),
+ patch(f"{_GH}.remember_observed_core_limit", lambda *a, **k: None),
+ patch(f"{_GH}.raise_if_github_rate_limited", lambda *a, **k: None),
+ ):
+ return call(StamphogGitHubClient("123"))
+
+
+def _teams_page(slugs: list[str], *, has_next: bool) -> fakes.FakeResponse:
+ teams = {"pageInfo": {"hasNextPage": has_next, "endCursor": "c"}, "nodes": [{"slug": s} for s in slugs]}
+ return fakes.FakeResponse(200, json_data={"data": {"organization": {"teams": teams}}})
+
+
+class GetUserTeamSlugsTests(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("later_page_counts", _teams_page(["team-workflows"], has_next=False), ["team-a", "team-workflows"]),
+ ("failed_later_page_fails_closed", fakes.FakeResponse(502, text="bad gateway"), []),
+ ]
+ )
+ def test_reads_every_page(self, _name: str, second_page: fakes.FakeResponse, expected: list[str]) -> None:
+ slugs = _with_scripted_graphql(
+ lambda client: client.get_user_team_slugs("acme", "alice"),
+ _teams_page(["team-a"], has_next=True),
+ second_page,
+ )
+ assert slugs == expected
+
+
+class GetPrReviewThreadsTests(SimpleTestCase):
+ def _fetch(self, *graphql_responses: fakes.FakeResponse) -> list[dict]:
+ return _with_scripted_graphql(
+ lambda client: client.get_pr_review_threads("acme/widgets", 5), *graphql_responses
+ )
def _threads_page(self, nodes: list[dict], *, has_next: bool) -> fakes.FakeResponse:
payload = {
diff --git a/products/stamphog/packages/pr-approval-agent/README.md b/products/stamphog/packages/pr-approval-agent/README.md
index c61449e4affe..e8b8d9ba2445 100644
--- a/products/stamphog/packages/pr-approval-agent/README.md
+++ b/products/stamphog/packages/pr-approval-agent/README.md
@@ -335,6 +335,16 @@ So a Cargo.lock bump hard-denies on its own but doesn't silence the scripts guar
A deny category may carry `exempt_path_prefixes`, for code that legitimately looks like a sensitive domain without touching one.
+A deny category may also carry `exempt_author_teams`, a list of bare GitHub team slugs.
+It makes the category owner-only: the category does not deny a PR whose author is on one of the teams, and denies everyone else's, so stamphog approves those paths only for the team that owns them.
+The deny-list gate message names the teams, so a refused author knows who has to review.
+Membership comes from GitHub, never from the PR.
+The hosted server looks up every team the author is on, and a local run asks GitHub per team.
+A failed lookup counts as no team, so the category denies.
+Bot authors are never on a team.
+The `stamphog_policy` category cannot carry the key, because a team that may approve policy edits could widen its own exemption.
+Unlike CODEOWNERS, the category only stops stamphog: any human approval still counts on GitHub.
+
The **migrations** deny-list is bypassed when the `Migration risk` check on the head commit concludes `success` (all migrations classified Safe).
The check is the same signal humans see in the PR's Checks tab.
See `migration_risk.py` for how the engine reads it.
diff --git a/products/stamphog/packages/pr-approval-agent/gates.py b/products/stamphog/packages/pr-approval-agent/gates.py
index cc7c94892711..a1222ea46924 100644
--- a/products/stamphog/packages/pr-approval-agent/gates.py
+++ b/products/stamphog/packages/pr-approval-agent/gates.py
@@ -498,6 +498,11 @@ def _is_exempt_path(category: str, path: str) -> bool:
return path.lower().startswith(DENY_EXEMPT_PATH_PREFIXES.get(category, ()))
+DENY_EXEMPT_AUTHOR_TEAMS: dict[str, tuple[str, ...]] = {
+ category: cat.exempt_author_teams for category, cat in POLICY.deny.items() if cat.exempt_author_teams
+}
+
+
def category_fully_exempt(category: str, files: list[str]) -> bool:
"""True when every changed file is exempt for this category.
diff --git a/products/stamphog/packages/pr-approval-agent/github.py b/products/stamphog/packages/pr-approval-agent/github.py
index 9212dff312fd..8a9bbaefbe25 100644
--- a/products/stamphog/packages/pr-approval-agent/github.py
+++ b/products/stamphog/packages/pr-approval-agent/github.py
@@ -45,6 +45,9 @@ class PRData:
# Set by the hosted server from GitHub's compare API. Its shallow checkout holds no history, so
# git cannot compute the merge base there (see diff_range).
merge_base_sha: str = ""
+ # Every path the diff touches, unquoted: a rename's old and new name both. `files` names a
+ # rename once, so a deny pattern would miss code moved out of a protected directory.
+ touched_paths: list[str] = field(default_factory=list)
@property
def stacked(self) -> bool:
@@ -55,6 +58,11 @@ class PRData:
def file_paths(self) -> list[str]:
return [f["filename"] for f in self.files]
+ @property
+ def deny_paths(self) -> list[str]:
+ """The paths the deny-list matches: the changed files plus every touched path."""
+ return list(dict.fromkeys([*self.file_paths, *self.touched_paths]))
+
@property
def lines_added(self) -> int:
return sum(f["additions"] for f in self.files)
@@ -505,6 +513,24 @@ def _git_diff_files(base_sha: str, head_sha: str, repo_root: Path, merge_base_sh
return files
+def git_touched_paths(base_sha: str, head_sha: str, repo_root: Path, merge_base_sha: str = "") -> list[str]:
+ """Every path the diff touches, with renames split into their old and new names.
+
+ `-z` keeps git from quoting a path with a newline or a quote in it, which would put a `"` in
+ front of the path and defeat every anchored deny pattern.
+ """
+ result = subprocess.run(
+ ["git", "diff", "--name-only", "--no-renames", "-z", diff_range(base_sha, head_sha, merge_base_sha)],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ cwd=repo_root,
+ )
+ if result.returncode != 0:
+ raise RuntimeError(f"git diff --name-only failed: {result.stderr.strip()}")
+ return [path for path in result.stdout.split("\0") if path]
+
+
def new_diff_file(directory: Path) -> Path:
"""Create a fresh, empty diff file under an unpredictable name inside ``directory``.
@@ -690,6 +716,7 @@ def fetch_pr(pr_number: int, repo: str, repo_root: Path | None = None) -> PRData
git_root = repo_root or Path.cwd()
ensure_commits(pr_number, head_sha, base_ref, base_sha, git_root)
files = _git_diff_files(base_sha, head_sha, git_root)
+ touched_paths = git_touched_paths(base_sha, head_sha, git_root)
review_comments, pr_reactions = _fetch_threads_and_reactions(repo, pr_number, pr["user"]["login"])
@@ -706,6 +733,7 @@ def fetch_pr(pr_number: int, repo: str, repo_root: Path | None = None) -> PRData
base_sha=base_sha,
head_sha=head_sha,
files=files,
+ touched_paths=touched_paths,
reviews=_normalize_reviews_for_prompt(reviews_raw, head_sha),
review_comments=review_comments,
check_runs=check_runs_resp.get("check_runs", []),
@@ -717,11 +745,11 @@ def fetch_pr(pr_number: int, repo: str, repo_root: Path | None = None) -> PRData
)
-def check_team_membership(author: str, team_slug: str) -> bool:
- """Check if author is an active member of the given GitHub team."""
+def check_team_membership(org: str, author: str, team_slug: str) -> bool:
+ """Check if author is an active member of the given GitHub team in ``org``."""
try:
result = subprocess.run(
- ["gh", "api", f"orgs/PostHog/teams/{team_slug}/memberships/{author}"],
+ ["gh", "api", f"orgs/{org}/teams/{team_slug}/memberships/{author}"],
capture_output=True,
text=True,
timeout=10,
diff --git a/products/stamphog/packages/pr-approval-agent/policy.py b/products/stamphog/packages/pr-approval-agent/policy.py
index 40bdf513f654..4f125f4e7a34 100644
--- a/products/stamphog/packages/pr-approval-agent/policy.py
+++ b/products/stamphog/packages/pr-approval-agent/policy.py
@@ -98,6 +98,7 @@ class DenyCategory:
# Scope keys are a subset of {"any", "titles", "paths"}.
match: dict[str, tuple[str, ...]]
exempt_path_prefixes: tuple[str, ...] = ()
+ exempt_author_teams: tuple[str, ...] = ()
@dataclass(frozen=True)
@@ -287,6 +288,23 @@ def _compile_or_raise(pattern: str, context: str) -> None:
raise PolicyError(f"{context}: pattern {pattern!r} does not compile: {exc}") from exc
+_TEAM_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
+
+
+def _parse_exempt_author_teams(category: str, raw: Any) -> tuple[str, ...]:
+ context = f"deny.{category}.exempt_author_teams"
+ _require(isinstance(raw, list), f"{context}: must be a list")
+ # A team that may approve edits to the policy could widen its own exemption.
+ _require(not (raw and category == "stamphog_policy"), f"{context}: the self-governance category exempts nobody")
+ for team in raw:
+ # Membership is matched against bare slugs, so `@PostHog/team-x` would exempt nobody without an error.
+ _require(
+ isinstance(team, str) and bool(_TEAM_SLUG_RE.match(team)),
+ f"{context}: {team!r} is not a bare GitHub team slug like 'team-workflows'",
+ )
+ return tuple(raw)
+
+
def _parse_deny(raw: Any, lockfile_names: Iterable[str]) -> dict[str, DenyCategory]:
_require(isinstance(raw, dict) and bool(raw), "deny: must be a non-empty mapping")
lockfile_patterns = [re.escape(name) for name in sorted(lockfile_names)]
@@ -321,6 +339,7 @@ def _parse_deny(raw: Any, lockfile_names: Iterable[str]) -> dict[str, DenyCatego
rationale=str(spec.get("rationale", "")),
match=match,
exempt_path_prefixes=tuple(str(p) for p in exempt),
+ exempt_author_teams=_parse_exempt_author_teams(category, spec.get("exempt_author_teams", [])),
)
_assert_self_governance(deny)
diff --git a/products/stamphog/packages/pr-approval-agent/review_local.py b/products/stamphog/packages/pr-approval-agent/review_local.py
index 2d528a954a22..839783e5b438 100644
--- a/products/stamphog/packages/pr-approval-agent/review_local.py
+++ b/products/stamphog/packages/pr-approval-agent/review_local.py
@@ -75,6 +75,7 @@ from github import (
_normalize_reviews_for_prompt,
_prompt_worthy_author,
_reaction_emoji,
+ git_touched_paths,
is_bot_author,
pr_provenance,
provenance_from_messages,
@@ -182,8 +183,12 @@ def _build_pr_data(context: dict, *, checkout: bool = True) -> PRData:
base_ref = base.get("ref") or default_branch
files = _git_diff_files(base_sha, head_sha, REPO_ROOT, merge_base_sha) if checkout else []
- if not files:
- files = [_convert_api_file(f) for f in context.get("files") or []]
+ if files:
+ touched_paths = git_touched_paths(base_sha, head_sha, REPO_ROOT, merge_base_sha)
+ else:
+ api_files = context.get("files") or []
+ files = [_convert_api_file(f) for f in api_files]
+ touched_paths = [path for f in api_files for path in (f.get("filename"), f.get("previous_filename")) if path]
# Drop only EMPTY COMMENTED reviews from the offline reviews. A bare COMMENTED top-level review
# carries no readable body — yet _summarize_assurance would surface its author as a current-head
@@ -259,6 +264,7 @@ def _build_pr_data(context: dict, *, checkout: bool = True) -> PRData:
head_sha=head_sha,
merge_base_sha=merge_base_sha,
files=files,
+ touched_paths=touched_paths,
reviews=_normalize_reviews_for_prompt(reviews, head_sha),
review_comments=review_comments,
check_runs=context.get("check_runs") or [],
@@ -283,54 +289,24 @@ def _context_provenance(context: dict, pr: PRData) -> CommitProvenance | None:
return pr_provenance(pr.base_sha, pr.head_sha, REPO_ROOT)
-def _apply_ownership_summary(pipeline: Pipeline, author_team_slugs: set[str]) -> None:
- """Mirror Pipeline._summarize_ownership with team membership injected instead of fetched.
-
- review_pr.py resolves membership with one `gh` call per owning team. The sandbox holds no
- token, so the server supplies every team that the author belongs to, and this function does the
- intersection.
+def _author_team_slugs(context: dict) -> set[str]:
+ """Every team that the server found the author on, for the pipeline's membership checks.
- `author_on_owning_team` matters beyond the summary text. The reviewer prompt reads that key with
- a default of True, so an unset key tells the reviewer that the author owns the code, whoever
- opened the PR. An unresolvable lookup arrives as an empty set and yields "not on any owning
- team". review_pr.py fails in the same direction, and that direction is the safe one for a bot that
- approves.
+ review_pr.py asks GitHub once per team. The sandbox holds no token, so the server supplies the set.
+ It decides two things. The reviewer prompt reads `author_on_owning_team` with a default of True,
+ so the ownership summary must always set it. A deny category's `exempt_author_teams` reads it too.
+ An unresolvable lookup arrives as an empty set, which yields "not on any owning team" and denies
+ owner-only paths. review_pr.py fails in the same direction, and that direction is the safe one
+ for a bot that approves.
"""
- cl = pipeline.classification
- ownership = cl.get("ownership", {})
- individuals = ownership.get("individuals", [])
- teams = ownership.get("teams", [])
- if ownership.get("team_count", 0) == 0 and not individuals:
- cl["ownership_summary"] = "no owned paths touched"
- return
+ return {str(slug) for slug in context.get("author_team_slugs") or []}
+
- author = pipeline.pr.author
- author_teams = [team for team in teams if team.split("/")[-1] in author_team_slugs]
-
- parts = []
- if teams:
- parts.append(f"touches {', '.join(teams)}")
- if individuals:
- # Individuals never enter the membership check. The author either is one of them or is
- # not.
- suffix = f" (author {author} is one of them)" if f"@{author}" in individuals else ""
- parts.append(f"individually owned by {', '.join(individuals)}{suffix}")
- if author_teams:
- parts.append(f"author {author} is on {', '.join(author_teams)}")
- elif teams:
- parts.append(f"author {author} is not on any owning team")
- if ownership.get("cross_team"):
- parts.append("cross-team change")
-
- cl["ownership_summary"] = "; ".join(parts)
- cl["author_on_owning_team"] = bool(author_teams)
-
-
-def _run_gates_offline(pipeline: Pipeline, author_team_slugs: set[str]) -> None:
+def _run_gates_offline(pipeline: Pipeline) -> None:
"""Run the four deterministic gate checks, the same ones that _run_gates runs.
- Mirrors Pipeline._run_gates, and replaces _summarize_ownership's `gh` membership lookup with the
- server-injected team set (see _apply_ownership_summary).
+ Mirrors Pipeline._run_gates without the console output. Set `pipeline.author_team_slugs` first
+ (see _author_team_slugs), or the membership checks call `gh`, which the sandbox cannot do.
"""
gates = [
("prerequisites", pipeline._check_prerequisites),
@@ -342,7 +318,7 @@ def _run_gates_offline(pipeline: Pipeline, author_team_slugs: set[str]) -> None:
passed, message = check()
pipeline.gate_results.append(GateResult(name, passed, message))
- _apply_ownership_summary(pipeline, author_team_slugs)
+ pipeline._summarize_ownership()
def _familiarity_offline(
@@ -597,8 +573,9 @@ def pregate(context: dict) -> dict:
pipeline._refuse_bot_author()
return {**outcome, "final": True, "result": pipeline.to_dict()}
+ pipeline.author_team_slugs = _author_team_slugs(context)
pipeline._classify()
- _run_gates_offline(pipeline, {str(slug) for slug in context.get("author_team_slugs") or []})
+ _run_gates_offline(pipeline)
if _blocked_only_by_pending_migration_check(pipeline):
if not _pending_migration_outcome_is_known(pipeline, folder_policies_known):
return {**outcome, "not_final_reason": "pending_migration_check"}
@@ -644,8 +621,9 @@ def run(context: dict) -> dict:
try:
with _timed_phase("gates"):
+ pipeline.author_team_slugs = _author_team_slugs(context)
pipeline._classify()
- _run_gates_offline(pipeline, {str(slug) for slug in context.get("author_team_slugs") or []})
+ _run_gates_offline(pipeline)
gate_verdict = pipeline._gate_verdict()
# A `Migration risk` check that has not reported yet is a race with CI, and not a judgment
diff --git a/products/stamphog/packages/pr-approval-agent/review_pr.py b/products/stamphog/packages/pr-approval-agent/review_pr.py
index 09e0c20e9fb3..3b5a8a5aee22 100644
--- a/products/stamphog/packages/pr-approval-agent/review_pr.py
+++ b/products/stamphog/packages/pr-approval-agent/review_pr.py
@@ -36,6 +36,7 @@ from typing import TYPE_CHECKING
from familiarity import AuthorFamiliarity, compute_familiarity, familiarity_evidence
from gates import (
+ DENY_EXEMPT_AUTHOR_TEAMS,
MAX_FILES,
MAX_LINES,
POLICY,
@@ -180,6 +181,14 @@ class GateResult:
details: dict = field(default_factory=dict)
+def _describe_deny_category(category: str) -> str:
+ """Name a denied category, and for an owner-only one, the teams that stamphog approves there."""
+ teams = DENY_EXEMPT_AUTHOR_TEAMS.get(category)
+ if not teams:
+ return category
+ return f"{category} (stamphog approves these paths only for authors on {', '.join(teams)})"
+
+
# ── Pipeline ─────────────────────────────────────────────────────
@@ -218,6 +227,9 @@ class Pipeline:
# git tree. The manifest scripts scan reads file text from git, so it is skipped there. That
# can only miss a deny, never add one, and the sandbox review runs the scan again.
self.checkout = checkout
+ # Every GitHub team the author is on, set by the hosted runtime because the sandbox holds no
+ # token. None means a local run, which asks GitHub per team instead.
+ self.author_team_slugs: set[str] | None = None
self._wait_refetched_pr = False
self.pr: PRData | None = None
self.provenance: CommitProvenance | None = None
@@ -407,7 +419,7 @@ class Pipeline:
breadth = scope_breadth(top_dirs)
cc = parse_conventional_commit(pr.title)
safe_migrations = safe_migration_files(pr.check_runs, file_paths)
- deny = detect_deny_categories(file_paths, ignored_files=safe_migrations)
+ deny = detect_deny_categories(pr.deny_paths, ignored_files=safe_migrations)
dep_manifests = dependency_manifests_without_lockfile(file_paths)
# Deterministic first line for the manifest scripts risk: an edit to
# scripts/lifecycle/build keys hard-denies rather than resting solely
@@ -419,6 +431,11 @@ class Pipeline:
)
if risky_manifests and "deps_toolchain" not in deny:
deny = sorted([*deny, "deps_toolchain"])
+ deny = [
+ category
+ for category in deny
+ if not any(self._author_on_team(team) for team in DENY_EXEMPT_AUTHOR_TEAMS.get(category, ()))
+ ]
title_flags = [
c
for c in detect_title_scrutiny_flags(pr.title)
@@ -487,6 +504,11 @@ class Pipeline:
"review_trigger": self.review_trigger,
}
+ def _author_on_team(self, team_slug: str) -> bool:
+ if self.author_team_slugs is not None:
+ return team_slug in self.author_team_slugs
+ return check_team_membership(self.repo.split("/")[0], self.pr.author, team_slug)
+
def _summarize_assurance(self) -> dict:
"""Deterministic pre-digest of review state for the TRUSTED prompt block.
@@ -617,12 +639,13 @@ class Pipeline:
def _check_deny_list(self) -> tuple[bool, str]:
deny = self.classification["deny_categories"]
+ matches = ", ".join(_describe_deny_category(c) for c in deny)
risky = self.classification.get("manifest_script_changes", [])
if risky:
risky_names = ", ".join(manifest_basenames(risky))
- return False, f"matches: {', '.join(deny)} (scripts/hooks changed in {risky_names})"
+ return False, f"matches: {matches} (scripts/hooks changed in {risky_names})"
if deny:
- return False, f"matches: {', '.join(deny)}"
+ return False, f"matches: {matches}"
return True, "no deny categories matched"
def _summarize_ownership(self) -> str:
@@ -637,8 +660,7 @@ class Pipeline:
author = self.pr.author
author_teams = []
for team_raw in teams:
- team_slug = team_raw.split("/")[-1]
- if check_team_membership(author, team_slug):
+ if self._author_on_team(team_raw.split("/")[-1]):
author_teams.append(team_raw)
parts = []
@@ -653,7 +675,7 @@ class Pipeline:
parts.append(f"author {author} is on {', '.join(author_teams)}")
elif teams:
parts.append(f"author {author} is not on any owning team")
- if ownership["cross_team"]:
+ if ownership.get("cross_team"):
parts.append("cross-team change")
self.classification["ownership_summary"] = "; ".join(parts)
diff --git a/products/stamphog/packages/pr-approval-agent/test_github.py b/products/stamphog/packages/pr-approval-agent/test_github.py
index e9adcc6f6704..60896399981f 100644
--- a/products/stamphog/packages/pr-approval-agent/test_github.py
+++ b/products/stamphog/packages/pr-approval-agent/test_github.py
@@ -15,6 +15,7 @@ from github import (
_reaction_emoji,
_trusted_reactor_predicate,
ensure_commits,
+ git_touched_paths,
is_bot_author,
parse_provenance_trailers,
write_pr_diff,
@@ -141,6 +142,25 @@ def _git(cwd: Path, *args: str) -> str:
return result.stdout.strip()
+def test_touched_paths_carry_both_rename_names_unquoted(tmp_path: Path) -> None:
+ repo = tmp_path / "repo"
+ _git(tmp_path, "init", "--quiet", "-b", "main", str(repo))
+ _git(repo, "config", "user.name", "t")
+ _git(repo, "config", "user.email", "[email protected]")
+ (repo / "models").mkdir()
+ (repo / "models" / "flow.py").write_text("\n".join(f"line {i}" for i in range(20)) + "\n")
+ _git(repo, "add", ".")
+ _git(repo, "commit", "--quiet", "-m", "root")
+ base = _git(repo, "rev-parse", "HEAD")
+ _git(repo, "mv", "models/flow.py", "flow.py")
+ (repo / "odd\nname.py").write_text("x\n")
+ _git(repo, "add", "--all")
+ _git(repo, "commit", "--quiet", "-m", "move")
+ head = _git(repo, "rev-parse", "HEAD")
+
+ assert sorted(git_touched_paths(base, head, repo)) == ["flow.py", "models/flow.py", "odd\nname.py"]
+
+
def test_shallow_checkout_diffs_from_the_given_merge_base(tmp_path: Path) -> None:
# The hosted sandbox holds only the PR head and the merge base, each at depth 1, so git cannot
# compute base...head there. With the merge base given, the file list and the diff text must
diff --git a/products/stamphog/packages/pr-approval-agent/test_policy.py b/products/stamphog/packages/pr-approval-agent/test_policy.py
index 54f3ff1bf3e5..20c15ddf2aca 100644
--- a/products/stamphog/packages/pr-approval-agent/test_policy.py
+++ b/products/stamphog/packages/pr-approval-agent/test_policy.py
@@ -139,6 +139,14 @@ OLD_DENY_PATTERN_DEFS = {
"^tools/hogli-commands/hogli_commands/product/(baseline|checks|crossings|isolation|reverse_accessors)\\.py$",
]
},
+ "workflows_delivery": {
+ "paths": [
+ "^products/cdp/backend/(api|models)/",
+ "^products/workflows/backend/(facade|presentation|models)/",
+ "^products/messaging/backend/(api|models)/",
+ "^nodejs/src/cdp/[\\s\\S]*(?<!\\.test\\.ts)\\Z",
+ ]
+ },
}
OLD_ALLOW_ONLY_EXTENSIONS = {
".txt",
@@ -242,6 +250,14 @@ def _rename_deps_toolchain(d: dict) -> None:
d["deny"]["dependencies_toolchain"] = d["deny"].pop("deps_toolchain")
+def _self_governance_exempts_a_team(d: dict) -> None:
+ d["deny"]["stamphog_policy"]["exempt_author_teams"] = ["team-devex"]
+
+
+def _exempt_author_team_with_org_prefix(d: dict) -> None:
+ d["deny"]["auth"]["exempt_author_teams"] = ["@PostHog/team-security"]
+
+
def _ownership_unknown_format(d: dict) -> None:
d["ownership"]["sources"][0]["format"] = "svn-blame"
@@ -276,6 +292,8 @@ def _ownership_wrong_locator_for_format(d: dict) -> None:
_out_of_contract_delegation,
_ceiling_under_global_default,
_rename_deps_toolchain,
+ _self_governance_exempts_a_team,
+ _exempt_author_team_with_org_prefix,
_ownership_unknown_format,
_ownership_both_locators,
_ownership_no_locator,
diff --git a/products/stamphog/packages/pr-approval-agent/test_review_local.py b/products/stamphog/packages/pr-approval-agent/test_review_local.py
index 08277744f454..7ccca77ef904 100644
--- a/products/stamphog/packages/pr-approval-agent/test_review_local.py
+++ b/products/stamphog/packages/pr-approval-agent/test_review_local.py
@@ -116,8 +116,9 @@ def test_ownership_summary_reflects_author_team_membership(
# which reads the key with a default of True. An unset key tells the reviewer that every author
# owns the code that they touched, and the note then never appears on a hosted review.
pipeline = _ownership_pipeline(ownership)
+ pipeline.author_team_slugs = author_team_slugs
- review_local._apply_ownership_summary(pipeline, author_team_slugs)
+ pipeline._summarize_ownership()
assert pipeline.classification["ownership_summary"] == expected_summary
assert pipeline.classification.get("author_on_owning_team") is expected_on_team
@@ -575,11 +576,14 @@ def _pregate_context(
user_type: str = "User",
check_runs: list[dict] | None = None,
folder_policies_known: bool = False,
+ author_team_slugs: list[str] | None = None,
) -> dict:
context = _run_context(files, check_runs)
context["pr"] = {**context["pr"], "draft": draft, "user": {"login": "alice", "type": user_type}}
if folder_policies_known:
context["folder_policies_known"] = True
+ if author_team_slugs is not None:
+ context["author_team_slugs"] = author_team_slugs
return context
@@ -642,6 +646,49 @@ _PENDING_MIGRATION_CHECK = [{"name": "Migration risk", "status": "in_progress",
id="pending-migration-check-with-a-manifest",
),
pytest.param(_pregate_context([_api_file("src/app.py")]), None, False, id="clean-t1"),
+ pytest.param(
+ _pregate_context([_api_file("nodejs/src/cdp/consumers/delivery.ts")], author_team_slugs=["team-replay"]),
+ "REFUSED",
+ True,
+ id="owner-only-path-from-another-team",
+ ),
+ pytest.param(
+ _pregate_context([_api_file("nodejs/src/cdp/consumers/delivery.ts")]),
+ "REFUSED",
+ True,
+ id="owner-only-path-without-team-lookup",
+ ),
+ pytest.param(
+ _pregate_context([_api_file("nodejs/src/cdp/consumers/delivery.ts")], author_team_slugs=["team-workflows"]),
+ None,
+ False,
+ id="owner-only-path-from-the-owning-team",
+ ),
+ pytest.param(
+ _pregate_context([_api_file("nodejs/src/cdp/consumers/delivery.test.ts")]),
+ None,
+ False,
+ id="owner-only-path-test-file",
+ ),
+ pytest.param(
+ _pregate_context(
+ [
+ {
+ **_api_file("products/workflows/backend/hog_flow.py", status="renamed"),
+ "previous_filename": "products/workflows/backend/models/hog_flow.py",
+ }
+ ]
+ ),
+ "REFUSED",
+ True,
+ id="owner-only-path-renamed-out",
+ ),
+ pytest.param(
+ _pregate_context([_api_file("nodejs/src/cdp/worker\n.ts")]),
+ "REFUSED",
+ True,
+ id="owner-only-path-with-a-newline",
+ ),
],
)
def test_pregate_is_final_only_where_the_full_review_agrees(