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): support additive deny exceptions (#115594)

Sven Langec4545bc76c04
diff --git a/products/stamphog/README.md b/products/stamphog/README.md
index aa5b1cec0c7d..07fdfa92ab55 100644
--- a/products/stamphog/README.md
+++ b/products/stamphog/README.md
@@ -104,6 +104,36 @@ The merged document is validated by the engine's strict loader inside the sandbo
A `policy.yml` that is present but unusable, such as malformed YAML or a non-mapping root, fails the run closed.
The repository declared something, so reviewing under pure defaults would be wrong.
+### Deny exceptions
+
+A repository can declare narrow exceptions without copying the hosted `deny` section:
+
+```yaml
+deny_exceptions:
+ billing:
+ - keyword: billing
+ path_prefixes: [apps/, argocd/, shared/, state/, charts/]
+ extensions: [.yaml, .yml]
+ infra_cicd:
+ - path_prefixes: [.github/]
+```
+
+The example permits agent review of billing-service deployment YAML and GitHub automation paths.
+The billing exception skips only the `billing` pattern; `payment`, `stripe`, `invoice`, and `pricing` still match.
+New billing patterns and other categories stay inherited because this file does not replace `deny`.
+
+Every rule needs literal directory prefixes relative to the repository root, with a trailing slash.
+The optional `extensions` list restricts the rule to those file suffixes.
+The optional `keyword` must name an existing literal path-capable pattern in that category; omitting it exempts the category within the selected paths.
+All selectors in a rule must match, and multiple rules provide alternative exceptions.
+Path prefixes and extensions match without regard to case.
+
+An exception that lifts a denial sends the PR to `T1-agent`, including YAML-only and test-only changes.
+The reviewer still evaluates actual effects, independent assurance, and unresolved concerns; exceptions do not grant approval.
+Title scrutiny, other categories, prerequisites, and size gates remain active.
+Unknown categories or fields, malformed selectors, and any `stamphog_policy` exception fail the run closed.
+Exception files use the same default-branch trust boundary as the rest of `policy.yml`, so editing them requires human review.
+
### The `digest:` key
`policy.yml` may also carry a `digest:` section.
diff --git a/products/stamphog/backend/tests/test_policy_defaults.py b/products/stamphog/backend/tests/test_policy_defaults.py
index ed66c1f75f04..f454f1fd486f 100644
--- a/products/stamphog/backend/tests/test_policy_defaults.py
+++ b/products/stamphog/backend/tests/test_policy_defaults.py
@@ -17,6 +17,7 @@ sys.path.insert(0, str(_ENGINE_DIR))
import gates # noqa: E402
import policy # noqa: E402
+from products.stamphog.backend.logic.engine_pregate import run_engine_pregate # noqa: E402
from products.stamphog.backend.temporal import activities # noqa: E402
from products.stamphog.backend.temporal.activities import ( # noqa: E402
_clone_pr,
@@ -99,6 +100,58 @@ def test_overlay_of_partial_repo_policy_validates_through_engine_loader(tmp_path
assert loaded.size_gate.max_files == 7
+ "path, denied_category",
+ [
+ ("apps/billing/values.yaml", None),
+ (".github/workflows/maintenance.yml", None),
+ ("apps/billing-ledger/values.yaml", "billing"),
+ (".github/workflows/restricted.yml", "new_guard"),
+ ("apps/billing/secret.yaml", "crypto_secrets"),
+ (".github/CODEOWNERS", "stamphog_policy"),
+ ],
+)
+def test_deny_exceptions_preserve_inherited_guards(path: str, denied_category: str | None) -> None:
+ default = yaml.safe_load(_DEFAULT_POLICY.read_text())
+ default["deny"]["billing"]["match"]["any"].append("ledger")
+ default["deny"]["new_guard"] = {"match": {"paths": [r"^\.github/workflows/restricted\.yml$"]}}
+ repo_policy = yaml.safe_dump(
+ {
+ "deny_exceptions": {
+ "billing": [
+ {
+ "keyword": "billing",
+ "path_prefixes": ["apps/"],
+ "extensions": [".yaml", ".yml"],
+ }
+ ],
+ "infra_cicd": [{"path_prefixes": [".github/"]}],
+ }
+ }
+ )
+ effective = activities._overlay_policy_yaml("example/widgets", yaml.safe_dump(default), repo_policy)
+ context = {
+ "repo": "example/widgets",
+ "pr": {
+ "number": 1,
+ "title": "chore: update configuration",
+ "state": "open",
+ "user": {"login": "maintainer", "type": "User"},
+ },
+ "files": [{"filename": path, "status": "modified", "additions": 1, "deletions": 1, "patch": "+setting"}],
+ "folder_policies_known": True,
+ }
+ outcome = run_engine_pregate(context, {STAMPHOG_POLICY_ENTRYPOINT: effective}, environment={})
+ if denied_category is None:
+ assert not outcome.final
+ assert outcome.not_final_reason == "no_failing_gate"
+ else:
+ assert outcome.result is not None
+ assert outcome.final
+ assert outcome.result["final_verdict"] == "REFUSED"
+ assert denied_category in outcome.result["classification"]["deny_categories"]
+
+
def test_repo_guidance_and_steering_pass_through() -> None:
files = {
STAMPHOG_REVIEW_GUIDANCE_PATH: "repo norms\n",
diff --git a/products/stamphog/packages/pr-approval-agent/README.md b/products/stamphog/packages/pr-approval-agent/README.md
index c971358bf26e..86dd8935a5fb 100644
--- a/products/stamphog/packages/pr-approval-agent/README.md
+++ b/products/stamphog/packages/pr-approval-agent/README.md
@@ -182,16 +182,17 @@ The machine policy, loaded and validated by a strict loader: a malformed or inco
Top-level sections:
-| Section | What it declares |
-| ------------- | -------------------------------------------------------------------- |
-| `version` | The policy schema version |
-| `deny` | The T2 categories and the title/path patterns that match them |
-| `allow` | The path patterns and extensions that make a PR eligible for T0 |
-| `size_gate` | The global `max_lines` and `max_files` ceilings |
-| `tiers` | The T1 sub-class thresholds |
-| `overrides` | The keys a folder file may override, and each key's ceiling |
-| `familiarity` | The author-familiarity bands, a judgment input and never a gate |
-| `ownership` | The ownership sources that feed the reviewer's advisory team context |
+| Section | What it declares |
+| ----------------- | ------------------------------------------------------------------------- |
+| `version` | The policy schema version |
+| `deny` | The T2 categories and the title/path patterns that match them |
+| `deny_exceptions` | Optional per-pattern or category path exceptions without replacing `deny` |
+| `allow` | The path patterns and extensions that make a PR eligible for T0 |
+| `size_gate` | The global `max_lines` and `max_files` ceilings |
+| `tiers` | The T1 sub-class thresholds |
+| `overrides` | The keys a folder file may override, and each key's ceiling |
+| `familiarity` | The author-familiarity bands, a judgment input and never a gate |
+| `ownership` | The ownership sources that feed the reviewer's advisory team context |
A rule may carry a `rationale`.
It records why the rule became what it is, which false positives drove an exclusion and when.
@@ -205,6 +206,26 @@ That is one more reason every edit to a policy file is a human-reviewed change.
The loader rejects unknown top-level keys.
The two exceptions are `digest` and `dismiss`, which a hosting server may declare and parse itself; the engine allows them and never reads them.
+`deny_exceptions` maps existing category names to non-empty lists of rules.
+Each rule requires `path_prefixes`, a non-empty list of literal repository-relative directory prefixes ending in `/`.
+Absolute paths, traversal, wildcards, regular expressions, and noncanonical prefixes fail validation.
+Optional `extensions` restricts the rule to a non-empty list of literal dot-prefixed file suffixes.
+Optional `keyword` restricts the exception to an existing literal pattern in `match.any` or `match.paths`; title-only patterns and arbitrary regular expressions are not accepted.
+Without `keyword`, the rule exempts every path pattern in that category within the selected paths.
+Rules combine their selectors with AND, and the rules within a category combine with OR.
+Prefix and extension comparisons ignore case.
+An absent or empty `deny_exceptions` mapping leaves matching unchanged.
+
+The matcher skips only matching patterns on matching files.
+Other keywords in the same category, other categories, and non-exempt files in a mixed PR still deny.
+Rename checks keep both real paths, so an exempt destination does not waive a protected source.
+Title scrutiny remains unchanged.
+When these exceptions lift a denial, classification requires `T1-agent` rather than the allow-list or test-only `T0` route.
+All remaining gates and the reviewer still apply.
+The loader rejects unknown rule fields and categories, malformed selectors, and every exception to `stamphog_policy`.
+The hosted default-branch overlay accepts a file containing only this section and keeps the inherited `deny` rules, including future additions.
+See the [repository configuration example](../../README.md#deny-exceptions).
+
### `review-guidance.md`
The trusted review-norms prose, injected into the reviewer's system prompt.
diff --git a/products/stamphog/packages/pr-approval-agent/gates.py b/products/stamphog/packages/pr-approval-agent/gates.py
index a1222ea46924..cc7b706d8f99 100644
--- a/products/stamphog/packages/pr-approval-agent/gates.py
+++ b/products/stamphog/packages/pr-approval-agent/gates.py
@@ -17,7 +17,7 @@ from fnmatch import fnmatch
from pathlib import Path
from typing import TYPE_CHECKING, Protocol
-from policy import OwnershipSource, load_policy
+from policy import DenyException, OwnershipSource, load_policy
if TYPE_CHECKING:
from owners_yaml.resolver import OwnersResolver
@@ -393,6 +393,27 @@ def _compile_patterns(
DENY_PATTERNS = _compile_patterns(_DENY_PATTERN_DEFS)
+
+def _compile_deny_exceptions(
+ defs: dict[str, dict[str, list[str]]],
+ exceptions: dict[str, tuple[DenyException, ...]],
+) -> dict[str, dict[re.Pattern[str], tuple[DenyException, ...]]]:
+ compiled: dict[str, dict[re.Pattern[str], tuple[DenyException, ...]]] = {}
+ for category, rules in exceptions.items():
+ scopes = defs[category]
+ pattern_rules: dict[re.Pattern[str], tuple[DenyException, ...]] = {}
+ for pattern in scopes.get("paths", []) + scopes.get("any", []):
+ matching_rules = tuple(
+ rule for rule in rules if rule.keyword is None or rule.keyword.lower() == pattern.lower()
+ )
+ if matching_rules:
+ pattern_rules[_compile_pattern(pattern, for_paths=True)] = matching_rules
+ compiled[category] = pattern_rules
+ return compiled
+
+
+DENY_EXCEPTIONS = _compile_deny_exceptions(_DENY_PATTERN_DEFS, POLICY.deny_exceptions)
+
ALLOW_ONLY_EXTENSIONS = set(POLICY.allow_extensions)
ALLOW_PATH_PATTERNS = list(POLICY.allow_path_patterns)
@@ -513,7 +534,9 @@ def category_fully_exempt(category: str, files: list[str]) -> bool:
return bool(files) and all(_is_exempt_path(category, f) for f in files)
-def detect_deny_categories(files: list[str], ignored_files: set[str] | None = None) -> list[str]:
+def detect_deny_categories(
+ files: list[str], ignored_files: set[str] | None = None, *, apply_exceptions: bool = True
+) -> list[str]:
"""Categories hard-denied by the changed file paths. Titles never deny."""
hits: set[str] = set()
ignored_files_lower = {f.lower() for f in ignored_files or set()}
@@ -522,7 +545,16 @@ def detect_deny_categories(files: list[str], ignored_files: set[str] | None = No
for category, scopes in DENY_PATTERNS.items():
category_paths = [p for p in paths_lower if not _is_exempt_path(category, p)]
path_regexes = scopes.get("paths", []) + [path_rx for path_rx, _title_rx in scopes.get("any", [])]
- if any(rx.search(p) for rx in path_regexes for p in category_paths):
+ exceptions = DENY_EXCEPTIONS.get(category, {}) if apply_exceptions else {}
+ if any(
+ rx.search(p)
+ and not any(
+ p.startswith(rule.path_prefixes) and (not rule.extensions or p.endswith(rule.extensions))
+ for rule in exceptions.get(rx, ())
+ )
+ for rx in path_regexes
+ for p in category_paths
+ ):
hits.add(category)
return sorted(hits)
diff --git a/products/stamphog/packages/pr-approval-agent/github.py b/products/stamphog/packages/pr-approval-agent/github.py
index d1af9b16f59e..002d75e19cdb 100644
--- a/products/stamphog/packages/pr-approval-agent/github.py
+++ b/products/stamphog/packages/pr-approval-agent/github.py
@@ -530,25 +530,36 @@ def _git_diff_files(base_sha: str, head_sha: str, repo_root: Path, merge_base_sh
revisions = diff_range(base_sha, head_sha, merge_base_sha)
run_opts = {"capture_output": True, "text": True, "timeout": 30, "cwd": repo_root}
- numstat = subprocess.run(["git", "diff", "--numstat", revisions], **run_opts)
+ numstat = subprocess.run(["git", "diff", "--numstat", "-z", revisions], **run_opts)
if numstat.returncode != 0:
raise RuntimeError(f"git diff --numstat failed: {numstat.stderr.strip()}")
- name_status = subprocess.run(["git", "diff", "--name-status", revisions], **run_opts)
+ name_status = subprocess.run(["git", "diff", "--name-status", "-z", revisions], **run_opts)
+ if name_status.returncode != 0:
+ raise RuntimeError(f"git diff --name-status failed: {name_status.stderr.strip()}")
status_map: dict[str, str] = {}
- for line in name_status.stdout.strip().splitlines():
- parts = line.split("\t", 1)
- if len(parts) == 2:
- status_map[parts[1]] = parts[0]
+ status_records = iter(name_status.stdout.split("\0"))
+ for status in status_records:
+ if not status:
+ continue
+ filename = next(status_records)
+ if status.startswith(("R", "C")):
+ filename = next(status_records)
+ status_map[filename] = status
files = []
- for line in numstat.stdout.strip().splitlines():
- if not line:
+ numstat_records = iter(numstat.stdout.split("\0"))
+ for record in numstat_records:
+ if not record:
continue
- parts = line.split("\t", 2)
+ parts = record.split("\t", 2)
if len(parts) != 3:
continue
added, deleted, filename = parts
+ if not filename:
+ # git_touched_paths keeps the old path for deny checks; file stats name only the destination.
+ next(numstat_records)
+ filename = next(numstat_records)
is_binary = added == "-"
files.append(
{
diff --git a/products/stamphog/packages/pr-approval-agent/policy.py b/products/stamphog/packages/pr-approval-agent/policy.py
index 4f125f4e7a34..e5b343b4bc52 100644
--- a/products/stamphog/packages/pr-approval-agent/policy.py
+++ b/products/stamphog/packages/pr-approval-agent/policy.py
@@ -25,7 +25,7 @@ Security posture (see .stamphog/README.md):
import re
import functools
from collections.abc import Iterable, Mapping
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath
from typing import Any
@@ -101,6 +101,13 @@ class DenyCategory:
exempt_author_teams: tuple[str, ...] = ()
+@dataclass(frozen=True, kw_only=True)
+class DenyException:
+ keyword: str | None
+ path_prefixes: tuple[str, ...]
+ extensions: tuple[str, ...]
+
+
@dataclass(frozen=True)
class SizeGate:
max_lines: int
@@ -173,6 +180,7 @@ class Policy:
overrides: dict[str, OverrideContract]
familiarity: FamiliarityPolicy
ownership: tuple[OwnershipSource, ...]
+ deny_exceptions: dict[str, tuple[DenyException, ...]] = field(default_factory=dict)
def deny_pattern_defs(self) -> dict[str, dict[str, list[str]]]:
"""Reconstruct the raw scope→patterns mapping the compiler consumes."""
@@ -261,6 +269,7 @@ _TOP_LEVEL_KEYS = {"version", "deny", "allow", "size_gate", "tiers", "overrides"
# a push may retain a standing approval (logic/approval_retention.py). A repo that could widen those
# rules could keep an approval standing across arbitrary code pushes.
_SERVER_ONLY_TOP_LEVEL_KEYS = {"digest", "dismiss"}
+_OPTIONAL_TOP_LEVEL_KEYS = {"deny_exceptions"}
_DENY_SCOPES = {"any", "titles", "paths"}
_BREADTH_RULES = {"single-area", "not-cross-cutting"}
@@ -289,6 +298,9 @@ def _compile_or_raise(pattern: str, context: str) -> None:
_TEAM_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
+_DENY_EXCEPTION_KEYS = {"keyword", "path_prefixes", "extensions"}
+_LITERAL_KEYWORD_RE = re.compile(r"[A-Za-z0-9_-]+")
+_DENY_EXCEPTION_METACHARS_RE = re.compile(r"[\\*?\[\]{}()+|^$\x00-\x1f\x7f-\x9f]")
def _parse_exempt_author_teams(category: str, raw: Any) -> tuple[str, ...]:
@@ -353,6 +365,90 @@ def _parse_deny(raw: Any, lockfile_names: Iterable[str]) -> dict[str, DenyCatego
return deny
+def _parse_deny_exception_prefixes(raw: object, context: str) -> tuple[str, ...]:
+ if not isinstance(raw, list) or not raw:
+ raise PolicyError(f"{context}: must be a non-empty list")
+ prefixes: list[str] = []
+ for prefix in raw:
+ if not isinstance(prefix, str):
+ raise PolicyError(f"{context}: prefixes must be strings")
+ _require(
+ prefix.endswith("/")
+ and all(segment not in {"", ".", ".."} for segment in prefix[:-1].split("/"))
+ and not any(character.isspace() for character in prefix)
+ and not _DENY_EXCEPTION_METACHARS_RE.search(prefix),
+ f"{context}: {prefix!r} must be a literal relative POSIX directory prefix with a trailing slash",
+ )
+ prefixes.append(prefix.lower())
+ return tuple(prefixes)
+
+
+def _parse_deny_exception_extensions(raw: object, context: str) -> tuple[str, ...]:
+ if not isinstance(raw, list) or not raw:
+ raise PolicyError(f"{context}: must be a non-empty list")
+ extensions: list[str] = []
+ for extension in raw:
+ if not isinstance(extension, str):
+ raise PolicyError(f"{context}: extensions must be strings")
+ _require(
+ extension.startswith(".")
+ and all(extension[1:].split("."))
+ and "/" not in extension
+ and not any(character.isspace() for character in extension)
+ and not _DENY_EXCEPTION_METACHARS_RE.search(extension),
+ f"{context}: {extension!r} must be a literal dot-prefixed suffix",
+ )
+ extensions.append(extension.lower())
+ return tuple(extensions)
+
+
+def _parse_deny_exceptions(raw: object, deny: dict[str, DenyCategory]) -> dict[str, tuple[DenyException, ...]]:
+ if not isinstance(raw, dict):
+ raise PolicyError("deny_exceptions: must be a mapping")
+ exceptions: dict[str, tuple[DenyException, ...]] = {}
+ for category, rules in raw.items():
+ context = f"deny_exceptions.{category}"
+ if not isinstance(category, str) or category not in deny:
+ raise PolicyError(f"{context}: unknown deny category")
+ _require(category != "stamphog_policy", f"{context}: the self-governance category exempts nobody")
+ if not isinstance(rules, list) or not rules:
+ raise PolicyError(f"{context}: must be a non-empty list")
+ parsed: list[DenyException] = []
+ for index, rule in enumerate(rules):
+ rule_context = f"{context}[{index}]"
+ if not isinstance(rule, dict):
+ raise PolicyError(f"{rule_context}: must be a mapping")
+ unknown = set(rule) - _DENY_EXCEPTION_KEYS
+ _require(not unknown, f"{rule_context}: unknown keys {sorted(unknown, key=str)}")
+ prefixes = _parse_deny_exception_prefixes(rule.get("path_prefixes"), f"{rule_context}.path_prefixes")
+ extensions = (
+ _parse_deny_exception_extensions(rule["extensions"], f"{rule_context}.extensions")
+ if "extensions" in rule
+ else ()
+ )
+ keyword = None
+ if "keyword" in rule:
+ requested = rule["keyword"]
+ if not isinstance(requested, str) or not _LITERAL_KEYWORD_RE.fullmatch(requested):
+ raise PolicyError(f"{rule_context}.keyword: must be a non-empty literal ASCII token")
+ keyword = next(
+ (
+ pattern
+ for scope in ("any", "paths")
+ for pattern in deny[category].match.get(scope, ())
+ if _LITERAL_KEYWORD_RE.fullmatch(pattern) and pattern.lower() == requested.lower()
+ ),
+ None,
+ )
+ _require(
+ keyword is not None,
+ f"{rule_context}.keyword: {requested!r} is not a path-capable literal pattern in this deny category",
+ )
+ parsed.append(DenyException(keyword=keyword, path_prefixes=prefixes, extensions=extensions))
+ exceptions[category] = tuple(parsed)
+ return exceptions
+
+
def _assert_self_governance(deny: dict[str, DenyCategory]) -> None:
_require("stamphog_policy" in deny, "deny: missing required 'stamphog_policy' self-governance category")
paths = " ".join(deny["stamphog_policy"].match.get("paths", ()))
@@ -545,7 +641,7 @@ def load_policy(
raise PolicyError(f"could not read/parse {path}: {exc}") from exc
_require(isinstance(raw, dict), "policy root: must be a mapping")
- unknown = set(raw) - _TOP_LEVEL_KEYS - _SERVER_ONLY_TOP_LEVEL_KEYS
+ unknown = set(raw) - _TOP_LEVEL_KEYS - _OPTIONAL_TOP_LEVEL_KEYS - _SERVER_ONLY_TOP_LEVEL_KEYS
_require(not unknown, f"policy root: unknown top-level keys {sorted(unknown)}")
for required in _TOP_LEVEL_KEYS:
_require(required in raw, f"policy root: missing required section {required!r}")
@@ -555,9 +651,10 @@ def load_policy(
size_gate = _parse_size_gate(raw["size_gate"])
overrides = _parse_overrides(raw["overrides"])
_require_ceilings_cover_globals(size_gate, overrides)
+ deny = _parse_deny(raw["deny"], lockfile_names)
return Policy(
version=1,
- deny=_parse_deny(raw["deny"], lockfile_names),
+ deny=deny,
allow_path_patterns=path_patterns,
allow_extensions=extensions,
size_gate=size_gate,
@@ -565,6 +662,7 @@ def load_policy(
overrides=overrides,
familiarity=_parse_familiarity(raw["familiarity"]),
ownership=_parse_ownership(raw["ownership"], ownership_formats),
+ deny_exceptions=_parse_deny_exceptions(raw.get("deny_exceptions", {}), deny),
)
diff --git a/products/stamphog/packages/pr-approval-agent/review_pr.py b/products/stamphog/packages/pr-approval-agent/review_pr.py
index bf841a231043..9972152db250 100644
--- a/products/stamphog/packages/pr-approval-agent/review_pr.py
+++ b/products/stamphog/packages/pr-approval-agent/review_pr.py
@@ -439,6 +439,9 @@ class Pipeline:
cc = parse_conventional_commit(pr.title)
safe_migrations = safe_migration_files(pr.check_runs, file_paths)
deny = detect_deny_categories(pr.deny_paths, ignored_files=safe_migrations)
+ exception_lifted = bool(POLICY.deny_exceptions) and (
+ detect_deny_categories(pr.deny_paths, ignored_files=safe_migrations, apply_exceptions=False) != deny
+ )
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
@@ -475,8 +478,9 @@ class Pipeline:
and not has_dependency_changes(file_paths)
and not dep_manifests
and not owner_exempted
+ and not exception_lifted
)
- is_test = test_only(categories) and not owner_exempted
+ is_test = test_only(categories) and not owner_exempted and not exception_lifted
ownership_resolvers = build_ownership(REPO_ROOT, POLICY.ownership)
ownership = detect_ownership(file_paths, ownership_resolvers)
diff --git a/products/stamphog/packages/pr-approval-agent/test_gates.py b/products/stamphog/packages/pr-approval-agent/test_gates.py
index 3e2e850535ac..f53b08a101c6 100644
--- a/products/stamphog/packages/pr-approval-agent/test_gates.py
+++ b/products/stamphog/packages/pr-approval-agent/test_gates.py
@@ -4,6 +4,7 @@ from pathlib import Path
import pytest
+import yaml
import gates
from gates import (
DEPENDENCY_ECOSYSTEMS,
@@ -16,7 +17,7 @@ from gates import (
is_size_exempt,
substantive_size,
)
-from policy import OwnershipSource
+from policy import OwnershipSource, load_policy, repo_root
# ── False positives that should NOT trigger ──────────────────────
@@ -333,6 +334,83 @@ def test_title_scrutiny_flags(subject: str, expected_flags: list[str]) -> None:
assert detect_title_scrutiny_flags(subject) == expected_flags
+def deny_exceptions(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ raw = yaml.safe_load((repo_root() / ".stamphog" / "policy.yml").read_text())
+ raw["deny"]["billing"]["match"]["any"][0] = "Billing"
+ raw["deny_exceptions"] = {
+ "billing": [
+ {
+ "keyword": "BILLING",
+ "path_prefixes": ["APPS/", "argocd/", "shared/", "state/", "charts/"],
+ "extensions": [".YAML", ".yml"],
+ },
+ {"keyword": "billing", "path_prefixes": ["apps/billing.v2/"], "extensions": [".tar.gz"]},
+ ],
+ "infra_cicd": [{"path_prefixes": [".github/"]}],
+ "auth": [{"keyword": "permission", "path_prefixes": ["apps/billing.v2/"], "extensions": [".yaml"]}],
+ }
+ policy_path = tmp_path / "policy.yml"
+ policy_path.write_text(yaml.safe_dump(raw))
+ policy = load_policy(
+ policy_path, lockfile_names=gates._ALL_LOCKFILE_NAMES, ownership_formats=gates.OWNERSHIP_FORMAT_LOCATORS
+ )
+ monkeypatch.setattr(gates, "DENY_PATTERNS", gates._compile_patterns(policy.deny_pattern_defs()))
+ monkeypatch.setattr(
+ gates, "DENY_EXCEPTIONS", gates._compile_deny_exceptions(policy.deny_pattern_defs(), policy.deny_exceptions)
+ )
+
+
+ "files, expected",
+ [
+ pytest.param(["apps/billing/values.yaml"], [], id="billing-yaml"),
+ pytest.param(["ARGocd/BILLING/VALUES.YML"], [], id="case-insensitive"),
+ pytest.param(["shared/billing.yaml", "state/billing.yml", "charts/billing/values.yaml"], [], id="all-prefixes"),
+ pytest.param(["apps/payment-billing/values.yaml"], ["billing"], id="payment-in-same-path"),
+ pytest.param(["apps/stripe-billing/values.yaml"], ["billing"], id="stripe-in-same-path"),
+ pytest.param(["apps/invoice-billing/values.yaml"], ["billing"], id="invoice-in-same-path"),
+ pytest.param(["apps/pricing-billing/values.yaml"], ["billing"], id="pricing-in-same-path"),
+ pytest.param(["apps/billing/values.json"], ["billing"], id="wrong-extension"),
+ pytest.param(["apps/billing/values.yaml.py"], ["billing"], id="lookalike-extension"),
+ pytest.param(["apps-other/billing/values.yaml"], ["billing"], id="lookalike-prefix"),
+ pytest.param(["src/apps/billing/values.yaml"], ["billing"], id="nested-prefix"),
+ pytest.param(["apps/billing.v2/values.tar.gz"], [], id="compound-suffix-and-literal-dot-prefix"),
+ pytest.param(["apps/billing-v2/values.tar.gz"], ["billing"], id="dot-prefix-is-literal"),
+ pytest.param(["apps/billing.v2/values.tar.gz.py"], ["billing"], id="compound-suffix-is-terminal"),
+ pytest.param(["apps/billing.v2/permission.yaml"], [], id="path-only-keyword-exception"),
+ pytest.param(["apps/billing.v2/permission-auth.yaml"], ["auth"], id="path-only-keeps-other-auth-pattern"),
+ pytest.param(["apps/billing/permission.yaml"], ["auth"], id="path-only-keeps-other-scopes"),
+ pytest.param(["apps/billing/values.yaml", "src/billing.py"], ["billing"], id="non-exempt-file"),
+ pytest.param(["apps/billing/auth.yaml"], ["auth"], id="auth-stays-protected"),
+ pytest.param(["apps/billing/secret.yaml"], ["crypto_secrets"], id="secrets-stay-protected"),
+ pytest.param(["apps/billing/openapi.yaml"], ["public_api"], id="api-stays-protected"),
+ pytest.param(["apps/billing/migrations/change.yaml"], ["migrations"], id="migrations-stay-protected"),
+ pytest.param(["apps/billing/owners.yaml"], ["stamphog_policy"], id="policy-stays-protected"),
+ pytest.param([".github/helm/check.py"], [], id="category-exception-without-extension"),
+ pytest.param([".github/pr-deploy"], [], id="category-path-pattern"),
+ pytest.param([".github-other/helm/check.py"], ["infra_cicd"], id="category-prefix-lookalike"),
+ pytest.param([".github/helm/check.py", "terraform/main.tf"], ["infra_cicd"], id="category-mixed-files"),
+ pytest.param([".github/workflows/codeql.yml"], ["ci_workflows"], id="other-category-same-file"),
+ ],
+)
+def test_deny_exceptions_are_per_pattern_and_per_file(deny_exceptions, files: list[str], expected: list[str]) -> None:
+ assert detect_deny_categories(files) == expected
+
+
+def test_disabling_deny_exceptions_preserves_legacy_exemptions_and_ignored_files(deny_exceptions) -> None:
+ files = [
+ "apps/billing/values.yaml",
+ "products/warehouse_sources/backend/temporal/data_imports/sources/stripe/auth.py",
+ "posthog/migrations/0999_add_column.py",
+ ]
+ ignored = {"posthog/migrations/0999_add_column.py"}
+
+ assert detect_deny_categories(files, ignored_files=ignored) == []
+ assert detect_deny_categories(files, ignored_files=ignored, apply_exceptions=False) == ["billing"]
+ assert detect_title_scrutiny_flags("fix: billing helm auth") == ["auth", "billing", "infra_cicd"]
+
+
# ── Deny-list bypass via ignored_files ───────────────────────────
diff --git a/products/stamphog/packages/pr-approval-agent/test_github.py b/products/stamphog/packages/pr-approval-agent/test_github.py
index 60896399981f..59a5ebad9ad7 100644
--- a/products/stamphog/packages/pr-approval-agent/test_github.py
+++ b/products/stamphog/packages/pr-approval-agent/test_github.py
@@ -6,6 +6,7 @@ from pathlib import Path
import pytest
+import gates
import github
from github import (
CommitProvenance,
@@ -20,6 +21,7 @@ from github import (
parse_provenance_trailers,
write_pr_diff,
)
+from policy import DenyException
def test_normalize_reviews_marks_current_head_and_preserves_stale_reviews() -> None:
@@ -142,23 +144,44 @@ def _git(cwd: Path, *args: str) -> str:
return result.stdout.strip()
-def test_touched_paths_carry_both_rename_names_unquoted(tmp_path: Path) -> None:
+ "old_path, new_path, denied",
+ [
+ ("models/flow.py", "flow.py", []),
+ ("apps/billing/old.yaml", "apps/billing/new.yaml", []),
+ ("apps/billing/old\tname.yaml", "apps/billing/new\nname.yaml", []),
+ ("apps/billing/service.py", "apps/plain/values.yaml", ["billing"]),
+ ],
+)
+def test_touched_paths_carry_both_rename_names_unquoted(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, old_path: str, new_path: str, denied: list[str]
+) -> 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")
+ (repo / old_path).parent.mkdir(parents=True)
+ (repo / old_path).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 / new_path).parent.mkdir(parents=True, exist_ok=True)
+ _git(repo, "mv", old_path, new_path)
(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"]
+ touched = git_touched_paths(base, head, repo)
+ assert sorted(touched) == sorted([old_path, new_path, "odd\nname.py"])
+ files = _git_diff_files(base, head, repo)
+ assert {f["filename"]: f for f in files} == {
+ new_path: {"filename": new_path, "additions": 0, "deletions": 0, "binary": False, "status": "R100"},
+ "odd\nname.py": {"filename": "odd\nname.py", "additions": 1, "deletions": 0, "binary": False, "status": "A"},
+ }
+ exceptions = {"billing": (DenyException(keyword="billing", path_prefixes=("apps/",), extensions=(".yaml",)),)}
+ monkeypatch.setattr(gates, "DENY_EXCEPTIONS", gates._compile_deny_exceptions(gates._DENY_PATTERN_DEFS, exceptions))
+ assert gates.detect_deny_categories([*(f["filename"] for f in files), *touched]) == denied
def test_shallow_checkout_diffs_from_the_given_merge_base(tmp_path: Path) -> None:
diff --git a/products/stamphog/packages/pr-approval-agent/test_policy.py b/products/stamphog/packages/pr-approval-agent/test_policy.py
index 91ed568aa055..efc5ae9f07e1 100644
--- a/products/stamphog/packages/pr-approval-agent/test_policy.py
+++ b/products/stamphog/packages/pr-approval-agent/test_policy.py
@@ -1,6 +1,7 @@
"""Tests for the declarative policy loader, resolver, and prompt recomposition."""
import sys
+from functools import partial
from pathlib import Path
import pytest
@@ -288,6 +289,10 @@ def _ownership_wrong_locator_for_format(d: dict) -> None:
d["ownership"]["sources"][0] = {"format": "hogli-resolver", "glob": "products/*/product.yaml"}
+def _set_deny_exceptions(d: dict, *, raw: object) -> None:
+ d["deny_exceptions"] = raw
+
+
@pytest.mark.parametrize(
"mutate",
[
@@ -306,6 +311,76 @@ def _ownership_wrong_locator_for_format(d: dict) -> None:
_ownership_empty_sources,
_ownership_path_escapes_repo,
_ownership_wrong_locator_for_format,
+ *[
+ pytest.param(partial(_set_deny_exceptions, raw=raw), id=f"deny-exceptions-{name}")
+ for name, raw in [
+ ("null", None),
+ ("not-mapping", []),
+ ("unknown-category", {"billling": [{"path_prefixes": ["apps/"]}]}),
+ ("self-governance", {"stamphog_policy": [{"path_prefixes": [".stamphog/"]}]}),
+ ("self-governance-empty", {"stamphog_policy": []}),
+ ("rules-not-list", {"billing": {"path_prefixes": ["apps/"]}}),
+ ("empty-rules", {"billing": []}),
+ ("rule-not-mapping", {"billing": ["apps/"]}),
+ ("missing-prefixes", {"billing": [{"keyword": "billing"}]}),
+ ("unknown-rule-key", {"billing": [{"path_prefixes": ["apps/"], "extension": [".yaml"]}]}),
+ ("mixed-rule-keys", {"billing": [{"path_prefixes": ["apps/"], None: True, "bogus": True}]}),
+ ("invented-keyword", {"billing": [{"path_prefixes": ["apps/"], "keyword": "subscription"}]}),
+ ("title-only-keyword", {"auth": [{"path_prefixes": ["apps/"], "keyword": "authorized"}]}),
+ ("regex-keyword", {"auth": [{"path_prefixes": ["apps/"], "keyword": "two[_-]?factor"}]}),
+ ("null-keyword", {"billing": [{"path_prefixes": ["apps/"], "keyword": None}]}),
+ ("non-string-keyword", {"billing": [{"path_prefixes": ["apps/"], "keyword": 1}]}),
+ ("empty-keyword", {"billing": [{"path_prefixes": ["apps/"], "keyword": ""}]}),
+ ("non-ascii-keyword", {"billing": [{"path_prefixes": ["apps/"], "keyword": "billíng"}]}),
+ ]
+ ],
+ *[
+ pytest.param(
+ partial(_set_deny_exceptions, raw={"billing": [{"path_prefixes": prefixes}]}),
+ id=f"deny-exceptions-prefix-{name}",
+ )
+ for name, prefixes in [
+ ("not-list", "apps/"),
+ ("empty-list", []),
+ ("non-string", [1]),
+ ("empty", [""]),
+ ("absolute", ["/apps/"]),
+ ("missing-slash", ["apps"]),
+ ("dot-segment", ["apps/./"]),
+ ("parent-segment", ["apps/../shared/"]),
+ ("repeated-slash", ["apps//billing/"]),
+ ("backslash", ["apps\\billing/"]),
+ ("wildcard", ["apps/*/"]),
+ ("regex", ["apps/(billing|payment)/"]),
+ ("whitespace", ["apps /"]),
+ ("control", ["apps\x00/"]),
+ ("invalid-second-entry", ["apps/", "../"]),
+ ]
+ ],
+ *[
+ pytest.param(
+ partial(
+ _set_deny_exceptions, raw={"billing": [{"path_prefixes": ["apps/"], "extensions": extensions}]}
+ ),
+ id=f"deny-exceptions-extension-{name}",
+ )
+ for name, extensions in [
+ ("not-list", ".yaml"),
+ ("empty-list", []),
+ ("non-string", [1]),
+ ("empty", [""]),
+ ("missing-dot", ["yaml"]),
+ ("empty-suffix", ["."]),
+ ("empty-compound-segment", [".tar..gz"]),
+ ("slash", [".yaml/"]),
+ ("backslash", [".yaml\\"]),
+ ("wildcard", [".*"]),
+ ("regex", [".(yaml|yml)"]),
+ ("whitespace", [".yaml "]),
+ ("control", [".yaml\x00"]),
+ ("invalid-second-entry", [".yaml", "."]),
+ ]
+ ],
],
)
def test_malformed_policy_hard_fails(tmp_path: Path, mutate) -> None:
@@ -328,6 +403,28 @@ def test_server_owned_digest_section_is_allowed_and_ignored(tmp_path: Path) -> N
assert loaded.version == 1
+ "match, keyword",
+ [
+ ({"titles": ["billing"]}, "billing"),
+ ({"paths": ["payment"]}, "billing"),
+ ({"any": ["billing.*"]}, "billing"),
+ ({"paths": ["[Bb]illing"]}, "billing"),
+ ({"paths": [r"\bbilling\b"]}, "billing"),
+ ],
+)
+def test_deny_exception_keyword_requires_effective_path_literal(
+ tmp_path: Path, match: dict[str, list[str]], keyword: str
+) -> None:
+ data = _valid_policy_dict()
+ data["deny"]["billing"]["match"] = match
+ data["deny_exceptions"] = {"billing": [{"keyword": keyword, "path_prefixes": ["apps/"]}]}
+ path = tmp_path / "policy.yml"
+ path.write_text(yaml.safe_dump(data))
+ with pytest.raises(PolicyError, match="path-capable literal pattern"):
+ load_policy(path, lockfile_names=_LOCKFILE_NAMES, ownership_formats=_OWNERSHIP_FORMATS)
+
+
# ── 3. Folder-override resolution ──
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 786e1b880698..74d7c9ff1188 100644
--- a/products/stamphog/packages/pr-approval-agent/test_review_local.py
+++ b/products/stamphog/packages/pr-approval-agent/test_review_local.py
@@ -2,6 +2,7 @@
import sys
import json
+from dataclasses import replace
from datetime import UTC, datetime
from typing import Any
@@ -14,10 +15,12 @@ from unittest.mock import MagicMock
sys.modules.setdefault("claude_agent_sdk", MagicMock())
sys.modules.setdefault("claude_agent_sdk.types", MagicMock())
+import gates # noqa: E402
import review_pr # noqa: E402
import review_local # noqa: E402
import openai_reviewer # noqa: E402
from github import CommitProvenance # noqa: E402
+from policy import DenyException # noqa: E402
from review_pr import Pipeline # noqa: E402
@@ -763,6 +766,82 @@ def test_pregate_is_final_only_where_the_full_review_agrees(
assert review_local.run(context)["final_verdict"] == expect_verdict
+ "files, safe_migrations, expected_tier, expected_verdict",
+ [
+ pytest.param(["apps/billing/values.yaml"], [], "T1-agent", "REFUSED", id="billing-config-not-t0"),
+ pytest.param(["apps/tests/billing/values.yaml"], [], "T1-agent", "REFUSED", id="billing-test-not-t0"),
+ pytest.param([".github/workflows/codeql.yml"], [], "T1-agent", "REFUSED", id="ci-category-not-t0"),
+ pytest.param([".github/helm/test_chart.py"], [], "T1-agent", "REFUSED", id="ci-test-not-t0"),
+ pytest.param(["docs/change.md"], [], "T0-deterministic", "ESCALATE", id="unaffected-allow-list-stays-t0"),
+ pytest.param(["src/test_app.py"], [], "T0-deterministic", "ESCALATE", id="unaffected-tests-stay-t0"),
+ pytest.param(
+ ["apps/billing/values.yaml", "posthog/migrations/0999_add_col.py"],
+ ["posthog/migrations/0999_add_col.py"],
+ "T1-agent",
+ "REFUSED",
+ id="safe-migration-ignored-in-both-scans",
+ ),
+ ],
+)
+def test_deny_exception_requires_full_review_in_pipeline_and_pregate(
+ monkeypatch, tmp_path, files: list[str], safe_migrations: list[str], expected_tier: str, expected_verdict: str
+) -> None:
+ policy = replace(
+ review_pr.POLICY,
+ deny_exceptions={
+ "billing": (DenyException(keyword="billing", path_prefixes=("apps/",), extensions=(".yaml", ".yml")),),
+ "infra_cicd": (DenyException(keyword=None, path_prefixes=(".github/",), extensions=()),),
+ "ci_workflows": (DenyException(keyword=None, path_prefixes=(".github/",), extensions=()),),
+ },
+ )
+ monkeypatch.setattr(review_pr, "POLICY", policy)
+ monkeypatch.setattr(
+ gates, "DENY_EXCEPTIONS", gates._compile_deny_exceptions(policy.deny_pattern_defs(), policy.deny_exceptions)
+ )
+ monkeypatch.setattr(review_pr, "REPO_ROOT", tmp_path)
+ monkeypatch.setattr(review_local, "REPO_ROOT", tmp_path)
+ monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", False)
+ monkeypatch.setattr(review_local, "_git_diff_files", lambda *a, **k: [])
+ diff_path = tmp_path / "change.diff"
+ diff_path.write_text("+change\n")
+ monkeypatch.setattr(review_pr, "write_pr_diff", lambda *a, **k: diff_path)
+
+ def refuse(self, pr, classification, gate_context, diff_path=None):
+ return {"verdict": "REFUSE", "reasoning": "Needs a safer change.", "risk": "high", "issues": []}
+
+ monkeypatch.setattr(openai_reviewer.OpenAIReviewer, "review", refuse)
+ checks = (
+ [
+ {
+ "name": "Migration risk",
+ "status": "completed",
+ "conclusion": "success",
+ "output": {"summary": f"<!-- stamphog:v1 {json.dumps(safe_migrations)} -->"},
+ }
+ ]
+ if safe_migrations
+ else []
+ )
+ context = _pregate_context(
+ [_api_file(path, status="modified") for path in files],
+ check_runs=checks,
+ folder_policies_known=True,
+ author_team_slugs=[],
+ )
+ context["pr"]["title"] = "fix: billing helm configuration"
+ context["commit_messages"] = []
+ outcome = review_local.pregate(context)
+ result = review_local.run(context)
+
+ assert outcome["final"] is False
+ assert outcome["result"] is None
+ assert result["classification"]["tier"] == expected_tier
+ assert result["classification"]["deny_categories"] == []
+ assert result["classification"]["title_scrutiny_flags"] == ["billing", "infra_cicd"]
+ assert result["final_verdict"] == expected_verdict
+
+
def test_pregate_refusal_reasoning_falls_back_to_the_gate_messages(monkeypatch) -> None:
monkeypatch.setattr(review_local, "_git_diff_files", lambda *a, **k: [])
context = _pregate_context([_api_file("terraform/main.tf")])
diff --git a/products/stamphog/packages/pr-approval-agent/version.py b/products/stamphog/packages/pr-approval-agent/version.py
index 00e9578e1d65..48d3c5a0e433 100644
--- a/products/stamphog/packages/pr-approval-agent/version.py
+++ b/products/stamphog/packages/pr-approval-agent/version.py
@@ -9,4 +9,4 @@ changes don't need a bump - they are tracked by the policy sha shown next to
the version in the verdict table.
"""
-STAMPHOG_VERSION = "2.4.1"
+STAMPHOG_VERSION = "2.5.0"