: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
fix(stamphog): tidy reviewer tool and telemetry edges from 2.4.0 (#113715)
Julian Bez0d9e0cd5ed0d
diff --git a/products/stamphog/packages/pr-approval-agent/gateway.py b/products/stamphog/packages/pr-approval-agent/gateway.pyindex bad01ca28f6d..149e6587ce98 100644--- a/products/stamphog/packages/pr-approval-agent/gateway.py+++ b/products/stamphog/packages/pr-approval-agent/gateway.py@@ -66,7 +66,7 @@ def _misconfig(url: str, api_key: str) -> str | None:def resolve_gateway_config() -> tuple[str, str] | None:- """Validated (anthropic_base_url, phs_api_key), or None to use direct Anthropic.+ """Validated (base_url, phs_api_key), or None to use the direct provider key.Trailing /v1 is stripped; the Agent SDK re-appends /v1/messages."""@@ -76,7 +76,7 @@ def resolve_gateway_config() -> tuple[str, str] | None:return Nonereason = _misconfig(url, api_key)if reason:- print(f"⚠️ ai-gateway misconfigured, falling back to direct Anthropic: {reason}")+ print(f"⚠️ ai-gateway misconfigured, falling back to the direct provider key: {reason}")return None# Rebuild from parsed components (not raw-string slicing) so nothing past the# path can leak into the base; _misconfig already rejected query/fragment.diff --git a/products/stamphog/packages/pr-approval-agent/openai_reviewer.py b/products/stamphog/packages/pr-approval-agent/openai_reviewer.pyindex 1a712fa21271..f7aeb74bf678 100644--- a/products/stamphog/packages/pr-approval-agent/openai_reviewer.py+++ b/products/stamphog/packages/pr-approval-agent/openai_reviewer.py@@ -18,6 +18,8 @@ import tempfileimport threadingimport subprocessfrom dataclasses import asdict, dataclass+from fnmatch import fnmatchcase+from functools import cachefrom pathlib import Pathfrom typing import Any@@ -151,6 +153,27 @@ def git_environment() -> dict[str, str]:return {name: value for name, value in os.environ.items() if name not in _GIT_LOCATION_VARIABLES}+def _glob_matches(parts: list[str], pattern: list[str]) -> bool:+ """Match path segments the way a git :(glob) pathspec does: * stays inside one segment, ** spans any number.++ The glob comes from the model, which PR content can steer, so the match is memoized: its work stays+ bounded by path depth times pattern length, however many ** segments the glob has.+ """++ @cache+ def match(part: int, segment: int) -> bool:+ if segment == len(pattern):+ return part == len(parts)+ if pattern[segment] == "**":+ if segment == len(pattern) - 1:+ # A trailing ** matches what is below the prefix, never the prefix itself.+ return part < len(parts)+ return match(part, segment + 1) or (part < len(parts) and match(part + 1, segment))+ return part < len(parts) and fnmatchcase(parts[part], pattern[segment]) and match(part + 1, segment + 1)++ return match(0, 0)++class ToolError(Exception):"""A tool call the model can correct. Its message goes back to the model as the tool output."""@@ -210,7 +233,11 @@ class RepoTools:def _is_ignored(self, target: Path) -> bool:relative = target.relative_to(self.root).as_posix()command = ["git", "check-ignore", "-q", "--", relative]- result = subprocess.run(command, cwd=self.root, env=git_environment(), capture_output=True, timeout=10)+ try:+ result = subprocess.run(command, cwd=self.root, env=git_environment(), capture_output=True, timeout=10)+ except subprocess.TimeoutExpired:+ # Without an answer the file could be an ignored secret, so the read is refused.+ raise ToolError(f"could not check whether {relative} is ignored by git; try again") from Nonereturn result.returncode == 0def read_file(self, path: str, offset: int | None, limit: int | None) -> str:@@ -240,6 +267,8 @@ class RepoTools:if glob and target.is_dir():prefix = "" if relative == "." else f"{relative}/"pathspec = f":(glob){prefix}{glob}" if "/" in glob else f":(glob){prefix}**/{glob}"+ elif glob and not _glob_matches(relative.split("/"), glob.split("/") if "/" in glob else ["**", glob]):+ return "(no matches)"else:pathspec = relative# git grep reads the checkout's own index, so it is fast on a large repository, and it neverdiff --git a/products/stamphog/packages/pr-approval-agent/review_pr.py b/products/stamphog/packages/pr-approval-agent/review_pr.pyindex 1af670723dab..3e8701ba57a1 100644--- a/products/stamphog/packages/pr-approval-agent/review_pr.py+++ b/products/stamphog/packages/pr-approval-agent/review_pr.py@@ -259,6 +259,8 @@ class Pipeline:self._diff_path: Path | None = Noneself.gate_results: list[GateResult] = []self.reviewer_output: dict | None = None+ # Empty until an LLM reviewer starts, so a gate-only verdict names no engine.+ self.reviewer_engine = ""self.final_verdict: str = ""def run(self) -> str:@@ -937,8 +939,9 @@ class Pipeline:raise AssertionError("review retry loop exhausted without a verdict")def _new_reviewer(self, explore_root: Path | None) -> "Reviewer":+ self.reviewer_engine = reviewer_engine()# Deferred so the gate-only pre-check can import this module where the LLM SDKs are absent.- if reviewer_engine() == CLAUDE_ENGINE:+ if self.reviewer_engine == CLAUDE_ENGINE:from reviewer import Reviewer # noqa: PLC0415 — keeps the heavy dep off the import pathreturn Reviewer(REPO_ROOT, explore_root=explore_root, verbose=self.verbose)@@ -1061,7 +1064,7 @@ class Pipeline:"stamphog_llm_risk": (self.reviewer_output or {}).get("risk", ""),"stamphog_llm_issues": (self.reviewer_output or {}).get("issues", []),"stamphog_llm_facts_summary": facts_summary((self.reviewer_output or {}).get("facts")),- "stamphog_reviewer_engine": reviewer_engine(),+ "stamphog_reviewer_engine": self.reviewer_engine,**_llm_usage_properties(self.reviewer_output),},)diff --git a/products/stamphog/packages/pr-approval-agent/test_openai_reviewer.py b/products/stamphog/packages/pr-approval-agent/test_openai_reviewer.pyindex 6e1cb05fc7d7..14099eec6d3a 100644--- a/products/stamphog/packages/pr-approval-agent/test_openai_reviewer.py+++ b/products/stamphog/packages/pr-approval-agent/test_openai_reviewer.py@@ -27,6 +27,8 @@ def checkout(tmp_path: Path) -> Path:root = tmp_path / "repo"(root / "src").mkdir(parents=True)(root / "src" / "app.py").write_text("def handler():\n return 1\n")+ (root / "src" / "deep").mkdir()+ (root / "src" / "deep" / "inner.py").write_text("nested = True\n")(tmp_path / "secret.txt").write_text(SECRET)(root / "src" / "link.txt").symlink_to(tmp_path / "secret.txt")(root / "src" / "linkdir").symlink_to(tmp_path)@@ -77,6 +79,29 @@ def test_tools_never_reveal_content_outside_the_checkout(checkout: Path, tool: sid="ignored-pipeline-diff",),pytest.param({"pattern": "(unclosed", "path": None, "glob": None}, "error:", id="bad-pattern"),+ pytest.param(+ {"pattern": "handler", "path": "src/app.py", "glob": "*.ts"}, "(no matches)", id="file-outside-glob"+ ),+ pytest.param(+ {"pattern": "handler", "path": "src/app.py", "glob": "src/*.py"},+ "src/app.py:1:def handler():",+ id="file-in-glob",+ ),+ pytest.param(+ {"pattern": "nested", "path": "src/deep/inner.py", "glob": "src/*.py"},+ "(no matches)",+ id="star-stays-in-segment",+ ),+ pytest.param(+ {"pattern": "nested", "path": "src/deep/inner.py", "glob": "**/*.py"},+ "src/deep/inner.py:1:nested = True",+ id="double-star-spans-segments",+ ),+ pytest.param(+ {"pattern": "handler", "path": "src/app.py", "glob": "src/app.py/**"},+ "(no matches)",+ id="trailing-double-star-excludes-the-prefix",+ ),],)def test_grep_finds_untracked_files_and_reports_bad_patterns(checkout: Path, arguments: dict, expected: str) -> None:@@ -85,6 +110,31 @@ def test_grep_finds_untracked_files_and_reports_bad_patterns(checkout: Path, argassert output.startswith(expected)+def test_grep_glob_with_many_double_stars_finishes_on_a_deep_path(checkout: Path) -> None:+ deep = checkout.joinpath(*["d"] * 40)+ deep.mkdir(parents=True)+ (deep / "zz.py").write_text("x = 1\n")+ path = deep.relative_to(checkout).joinpath("zz.py").as_posix()++ output = RepoTools(checkout).call(+ "grep", json.dumps({"pattern": "x", "path": path, "glob": "/".join(["**"] * 8 + ["nomatch"])})+ )++ assert output == "(no matches)"+++def test_read_file_refuses_when_the_ignore_check_times_out(checkout: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ def slow_git(command: list[str], **kwargs: Any) -> None:+ raise subprocess.TimeoutExpired(command, timeout=10)++ monkeypatch.setattr(openai_reviewer.subprocess, "run", slow_git)++ output = RepoTools(checkout).call("read_file", json.dumps({"path": ".env", "offset": None, "limit": None}))++ assert output.startswith("error:")+ assert SECRET not in output++def test_grep_returns_clipped_output_when_a_broad_pattern_matches_too_much(checkout: Path) -> None:(checkout / "src" / "big.txt").write_text("match this line\n" * 20_000)diff --git a/products/stamphog/packages/pr-approval-agent/test_review_pr.py b/products/stamphog/packages/pr-approval-agent/test_review_pr.pyindex 3af7c9ac592d..1dd0d961f809 100644--- a/products/stamphog/packages/pr-approval-agent/test_review_pr.py+++ b/products/stamphog/packages/pr-approval-agent/test_review_pr.py@@ -686,7 +686,7 @@ def test_familiarity_computed_on_every_tier_but_prompted_only_on_t1(],)def test_capture_review_completed_includes_familiarity_and_provenance(- monkeypatch: pytest.MonkeyPatch, populated: bool+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, populated: bool) -> None:# Downstream HogQL queries key on these property names and null/empty# defaults; a rename or a crash on the early-exit paths (bot author, WAIT —@@ -716,6 +716,8 @@ def test_capture_review_completed_includes_familiarity_and_provenance(top_prior_authors=("Alice",),)pipeline.familiarity_source = "server"+ monkeypatch.delenv("STAMPHOG_REVIEWER_ENGINE", raising=False)+ pipeline._new_reviewer(tmp_path)pipeline.provenance = CommitProvenance(commit_count=3,agent_commit_count=2,@@ -739,6 +741,7 @@ def test_capture_review_completed_includes_familiarity_and_provenance(assert props["stamphog_generated_by"] == ["PostHog Desktop"]assert props["stamphog_task_ids"] == ["task-1", "task-2"]assert props["stamphog_review_trigger"] == "manual"+ assert props["stamphog_reviewer_engine"] == "openai"else:assert props["stamphog_owner_teams"] == []assert props["stamphog_familiarity_band"] == ""@@ -748,6 +751,8 @@ def test_capture_review_completed_includes_familiarity_and_provenance(assert props["stamphog_generated_by"] == []assert props["stamphog_task_ids"] == []assert props["stamphog_review_trigger"] == ""+ # A gate-only verdict ran no reviewer, so it must not name one.+ assert props["stamphog_reviewer_engine"] == ""def test_capture_review_completed_merges_server_extras_base_wins(monkeypatch: pytest.MonkeyPatch) -> None: