: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): stop the digest telling a team another team's news (#92246)
Julian Bezc435a6b0fbf2
diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.mdindex 45dba5621499..051c05378b74 100644--- a/products/stamphog/AGENTS.md+++ b/products/stamphog/AGENTS.md@@ -53,8 +53,10 @@ There is deliberately no "this file is harmless" rule, and adding one back needsSuccessive review passes found every candidate wrong in this repository: lockfiles select the dependency code that gets installed, tests run in CI with CI's credentials, a file under a `generated/` directory can be hand-edited and still compiles into a service, `docs/onboarding` is aliased into the production frontend, MDX compiles to JavaScript, snapshot files are JavaScript modules the test runner executes, and even plain Markdown ships, because `services/mcp` imports `.md` templates and product `tools.yaml` files compile `.md` prompts into shipped tool definitions.The digest carries the one narrow exception, and it is not a gate.-`detect_ownership` counts each team's files under `products/<name>/frontend/generated/`, and a team whose changed files are all in there is not a digest audience (`backend/logic/audiences.py`).+`detect_ownership` counts each team's files under `products/<name>/frontend/generated/` and keeps them out of the team's path sample, and `backend/logic/audiences.py` subtracts that count, so a team's `owned_file_count` is the files a person edited.+A team left with none of those is not a digest audience at all.`hogli build:openapi` rewrites those types whenever any shared serializer changes anywhere in the repo, so a team owning nothing else in a PR was not touched by it: that is how an error-tracking change reached the product analytics channel.+Subtracting rather than only dropping the all-generated case came from the same channel getting swept again: one regenerated file next to one real one read as a two-file stake, which is above the graze rule's threshold, so the sweep looked like ownership.Three things keep it from being the harmless-file rule above.It decides who hears about a merge, never whether code is safe to approve.The root `CLAUDE.md` forbids hand-editing those files, so the hand-edited-and-still-ships case does not apply to this path.diff --git a/products/stamphog/README.md b/products/stamphog/README.mdindex a5e66fdcd031..85bf5880e311 100644--- a/products/stamphog/README.md+++ b/products/stamphog/README.md@@ -16,13 +16,13 @@ There is one non-webhook entry: **self-driving inbox PRs**. When a self-drivingOn top of reviews, a repo can enable a daily Slack digest of its merged PRs (`backend/logic/digest_runs.py`, scheduled from `backend/tasks/digest.py`). Only stamphog-approved merges are digested, so the digest needs reviews enabled for the repo.-A merge fans out to every audience it belongs to (`backend/logic/audiences.py`): every team owning a file it changed, read back from the ownership the review already resolved, plus a per-repo audience when a repo declares its own channel under `digest:` in `.stamphog/policy.yml`. A team hears about code it owns, not about everywhere its members touched, so a merge nobody owns in a repo that declares nothing reaches nobody — that is an ownership gap, and `hogli owners:unowned` is where it gets fixed. A `PullRequestAudience` row per audience is what the daily run claims, so one channel failing to post never strands the merge for another. A team whose only changed files were written by a generator is not an audience at all: `hogli build:openapi` rewrites a product's generated API types whenever any shared serializer changes anywhere in the repo, so owning one says nothing about whether that team was touched.+A merge fans out to every audience it belongs to (`backend/logic/audiences.py`): every team owning a file it changed, read back from the ownership the review already resolved, plus a per-repo audience when a repo declares its own channel under `digest:` in `.stamphog/policy.yml`. A team hears about code it owns, not about everywhere its members touched, so a merge nobody owns in a repo that declares nothing reaches nobody — that is an ownership gap, and `hogli owners:unowned` is where it gets fixed. A `PullRequestAudience` row per audience is what the daily run claims, so one channel failing to post never strands the merge for another. Files a generator wrote do not count toward a team's stake in a merge, and a team that owns nothing else is not an audience at all: `hogli build:openapi` rewrites a product's generated API types whenever any shared serializer changes anywhere in the repo, so owning one says nothing about whether that team was touched.Routing is config, and it lives in the repositories rather than in this database (`backend/logic/channel_resolution.py`). Nothing is stored: a run resolves, posts, and records where it went, so changing a declaration moves the next morning's digest. The order is proximity. A `repo:` audience takes the channel that repo declared. A team slug takes the root `owners.yaml` registry of the repo the merge came from, and a repo that carries a registry answers for its own merges completely, including by omission — a registry lists the teams whose derived name is wrong, so a missing slug means the derived name is right. A repo carrying no registry inherits one, which is what lets `charts` route `logs` to `#team-apm` because the monorepo says so. Otherwise the slug name-matches a Slack channel, and the app joins one it was never invited to, so a team's digest starts without anyone wiring it up. Channels shared outside the workspace are skipped, and `notifications: false` on a registry entry is how a team opts out. The registry is asked where _automation_ posts (`notifications`), which falls back to the team's own `slack` channel, so a team that wants bots somewhere quieter says so once and every producer follows.Two repos declaring one team is a scope, not a conflict. Each answers for the merges that came from it, so one audience can resolve to two channels in a run and the digest partitions between them. No merge is posted twice and no declaration is discarded.-Summaries are written where the diff is. The reviewer emits a one-line `change_summary` alongside its verdict, which is stamped onto the merged PR; the daily run condenses those rather than guessing from PR titles, and for an owning team it also sees which of the changed files are theirs, so a repo-wide sweep that grazed two of them can be dropped as noise. A team that owns exactly one file of a large change is flagged to the summarizer outright, because the file counts alone were not enough to stop a config sweep reaching ten channels. The author's own PR body never reaches the prompt, and a PR stamphog never summarized contributes only its title. The reviewed sentence already says what changed, and carrying the body handed one contributor two thousand characters of a prompt whose empty answer consumes the whole batch. What remains is fenced so it cannot close its own tag and continue as instructions.+Summaries are written where the diff is. The reviewer emits a one-line `change_summary` alongside its verdict, which is stamped onto the merged PR; the daily run condenses those rather than guessing from PR titles, and for an owning team it also sees which of the changed files are theirs, so a repo-wide sweep that grazed two of them can be dropped as noise. A team that owns one file of a change of eight or more never reaches the summarizer: that merge is dropped from the team's digest in code (`GRAZE_CHANGED_FILES` in `backend/logic/digest.py`). The prompt asked for that judgment first and the model kept a merge it had been told to drop, which is no surprise — the prompt carries the title, the reviewed sentence and the paths, never the diff, so nothing in it says what the one file does. The team that owns the rest of the merge still hears about it. The author's own PR body never reaches the prompt, and a PR stamphog never summarized contributes only its title. The reviewed sentence already says what changed, and carrying the body handed one contributor two thousand characters of a prompt whose empty answer consumes the whole batch. What remains is fenced so it cannot close its own tag and continue as instructions.The daily run asks the model twice. The first call picks the merges worth posting and writes one line each for the thread. The second writes the channel headline and is shown only what the first call kept, so a headline cannot name a change the thread has no line for. One call did both jobs before, and a prompt rule forbidding that did not hold: the headline reached the channel naming merges the model had chosen to leave out, accurate and unlinkable. A failed second call costs the headline and nothing else, because the first call's lines are already the digest.diff --git a/products/stamphog/backend/logic/audiences.py b/products/stamphog/backend/logic/audiences.pyindex a6c5ee27e5f0..a4609f0bf382 100644--- a/products/stamphog/backend/logic/audiences.py+++ b/products/stamphog/backend/logic/audiences.py@@ -54,7 +54,8 @@ _TEAM_SLUG_RE = re.compile(r"^[A-Za-z0-9._-]+$")@frozenclass _OwnerTeam:- """One team's stake in a PR: its slug, a capped sample of its changed paths, and the true count."""+ """One team's stake in a PR: its slug, a capped sample of its changed paths, and how many+ source files it owns in the PR."""slug: strfiles: list[str]@@ -67,7 +68,7 @@ class ResolvedAudience:reason: AudienceReason# Capped sample of this team's changed paths; empty unless reason is OWNED.owned_files: list[str] = field(default_factory=list)- # How many files this team owns in the PR, uncapped.+ # How many files this team owns in the PR, uncapped, and counting only what a person edited.owned_file_count: int = 0@@ -82,10 +83,13 @@ def _owner_teams(gate_result: dict[str, Any] | None) -> list[_OwnerTeam]:unexpected in the blob resolves to "no owners" rather than raising: a merge must still becaptured when the ownership section is missing or an older engine never wrote it.- A team whose changed files were all written by a build step is dropped here rather than left to- the digest prompt. The prompt carries the same rule in words, and it did not hold to it. The- engine counts those files per team (gates.detect_ownership), so a run recorded before it did- that carries no count and drops nobody.+ The count is the team's source files: the files a build step wrote are subtracted from it, so a+ team that owns one real file plus a regenerated one reads as owning one. Both the graze rule in+ logic/digest.py and the prompt read that count, and a build artifact inflating it hid a sweep+ from both. A team left with no source file is dropped here rather than passed to the digest+ prompt, which carried the same rule in words and did not hold to it. The engine counts the+ generated files per team (gates.detect_ownership), so a run recorded before it did that carries+ no count, subtracts nothing, and drops nobody."""ownership = ((gate_result or {}).get("classification") or {}).get("ownership") or {}teams = ownership.get("teams")@@ -115,12 +119,13 @@ def _owner_teams(gate_result: dict[str, Any] | None) -> list[_OwnerTeam]:# Fall back to the sample size when the count is missing or nonsense; never below it.file_count = max(count, len(sample)) if isinstance(count, int) else len(sample)generated_count = generated_by_team.get(team)- # Compared with >= rather than ==: file_count falls back to the capped sample size when the- # count is missing, and the generated tally is uncapped, so it can legitimately exceed it.- if file_count > 0 and isinstance(generated_count, int) and generated_count >= file_count:+ # Clamped at zero: file_count falls back to the capped sample size when the count is+ # missing, and the generated tally is uncapped, so it can legitimately exceed it.+ source_count = max(file_count - generated_count, 0) if isinstance(generated_count, int) else file_count+ if file_count > 0 and source_count == 0:logger.info("stamphog_owner_team_generated_only", team=team, file_count=file_count)continue- owners[slug] = (sample, file_count)+ owners[slug] = (sample, source_count)return [_OwnerTeam(slug=slug, files=sample, file_count=count) for slug, (sample, count) in sorted(owners.items())]diff --git a/products/stamphog/backend/logic/digest.py b/products/stamphog/backend/logic/digest.pyindex 94f2fb4116df..cabb766139e7 100644--- a/products/stamphog/backend/logic/digest.py+++ b/products/stamphog/backend/logic/digest.py@@ -4,7 +4,11 @@ Boring by design: ask a cheap model to drop the PRs that changed nothing a readegive the few that survive one plain sentence each. Any failure falls back to a deterministic listusing each PR's title as its sentence, so a flaky model never loses a digest.-Two calls, and the order is the point. The first picks the merges worth posting and writes one+One rule runs before either call. A merge that owns a single file of a large change only swept this+team up, so it is dropped here rather than described to the model, which has no diff to judge it by+(see GRAZE_CHANGED_FILES).++Then two calls, and the order is the point. The first picks the merges worth posting and writes onesentence each for the thread. The second writes the channel headline and is shown only what thefirst one kept, so a headline naming a change the thread does not carry is unreachable rather thanforbidden. A single call had to be asked not to do it, and asking did not hold.@@ -66,10 +70,19 @@ MAX_FALLBACK_PRS = 10# so a rule the model invented drops the merge instead of carrying it.KEEP_RULES = frozenset({"contract", "assumption", "decision", "customer"})-# A team that owns exactly one file of a change this size was swept, not targeted. Derived from-# what the audience row already carries, so it needs no capture-time decision. Flagged to the model-# rather than dropped outright: a one-line change in a team's own product can still be the thing-# that team needs to hear about, and only the diff says which it is.+# A team that owns one source file of a change this size was swept, not targeted, and the merge is+# taken out of that team's digest before the model reads it. Derived from what the audience row+# already carries, so it needs no capture-time decision.+#+# This was a line in the prompt first, and the model kept a merge it had been told to drop. The+# instruction asked for a judgment the prompt has no evidence for: the model sees the title, the+# reviewed sentence and the paths, never the diff, so it cannot tell a one-file sweep from a+# one-file change in the team's own area. Without the diff it falls back to what the PR was about,+# which is the other team's announcement.+#+# The cost is accepted. A single-file change that a team really did need to hear about is now+# silence for that team. The team that owns the rest of the merge still gets it, and a digest that+# says nothing costs less than one that repeats another team's news.GRAZE_CHANGED_FILES = 8# Shared by both prompts. Who the digest is for decides what counts as worth saying, so the two@@ -127,8 +140,10 @@ class DigestPRSummary:@frozenclass DigestSummary:- # How many merged PRs the model was shown. The digest prints "3 of 11" from it, which is the- # line that stops a short digest from reading as everything that happened.+ # How many merged PRs the audience claimed. The digest prints "3 of 11" from it, which is the+ # line that stops a short digest from reading as everything that happened. Counted before the+ # graze filter, so a team that was swept by eight merges still reads "0 of 8" rather than "0 of+ # 0", which would say nothing landed in its area at all.considered: int# Prose about the changes that carry real consequence, and the only thing posted in the channel:# the per-PR lines go to its thread. Empty when the model judged nothing worth a channel-level@@ -163,15 +178,18 @@ def _build_summary(return DigestSummary(considered=considered, headline=headline, prs=prs[:limit], judged=judged)-def _fallback_summary(prs: list[PullRequest]) -> DigestSummary:+def _fallback_summary(prs: list[PullRequest], considered: int) -> DigestSummary:"""Deterministic no-LLM summary: no PR is judged, and each one's title becomes its sentence.Keeps the oldest MAX_FALLBACK_PRS merges and drops the rest. Without a model there is nothingto weigh, so which merges survive is merge order and not merit, and the reader gets a plainlist rather than a digest. ``judged`` records that, because the post itself does not show it.++ ``prs`` has already had the grazes taken out of it, so this path drops them too. That rule needs+ no model, and an outage is the worst moment to post a team another team's news."""return _build_summary(- len(prs),+ considered,[DigestPRSummary(pr_number=pr.pr_number,@@ -273,12 +291,8 @@ def _build_selection_prompt(prs: list[PullRequest], audiences: list[PullRequestA"A `your_files` line means this digest goes to the team owning those files, so judge the PR","from their side: keep it when it changes how their area behaves, and drop it when it only","grazed them (a repo-wide rename, a shared type bump, an import fix). Say what changed for",- "them, not what the PR was about overall.",- "",- "A `grazed` line means the team owns exactly one file of a large change. Drop the pull",- "request unless that one file changes how their area behaves. Being caught by a sweep is not",- "news. Treat this as an instruction and not a hint: an unexplained one-file touch is the",- "most common way this digest wastes a team's morning.",+ "them, not what the PR was about overall. A line that would read the same in every team's",+ "digest is a sign you wrote about the pull request instead of about their files.","","HOW TO WRITE THE LINE","- One sentence. 20 words or fewer. Present tense. Active voice. One idea.",@@ -343,8 +357,6 @@ def _build_selection_prompt(prs: list[PullRequest], audiences: list[PullRequestAif owned:sample = _fenced(", ".join(owned))lines.append(f" <your_file_sample index={index}>{sample}</your_file_sample>")- if owned_count == 1 and pr.changed_files >= GRAZE_CHANGED_FILES:- lines.append(f" grazed index={index}")return "\n".join(lines)@@ -548,16 +560,57 @@ def _parse_selection(content: str, prs_by_index: dict[int, PullRequest]) -> listreturn picked+def _grazed(pr: PullRequest, audience: PullRequestAudience | None) -> bool:+ """True when this merge only swept the audience's team up, so the team is not told about it.++ The test is the owned file count, never the path sample, which is capped and can be empty on a+ row an older engine wrote. An audience whose count is zero is therefore never a graze: a+ repo-declared audience asked for every merge in its repository, and a row carrying no count+ says nothing either way. Both keep the merge and leave the judgment to the model.+ """+ return audience is not None and audience.owned_file_count == 1 and pr.changed_files >= GRAZE_CHANGED_FILES+++def _drop_grazes(+ prs: list[PullRequest], audiences: list[PullRequestAudience] | None+) -> tuple[list[PullRequest], list[PullRequestAudience] | None]:+ """The merges this audience is actually told about, with its rows still positionally matched."""+ if not audiences:+ return prs, audiences++ kept_prs = []+ kept_audiences = []+ for pr, audience in zip(prs, audiences):+ if _grazed(pr, audience):+ logger.info(+ "stamphog_digest_graze_dropped",+ pr_number=pr.pr_number,+ audience_key=audience.audience_key,+ changed_files=pr.changed_files,+ )+ continue+ kept_prs.append(pr)+ kept_audiences.append(audience)+ return kept_prs, kept_audiences++def summarize_merged_prs(prs: list[PullRequest], audiences: list[PullRequestAudience] | None = None) -> DigestSummary:"""Summarize merged PRs into a digest, falling back to a plain list on any failure.- ``audiences`` is this channel's audience rows, positionally matching ``prs``. When a row is an- OWNED audience its file sample goes into the prompt, which is what lets the model drop a PR- that merely grazed the team's files while keeping one that changed their area.+ ``audiences`` is this channel's audience rows, positionally matching ``prs``. A merge that only+ grazed the team is dropped here, before any model reads it. What survives goes to the prompt+ with its file sample, which is what lets the model tell a change in the team's area from a+ sweep large enough to reach it through more than one file."""if not prs:return _build_summary(0, [])+ # Everything the audience claimed, which is what the channel's "3 of 11" line counts.+ considered = len(prs)+ prs, audiences = _drop_grazes(prs, audiences)+ if not prs:+ return _build_summary(considered, [])+team_id = prs[0].team_idtry:client = get_llm_client(product="stamphog", team_id=team_id)@@ -567,12 +620,12 @@ def summarize_merged_prs(prs: list[PullRequest], audiences: list[PullRequestAudi)except Exception as e:logger.warning("stamphog_digest_summarize_fallback", team_id=team_id, error=str(e))- return _fallback_summary(prs)+ return _fallback_summary(prs, considered)# Built before the headline is asked for, so the headline call sees the railed list rather than# everything the model kept. A rail that trimmed the thread after the fact would reopen exactly# the gap this split closes, on the entries it cut.- summary = _build_summary(len(prs), picked)+ summary = _build_summary(considered, picked)if not summary.prs:return summaryreturn replace(summary, headline=_request_headline(client, team_id, summary.prs, prs))diff --git a/products/stamphog/backend/models.py b/products/stamphog/backend/models.pyindex 229d0b33b5f7..f6caafae2db7 100644--- a/products/stamphog/backend/models.py+++ b/products/stamphog/backend/models.py@@ -172,8 +172,9 @@ class PullRequestAudience(ProductTeamModel):# it to tell "this changed in your area" from a sweep that grazed two of your files, which it# cannot judge from the PR alone. Empty for an authored audience or an engine without the field.owned_files = models.JSONField(default=list)- # How many of the PR's changed files this team owns. Not len(owned_files) — that list is a- # capped sample, and a team owning most of a large change must not read as grazed by it.+ # How many of the PR's changed files this team owns, counting only what a person edited. Not+ # len(owned_files) — that list is a capped sample, and a team owning most of a large change must+ # not read as grazed by it. A file a build step wrote is not a stake, so it is not counted here.owned_file_count = models.IntegerField(default=0)digest_run = models.ForeignKey("DigestRun", on_delete=models.SET_NULL, null=True, related_name="audiences")created_at = models.DateTimeField(auto_now_add=True)diff --git a/products/stamphog/backend/tests/test_digest.py b/products/stamphog/backend/tests/test_digest.pyindex bec9a5363d0d..acb7613bdbe3 100644--- a/products/stamphog/backend/tests/test_digest.py+++ b/products/stamphog/backend/tests/test_digest.py@@ -28,6 +28,7 @@ from products.stamphog.backend.logic.channel_resolution import (from products.stamphog.backend.logic.digest import (_HEADLINE_MAX_RETRIES,_HEADLINE_TIMEOUT_SECONDS,+ GRAZE_CHANGED_FILES,MAX_DIGEST_PRS,MAX_FALLBACK_PRS,DigestPRSummary,@@ -732,6 +733,47 @@ def test_a_headline_failure_keeps_the_judged_digest() -> None:assert client.options == [{"timeout": _HEADLINE_TIMEOUT_SECONDS, "max_retries": _HEADLINE_MAX_RETRIES}]+ "owned_count,changed_files,dropped",+ [+ (1, GRAZE_CHANGED_FILES, True),+ (1, GRAZE_CHANGED_FILES - 1, False),+ (2, GRAZE_CHANGED_FILES, False),+ ],+)+def test_a_merge_that_only_grazed_the_team_never_reaches_the_model(+ owned_count: int, changed_files: int, dropped: bool+) -> None:+ # A repo-wide config change owned one line in ten products and reached every one of their+ # channels. The prompt named the graze and asked the model to drop it, and the model kept it+ # anyway: the prompt carries no diff, so nothing in it says what that one file does. Code+ # decides now. The grazed merge goes first so a filter that forgot to renumber the index map+ # would resolve the model's index 0 to the wrong PR.+ grazed = _pr_stub("o/r", 1, "Swept in", "https://github.com/o/r/pull/1")+ grazed.changed_files = changed_files+ owned = _pr_stub("o/r", 2, "Ours", "https://github.com/o/r/pull/2")+ audiences = [+ PullRequestAudience(+ audience_key=AUDIENCE,+ reason=AudienceReason.OWNED,+ owned_files=[f"a{i}.py" for i in range(count)],+ owned_file_count=count,+ )+ for count in (owned_count, 1)+ ]+ selection = json.dumps({"prs": [{"index": 0, "rule": "contract", "summary": "The first one."}]})+ client = _recording_llm_client([selection, json.dumps({"headline": "Something shipped."})])++ with patch("products.stamphog.backend.logic.digest.get_llm_client", return_value=client):+ summary = summarize_merged_prs([grazed, owned], audiences)++ assert ("Swept in" in client.prompts[0]) is not dropped+ assert [p.pr_number for p in summary.prs] == [2 if dropped else 1]+ # The scope line still counts every merge the audience claimed. Counting only what survived+ # would tell a swept team that nothing landed in its area at all.+ assert summary.considered == 2++def test_a_model_outage_posts_a_short_plain_list_and_says_it_judged_nothing() -> None:# The fallback keeps merge order and judges nothing, so it needs its own low rail: the bar that# normally keeps a digest short never runs on this path. It also has to mark itself, because adiff --git a/products/stamphog/backend/tests/test_logic.py b/products/stamphog/backend/tests/test_logic.pyindex b3c915ff19a7..7ec34a79b654 100644--- a/products/stamphog/backend/tests/test_logic.py+++ b/products/stamphog/backend/tests/test_logic.py@@ -12,12 +12,7 @@ from parameterized import parameterizedfrom products.stamphog.backend.facade.enums import AudienceReason, ReviewMode, ReviewTriggerfrom products.stamphog.backend.logic.approval_retention import approved_diff_unchangedfrom products.stamphog.backend.logic.audiences import resolve_audiences-from products.stamphog.backend.logic.digest import (- GRAZE_CHANGED_FILES,- DigestPRSummary,- DigestSummary,- _build_selection_prompt,-)+from products.stamphog.backend.logic.digest import DigestPRSummary, DigestSummary, _build_selection_promptfrom products.stamphog.backend.logic.digest_config import RepoDigestConfig, load_repo_digest_configfrom products.stamphog.backend.logic.github_client import (MAX_COMPARE_DIFF_BYTES,@@ -662,13 +657,15 @@ class GeneratedOwnershipTests(SimpleTestCase):@parameterized.expand([("every_file_was_generated", 1, 1, []),- ("a_real_file_alongside_a_generated_one", 2, 1, [("team-replay", AudienceReason.OWNED)]),+ # The regression: one generated file next to one real one read as a two-file stake,+ # which is over the graze threshold, so the sweep passed for ownership.+ ("a_real_file_alongside_a_generated_one", 2, 1, [("team-replay", AudienceReason.OWNED, 1)]),# The count is exact, so this holds however far past the engine's path sample it goes.("more_generated_files_than_the_sample_carries", 40, 40, []),- ("a_run_recorded_before_the_engine_counted_them", 1, None, [("team-replay", AudienceReason.OWNED)]),+ ("a_run_recorded_before_the_engine_counted_them", 1, None, [("team-replay", AudienceReason.OWNED, 1)]),])- def test_a_team_owning_only_generated_files_is_not_an_audience(+ def test_generated_files_are_not_a_teams_stake_in_a_merge(self, _name: str, count: int, generated: int | None, expected: list) -> None:# `hogli build:openapi` rewrites a product's generated API types whenever any shared@@ -685,7 +682,7 @@ class GeneratedOwnershipTests(SimpleTestCase):ownership["team_generated_file_counts"] = {"@PostHog/team-replay": generated}with patch("products.stamphog.backend.logic.audiences.load_repo_digest_config", return_value=None):audiences = resolve_audiences(repo_config, {"classification": {"ownership": ownership}})- assert [(a.key, a.reason) for a in audiences] == expected+ assert [(a.key, a.reason, a.owned_file_count) for a in audiences] == expectedclass OwnedFilePromptTests(SimpleTestCase):@@ -727,40 +724,6 @@ class OwnedFilePromptTests(SimpleTestCase):]assert "your_files index=0 count=5 of 5" in _build_selection_prompt([pr], audiences)- @parameterized.expand(- [- ("one_file_of_a_sweep_is_flagged", 1, GRAZE_CHANGED_FILES, True),- ("one_file_of_a_small_change_is_not", 1, GRAZE_CHANGED_FILES - 1, False),- ("owning_several_files_is_not_a_graze", 2, GRAZE_CHANGED_FILES, False),- ]- )- def test_a_swept_team_is_flagged_to_the_model(- self, _name: str, owned_count: int, changed_files: int, flagged: bool- ) -> None:- # A repo-wide config change owned one line in ten products and reached every one of their- # channels. The count was already in the prompt and the model kept the PR anyway, so the- # graze is named outright rather than left to be inferred from two numbers.- repo_config = StamphogRepoConfig(repository="PostHog/posthog", installation_id="1")- pr = PullRequest(- repo_config=repo_config,- team_id=7,- pr_number=1,- title="Ship it",- pr_url="https://github.com/o/r/pull/1",- author_login="dev",- changed_files=changed_files,- body_excerpt="",- )- audiences = [- PullRequestAudience(- audience_key="team-replay",- reason=AudienceReason.OWNED,- owned_files=[f"a{i}.py" for i in range(owned_count)],- owned_file_count=owned_count,- )- ]- assert ("grazed index=0" in _build_selection_prompt([pr], audiences)) is flagged-def test_contributor_text_cannot_speak_to_the_summarizer(self) -> None:# Two doors into this prompt, both shut. The author's body never reaches it, and the title# cannot write its own closing tag. An empty answer consumes the whole claim, so a titlediff --git a/products/stamphog/packages/pr-approval-agent/gates.py b/products/stamphog/packages/pr-approval-agent/gates.pyindex 25dfd272c9dc..95830d35d6b8 100644--- a/products/stamphog/packages/pr-approval-agent/gates.py+++ b/products/stamphog/packages/pr-approval-agent/gates.py@@ -272,7 +272,8 @@ def detect_ownership(files: list[str], resolvers: list[OwnershipResolver]) -> dibucket: `teams` feeds team-membership checks and the cross-team calculusdownstream, and a raw handle there would fail membership lookups and inflatethe team count. `team_files` samples each team's changed paths so a later- consumer can tell a change in a team's area from one that merely grazed it.+ consumer can tell a change in a team's area from one that merely grazed it,+ and a generated path is left out of that sample because no person edited it.`team_generated_file_counts` says how many of each team's files a build stepwrote, which the capped sample cannot answer."""all_teams: set[str] = set()@@ -297,6 +298,7 @@ def detect_ownership(files: list[str], resolvers: list[OwnershipResolver]) -> diteam_file_counts[t] += 1if generated:team_generated_counts[t] += 1+ continue# Capped: a sweeping rename can own hundreds of a team's files and no consumer# needs them all. The cap binds only on a sweep, where the count alone is the# useful signal anyway.@@ -314,7 +316,8 @@ def detect_ownership(files: list[str], resolvers: list[OwnershipResolver]) -> di"unowned_files": unowned_files,"team_file_counts": dict(team_file_counts.most_common()),"team_generated_file_counts": dict(team_generated_counts.most_common()),- "team_files": {t: team_files[t] for t, _ in team_file_counts.most_common()},+ # Empty for a team whose only files a build step wrote: those are excluded above.+ "team_files": {t: team_files.get(t, []) for t, _ in team_file_counts.most_common()},"cross_team": len(all_teams) > 1,}diff --git a/products/stamphog/packages/pr-approval-agent/test_gates.py b/products/stamphog/packages/pr-approval-agent/test_gates.pyindex 160f52225bd2..0725840e1326 100644--- a/products/stamphog/packages/pr-approval-agent/test_gates.py+++ b/products/stamphog/packages/pr-approval-agent/test_gates.py@@ -577,6 +577,11 @@ def test_ownership_counts_a_products_generated_directory_and_nothing_wider(tmp_passert ownership["team_file_counts"] == {"@PostHog/team-a": 3}assert ownership["team_generated_file_counts"] == {"@PostHog/team-a": 1}+ # The sample is what the digest shows a summarizer as "your files", so a path no person edited+ # does not belong in it. The count above is what the digest subtracts.+ assert ownership["team_files"] == {+ "@PostHog/team-a": ["products/foo/backend/generated/thing.py", "products/foo/backend/models.py"]+ }def test_owners_candidates_are_fixed_offsets_from_this_file() -> None: