: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): route the desktop digest and write lines per owning team (#94929)
Julian Beze8663106557f
diff --git a/.github/workflows/ci-owners-live-lint.yml b/.github/workflows/ci-owners-live-lint.ymlnew file mode 100644index 000000000000..a5f063cb0a3a--- /dev/null+++ b/.github/workflows/ci-owners-live-lint.yml@@ -0,0 +1,96 @@+# Revalidate every ownership identity against the GitHub org, once a week.+#+# The PR-scoped lint (validate-product-yamls in ci-backend.yml) only sees the ownership files a+# PR changed, so it cannot see a slug going stale after the file merged. A GitHub team that is+# renamed or deleted leaves valid-looking files behind, and the slug then routes its merges+# nowhere and drops out of reviewer assignment. This run reads every file again.++name: Ownership live lint++on:+ schedule:+ # Mondays, ahead of the 07:00 UTC stamphog digest, so a dead slug is reported before the+ # week's digests route on it.+ - cron: '17 6 * * 1'+ workflow_dispatch:++env:+ SLACK_CHANNEL: 'C0AS64N6DJL' # #alerts-devex++permissions:+ contents: read++concurrency:+ group: ${{ github.workflow }}-${{ github.event_name == 'schedule' && 'scheduled' || github.ref }}+ cancel-in-progress: false++jobs:+ owners-live-lint:+ name: Validate every ownership identity against GitHub+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ # Plain checkout: the lint reads every owners.yaml and product.yaml in the tree.+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2++ # Default GITHUB_TOKEN can't list /repos/{repo}/teams (needs org-level+ # `members: read`). Reuse the assign-reviewers app — same secret, same+ # use case. `owner: PostHog` scopes the issued token at the org so+ # org-level permissions actually flow through; otherwise the token is+ # repo-scoped and the org scope gets dropped.+ - name: Get app token+ id: app-token+ uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1+ with:+ client-id: ${{ secrets.GH_APP_POSTHOG_ASSIGN_REVIEWERS_APP_ID }}+ private-key: ${{ secrets.GH_APP_POSTHOG_ASSIGN_REVIEWERS_PRIVATE_KEY }}+ owner: ${{ github.repository_owner }}+ # Literal: a cron payload carries no event.repository, and this file lives in one repo.+ repositories: posthog++ - name: Set up Python+ uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0+ with:+ python-version: 3.13.13+ # Reuse the app token already minted above instead of a second mint.+ token: ${{ steps.app-token.outputs.token || github.token }}++ - name: Install uv+ uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7.6.0+ with:+ version: '0.11.28'++ - name: Install Python dependencies+ run: UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev++ - name: Lint every ownership file against the GitHub org+ id: lint+ env:+ GH_TOKEN: ${{ steps.app-token.outputs.token }}+ run: ./bin/hogli owners:lint --live++ # Only the lint step failing means an ownership file names an identity the org no+ # longer has. Infra failures upstream (checkout, token, uv sync) are CI noise. Nobody+ # watches a scheduled run, so alert explicitly when the lint itself fails.+ - name: Notify Slack on lint failure+ if: failure() && steps.lint.outcome == 'failure'+ uses: slackapi/slack-github-action@af78098f536edbc4de71162a307590698245be95 # v3.0.1+ with:+ method: chat.postMessage+ token: ${{ secrets.SLACK_DEVEX_BOT_TOKEN }}+ errors: true+ payload: |+ channel: "${{ env.SLACK_CHANNEL }}"+ text: ":red_circle: Ownership live lint failed"+ blocks:+ - type: "section"+ text:+ type: "mrkdwn"+ text: ":red_circle: *Ownership live lint failed*. An ownership file names a team slug or handle that no longer exists in the GitHub org, so its merges route nowhere and reviewer assignment skips it."+ - type: "actions"+ elements:+ - type: "button"+ text:+ type: "plain_text"+ text: "View run"+ url: "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"diff --git a/docs/internal/ownership-model-proposal.md b/docs/internal/ownership-model-proposal.mdindex d890b7f03d0f..0d0070703d29 100644--- a/docs/internal/ownership-model-proposal.md+++ b/docs/internal/ownership-model-proposal.md@@ -119,16 +119,15 @@ This keeps all 68 products at zero migration cost and preserves `hogli product:l### Slack derivation: measured, not assumed-Checked every team slug in use against live Slack channels, re-verified 2026-07-15 against the 30 slugs left after the migration:+Checked every team slug in use against live Slack channels (first pass 2026-07-15). The counts below follow the root `owners.yaml` registry, over the 30 slugs in use:-- 24/30: `#<slug>` exists verbatim, so no entry is needed.-- 6/30 need an entry in the root `teams:` registry (below):- - `clickhouse`, `conversations`, `batch-exports` — these predate the `team-` convention and are the real org slugs; `team-clickhouse` and friends do not exist as GitHub teams, so the slugs cannot be "fixed" and the channel is `#team-<slug>`.+- 22/30: `#<slug>` exists verbatim, so no entry is needed.+- 8/30 need an entry in the root `teams:` registry (below):+ - `ai-research`, `batch-exports`, `clickhouse`, `conversations`, `mcp-analytics`, `platform-ux` — these predate the `team-` convention and are the real org slugs; `team-clickhouse` and friends do not exist as GitHub teams, so the slugs cannot be "fixed" and the channel is `#team-<slug>`.- `team-data-stack` → `#group-data-stack`.- - `team-posthog-code` → `#team-desktop`, the name the channel was created under.- - `logs` → `#team-apm`: the `logs` and `apm` GitHub teams have identical membership, APM ("Logs, Metrics and Traces") having absorbed logs.+ - `team-posthog-desktop` → `#team-desktop`, the name the channel was created under.-So the derived default is right for 80% of teams and the rest carry one entry each.+So the derived default is right for most teams and the rest carry one entry each.Nothing validates that a derived channel actually exists — a wrong or dead channel fails silently.An opt-in Slack-API check in `owners:lint`, mirroring the existing opt-in live GitHub-team validation, would close that gap; it is not built.diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 985eb78fba4f..17c53b434b7b 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -447,9 +447,9 @@ export const FEATURE_FLAGS = {POSTHOG_AI_CONVERSATION_FEEDBACK_CONFIG: 'posthog-ai-conversation-feedback-config', // owner: #team-posthog-aiPOSTHOG_AI_CONVERSATION_FEEDBACK_LLMA_SESSIONS: 'posthog-ai-conversation-feedback-llma-sessions', // owner: #team-posthog-aiPOSTHOG_AI_QUEUE_MESSAGES_SYSTEM: 'posthog-ai-queue-messages-system', // owner: #team-posthog-ai- POSTHOG_CODE_BILLING: 'posthog-code-billing', // owner: #team-posthog-code+ POSTHOG_CODE_BILLING: 'posthog-code-billing', // owner: #team-desktopPOSTHOG_CONNECT: 'posthog-connect', // owner: @Gilbert09, gates the "connect another PostHog project" personal integration- POSTHOG_DESKTOP_CLOUD_COMPUTE_BILLING: 'posthog-desktop-cloud-compute-billing', // owner: #team-posthog-code+ POSTHOG_DESKTOP_CLOUD_COMPUTE_BILLING: 'posthog-desktop-cloud-compute-billing', // owner: #team-desktopPRODUCT_ANALYTICS_DASHBOARD_COLORS: 'dashboard-colors', // owner: @thmsobrmlr #team-product-analyticsPRODUCT_ANALYTICS_DASHBOARD_MODAL_SMART_DEFAULTS: 'product-analytics-dashboard-modal-smart-defaults', // owner: @sam #team-product-analyticsPRODUCT_ANALYTICS_INSIGHT_HORIZONTAL_CONTROLS: 'insight-horizontal-controls', // owner: #team-product-analyticsdiff --git a/owners.yaml b/owners.yamlindex ef5e0d488db3..17691bc08313 100644--- a/owners.yaml+++ b/owners.yaml@@ -2,7 +2,7 @@ version: 1owners: []# Slack channel per team, declared once for the whole repo (root-only registry).# A team only needs an entry where the derived '#<slug>' is wrong or missing; the-# other 23 slugs in use derive correctly and are deliberately absent.+# other 22 slugs in use derive correctly and are deliberately absent.teams:# GitHub team slugs that predate the 'team-' convention: the slug is right,# the channel just doesn't match it.@@ -24,7 +24,7 @@ teams:team-data-stack:slack: '#group-data-stack'# PostHog Desktop's channel kept the name it was created under.- team-posthog-code:+ team-posthog-desktop:slack: '#team-desktop'# The derived '#team-replay' is right; the entry exists only to drop the daily# stamphog digest, which the team reads on the PRs themselves.diff --git a/products/desktop/docs/UPDATES.md b/products/desktop/docs/UPDATES.mdindex 37e2760d34e9..098d45d0dd6f 100644--- a/products/desktop/docs/UPDATES.md+++ b/products/desktop/docs/UPDATES.md@@ -38,7 +38,7 @@ Remote announcements can drive this flow: a `required-update` announcement blockMerge to `master` and wait for the next scheduled `desktop-tag.yml` run. To release sooner:-- Add the `desktop-release` label to your PR before merging (the labeler must be a `team-posthog-code` member). The merge then tags immediately.+- Add the `desktop-release` label to your PR before merging (the labeler must be a `team-posthog-desktop` member). The merge then tags immediately.- Or trigger `desktop-tag.yml` manually with `gh workflow run desktop-tag.yml`.## Releasing a minor or major versiondiff --git a/products/stamphog/README.md b/products/stamphog/README.mdindex 34f1846bcfa9..94d354e694f5 100644--- a/products/stamphog/README.md+++ b/products/stamphog/README.md@@ -16,21 +16,21 @@ 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. 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.+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 slug that is not a live GitHub team reaches nobody in the same way, because there is no `#<slug>` channel to name-match and no registry entry to redirect it, and `hogli owners:lint --live` is the check that catches one. Renaming an audience in the ownership files does not move the rows already captured under the old key, and a branch opened before the rename keeps producing that key until it rebases, so those rows route nowhere and expire after the seven-day claim window. 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.+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 `team-data-stack` to `#group-data-stack` 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 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.+Summaries are written where the diff is. The reviewer emits a `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. That summary is one sentence about the whole change, and on a merge more than one team owns files in, one clause per owning team after it, each opening with that team's handle. The digest hands its model the sentence and the clause addressed to its own audience, and nothing else, so another team's clause is not there to be picked rather than forbidden. A team that owns part of a merge and got no clause of its own is dropped before the model reads anything, because the reviewer had the diff and found nothing to say about that team's files. 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.+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. The headline is written every time. The rule that let it return nothing on a routine day predates the split, and the changes it now sees have already cleared the bar, so its only remaining effect was on a single-change digest, where the renderer promoted that change's line and the channel said the same sentence as the thread.-How many changes a digest carries is decided by the bar and by nothing else. There is no target count and no editorial cap, so a quiet day shows none and a heavy one shows what it earns. The bar is four named rules — `contract`, `assumption`, `decision`, `customer` — and the summarizer has to name the one that admits each merge it keeps. A merge kept without a valid rule is dropped in code rather than trusted, because an unnamed bar gets rationalized away: on a real day of twenty-six connector fixes the same model kept twenty-one of them without the rules and none to two with them. Repair overrides all four. Making a broken integration work is maintenance, and only changing what a working one does is news. The one limit is Slack's own block ceiling, which the deterministic fallback rails far below because that path judges nothing.+How many changes a digest carries is decided by the bar and by nothing else. There is no target count and no editorial cap, so a quiet day shows none and a heavy one shows what it earns. The bar is four named rules — `contract`, `assumption`, `decision`, `customer` — and the summarizer has to name the one that admits each merge it keeps. A merge kept without a valid rule is dropped in code rather than trusted, because an unnamed bar gets rationalized away: on a real day of twenty-six connector fixes the same model kept twenty-one of them without the rules and none to two with them. The same trick carries the team's own perspective. A team that owns part of a merge was told what the merge was about, which is the other team's news, so the model has to say whether each line it keeps is about the team's own files or about the pull request overall, and a line about the whole pull request is dropped for a team that owns only part of it. A team owning every changed file, and a repo that declared its own channel, are asked for no such claim. Repair overrides all four. Making a broken integration work is maintenance, and only changing what a working one does is news. The one limit is Slack's own block ceiling, which the deterministic fallback rails far below because that path judges nothing.A run consumes every merge it claims, whatever the summarizer decided about it. Handing the leftovers back put the same merges in front of the same prompt every morning, where the same text produced the same answer, so a busy team's batch grew for a week and then aged out unseen. Merges above the per-run claim ceiling are the one exception: they are never claimed, so the next run picks them up.-A digest posts as two messages (`backend/logic/slack_digest.py`). The channel gets one lead, best available first: the model's headline when it judged something worth a channel-level sentence, otherwise the first change's own line, and the scope line ("3 of 11 Stamphog-approved merges") when neither is available. Promoting a change line keeps the channel saying something that shipped instead of a bare count, and it is the line the thread already carries, so a reader who wants the diff is one message away. Only a judged run may promote one: the deterministic fallback's lines are unreviewed PR titles, and the promoted line has to clear the same no-link rule the headline does, because the channel lead is the one piece of digest text posted without a link attached to it. The per-change lines go in a thread under that lead, so a team spends one line of its channel and opens the rest by choice. Neither message promises the reader every merge of the day: the thread leads with whose judgment picked its contents, and the footer marks the digest as beta and asks for a reaction or a reply, which is where feedback on the digest itself lands. A failed thread reply never fails the run — the lead is already posted and the run's PRs are consumed on that basis, so treating it as a failure would post the same lead again the next day.+A digest posts as two messages (`backend/logic/slack_digest.py`). The channel gets one lead, best available first: the model's headline, otherwise the first change's own line when the headline call failed or answered with something unpostable, and the scope line ("3 of 11 Stamphog-approved merges") when neither is available. Promoting a change line keeps the channel saying something that shipped instead of a bare count, and it is the line the thread already carries, so a reader who wants the diff is one message away. Only a judged run may promote one: the deterministic fallback's lines are unreviewed PR titles, and the promoted line has to clear the same no-link rule the headline does, because the channel lead is the one piece of digest text posted without a link attached to it. The per-change lines go in a thread under that lead, so a team spends one line of its channel and opens the rest by choice. Neither message promises the reader every merge of the day: the thread leads with whose judgment picked its contents, and the footer marks the digest as beta and asks for a reaction or a reply, which is where feedback on the digest itself lands. A failed thread reply never fails the run — the lead is already posted and the run's PRs are consumed on that basis, so treating it as a failure would post the same lead again the next day.## Stacked PRsdiff --git a/products/stamphog/backend/logic/audiences.py b/products/stamphog/backend/logic/audiences.pyindex a4609f0bf382..c49274342c11 100644--- a/products/stamphog/backend/logic/audiences.py+++ b/products/stamphog/backend/logic/audiences.py@@ -72,6 +72,16 @@ class ResolvedAudience:owned_file_count: int = 0+def team_slug_from_handle(handle: str) -> str:+ """The bare slug in a GitHub team handle: `@PostHog/team-devex` becomes `team-devex`.++ An audience key is this slug, and the digest matches the reviewer's per-team clauses back to+ one by reading their handles the same way (see logic/digest.py), so the two agree by+ construction rather than by two copies of the rule.+ """+ return handle.partition("/")[2]++def _repository_audience_key(repo_config: StamphogRepoConfig) -> str:return f"{REPO_AUDIENCE_PREFIX}{repo_config.repository}"@@ -108,8 +118,8 @@ def _owner_teams(gate_result: dict[str, Any] | None) -> list[_OwnerTeam]:for team in teams:if not isinstance(team, str) or not team.startswith(_TEAM_HANDLE_PREFIX):continue- # "@PostHog/team-devex" -> "team-devex". A handle without an org is not a team.- _, _, slug = team.partition("/")+ # A handle without an organization is not a team, and the slug regex below rejects it.+ slug = team_slug_from_handle(team)if not _TEAM_SLUG_RE.match(slug):logger.warning("stamphog_owner_team_slug_rejected", team=team)continuediff --git a/products/stamphog/backend/logic/digest.py b/products/stamphog/backend/logic/digest.pyindex 16aa67df0ad4..39c76fee7e24 100644--- a/products/stamphog/backend/logic/digest.py+++ b/products/stamphog/backend/logic/digest.py@@ -4,9 +4,15 @@ 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.-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).+Two rules run before either call, both about a merge this team owns only part of, and both decided+without a model because neither call has a diff to judge by. A merge that reached the team through+a single file of a large change only swept it up (see GRAZE_CHANGED_FILES). A merge whose reviewed+summary names the owning teams and not this one was read by a reviewer that did have the diff and+found nothing to say about this team's files.++What survives is cut to the part written for this team. The reviewed summary of a multi-team change+carries one clause per owning team, and only the clause addressed to this audience reaches either+prompt, so another team's half of the merge is not there to be picked rather than forbidden.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 the@@ -30,6 +36,8 @@ import structlogfrom posthog.dataclasses import frozenfrom posthog.llm.gateway_client import build_anthropic_client, team_distinct_id+from .audiences import REPO_AUDIENCE_PREFIX, team_slug_from_handle+if TYPE_CHECKING:from ..models import PullRequest, PullRequestAudience@@ -74,6 +82,13 @@ MAX_FALLBACK_PRS = 10# so a rule the model invented drops the merge instead of carrying it.KEEP_RULES = frozenset({"contract", "assumption", "decision", "customer"})+# The perspective a kept line was written from, as the model must name it. The same trick as the+# named rules above: a judgment the model states in the answer is one the code can check.+#+# A line about a partly owned merge has to claim it is about the owned files, and a line that+# claims otherwise is dropped for that team.+SCOPE_YOUR_FILES = "your_files"+# 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.@@ -129,6 +144,19 @@ _STYLE_RULES = (# through to another line that says something true, and the links are one message below either way._CHANNEL_LINK_RE = re.compile(r"[a-z][a-z0-9+.\-]*://|\bwww\.|\bmailto:|\S+@\S+\.\S", re.IGNORECASE)+# Where a reviewed summary stops describing the whole change and starts addressing one team. The+# reviewer opens each per-team clause with that team's GitHub handle, copied from the ownership+# block it was given (see packages/pr-approval-agent/reviewer.py). The handle is captured so a+# clause can be matched to the team it was written for.+#+# A clause opens a sentence, so the handle is only matched at the start of the summary or after+# sentence-ending punctuation. A scoped package name inside a sentence (`@posthog/cli:`) is prose.+_TEAM_CLAUSE_RE = re.compile(r"(?:^|(?<=[.!?])\s+)(@[A-Za-z0-9._-]+/[A-Za-z0-9._-]+):")+# Any handle-shaped token at all, wherever it sits. One the anchored pattern did not consume is a+# clause the reviewer opened without ending the sentence before it, or a token the prompt forbids,+# and either way the text around it can no longer be trusted to belong to one team.+_ANY_HANDLE_RE = re.compile(r"@[A-Za-z0-9._-]+/[A-Za-z0-9._-]+:")+@frozenclass DigestPRSummary:@@ -146,14 +174,14 @@ class DigestPRSummary:class DigestSummary:# 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.+ # rules that drop a merge before the model, 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- # sentence, when the headline call failed, and always on the deterministic fallback, which- # judges nothing at all. The renderer then leads with the first change's own line, so an empty- # headline still posts a usable digest.+ # the per-PR lines go to its thread. Empty when the headline call failed or answered with+ # something we will not post, and always on the deterministic fallback, which judges nothing at+ # all. The renderer then leads with the first change's own line, so an empty headline still+ # posts a usable digest.headline: str = ""prs: list[DigestPRSummary] = field(default_factory=list)# False when the deterministic fallback built this summary, so no model judged any of these@@ -182,6 +210,76 @@ def _build_summary(return DigestSummary(considered=considered, headline=headline, prs=prs[:limit], judged=judged)+@frozen+class _ReviewedSummary:+ """A reviewed summary taken apart: the sentence about the whole change, and each team's clause.++ ``clauses`` is keyed by the casefolded team slug the clause opens with. Empty for a summary+ about a merge one team owns, and for every summary an engine older than the per-team clauses+ wrote.+ """++ whole_change: str+ clauses: dict[str, str]+++def _split_clauses(summary_line: str) -> _ReviewedSummary:+ """Split a reviewed summary on the handles its per-team clauses open with.++ ``re.split`` on a pattern with one group returns the text before the first match, then each+ captured handle followed by the text after it, so the parts alternate from index 1 onwards.++ The first clause a slug opens wins, so a handle the reviewer names again later inside another+ team's clause cannot replace that team's own clause.+ """+ parts = _TEAM_CLAUSE_RE.split(summary_line)+ clauses: dict[str, str] = {}+ for i in range(1, len(parts) - 1, 2):+ clauses.setdefault(team_slug_from_handle(parts[i]).casefold(), parts[i + 1].strip())+ whole_change = parts[0].strip()+ # A handle left inside a part is a clause boundary the split did not see, so that part carries+ # another team's text. Discarding the whole summary costs this team the reviewed sentence and+ # leaves it the title; keeping it would post the other team's clause under this team's name.+ if _ANY_HANDLE_RE.search(whole_change) or any(_ANY_HANDLE_RE.search(clause) for clause in clauses.values()):+ logger.info("stamphog_digest_summary_unparsed")+ return _ReviewedSummary(whole_change="", clauses={})+ return _ReviewedSummary(whole_change=whole_change, clauses=clauses)+++def _whole_change_sentence(summary_line: str) -> str:+ """The reviewed summary with the per-team clauses taken off the end.++ What is left is about the whole change, so it is true for whoever reads it.+ """+ return _split_clauses(summary_line).whole_change+++def _addressed_summary(reviewed: _ReviewedSummary, team_slug: str) -> str | None:+ """The reviewed text this audience may read, or None when the reviewer wrote it none.++ A summary carrying no clause at all describes one team's merge and is read whole, and so is one+ read by a repo that declared its own channel, which is not a team a clause is addressed to.+ """+ if not reviewed.clauses or not team_slug:+ return reviewed.whole_change+ # Keyed on the slug, never the whole handle: the audience key never carries the org half, and+ # the reviewer may recase the handle it copied.+ clause = reviewed.clauses.get(team_slug.casefold())+ if clause is None:+ return None+ return f"{reviewed.whole_change} {clause}".strip()+++def _reviewed_for_prompt(summary_line: str, team_slug: str) -> str:+ """What a prompt's <reviewed_summary> carries for one merge.++ A team the reviewer wrote no clause for still reads the sentence about the whole change. A team+ owning part of the merge was already dropped over a missing clause (see ``_drop_unaddressed``).+ """+ reviewed = _split_clauses(summary_line)+ return _addressed_summary(reviewed, team_slug) or reviewed.whole_change++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.@@ -189,8 +287,9 @@ def _fallback_summary(prs: list[PullRequest], considered: int) -> DigestSummary:to 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.+ ``prs`` has already had the merges this team is not told about taken out of it, so this path+ drops them too. Those rules need no model, and an outage is the worst moment to post a team+ another team's news."""return _build_summary(considered,@@ -200,7 +299,7 @@ def _fallback_summary(prs: list[PullRequest], considered: int) -> DigestSummary:title=pr.title,url=pr.pr_url,author_login=pr.author_login,- summary=pr.summary_line or pr.title,+ summary=_whole_change_sentence(pr.summary_line) or pr.title,repository=pr.repo_config.repository,)for pr in prs@@ -209,7 +308,30 @@ def _fallback_summary(prs: list[PullRequest], considered: int) -> DigestSummary:)-def _build_selection_prompt(prs: list[PullRequest], audiences: list[PullRequestAudience] | None = None) -> str:+def _audience_team_slug(audiences: list[PullRequestAudience] | None) -> str:+ """The team both prompts are written for, or "" when the audience is not a team.++ Every row in one digest carries the same audience key, because the claim that opened the run+ filtered on it (see logic/digest_runs._claim_and_partition), so the first row answers for all+ of them. A repo that declared its own channel is a repository rather than a team, so no clause+ is ever addressed to it and it reads the sentence about the whole change.+ """+ if not audiences:+ return ""+ key = audiences[0].audience_key+ return "" if key.startswith(REPO_AUDIENCE_PREFIX) else key+++def _audience_block(team_slug: str) -> tuple[str, ...]:+ """Who this digest is for. Empty for a repo that declared its own channel, which is not a team."""+ if not team_slug:+ return ()+ return (f"This digest goes to the team `{team_slug}`.", "")+++def _build_selection_prompt(+ prs: list[PullRequest], audiences: list[PullRequestAudience] | None = None, team_slug: str = ""+) -> str:lines = ["You pick which merged pull requests a team sees in a short Slack digest, and you write the","one line each of them gets.",@@ -287,22 +409,53 @@ def _build_selection_prompt(prs: list[PullRequest], audiences: list[PullRequestA"- Drop: a right panel stays closed after you close it.","- Drop: a test now covers an id flowing through auth. Nothing observable changed.","",- "A <reviewed_summary> is stamphog's own one-line description, written while it reviewed the",- "diff. It is the input to trust. Rewrite it to the rules below, or keep it when it already",+ "A <reviewed_summary> is stamphog's own description of the change, written while it reviewed",+ "the diff. It is the input to trust. Rewrite it to the rules below, or keep it when it already","follows them. A pull request stamphog never summarized has only its title, which is the","author's claim about their own change rather than a reviewed fact.","",- "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 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.",+ "WHOSE CHANGE THE LINE IS ABOUT",+ "",+ *_audience_block(team_slug),+ "A `your_files` line means this digest goes to the team owning those files, so judge the pull",+ "request 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). 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.",+ "",+ "A marker reading `count=3 of 8` means this team owns three of the eight changed files, so",+ "somebody else owns the rest and the line is about their three files only. Write what a",+ "reader on that team recognizes as their own code: the file they would open, and what it does",+ "now for whoever calls it. Do not write about the feature another team built on top of it.",+ "",+ "Name the perspective of every line you keep:",+ "- scope your_files: the line says what is true now for the files this team owns.",+ "- scope whole_pr: the line is about the pull request overall.",+ "",+ "If you cannot say what changed inside their files, mark the line whole_pr. A whole_pr line is",+ "dropped for a team that owns only part of the merge, and silence costs that team less than",+ "another team's news does.",+ "",+ "PERSPECTIVE EXAMPLE",+ "",+ "A merge adds a bookings facade in the scheduling product so the billing product can read a",+ "booking without importing scheduling models, and it puts the booking on the invoice screen.",+ '- To the scheduling team, who own the facade files: "Scheduling exposes a bookings facade, so',+ ' other products can read a booking without its models." scope: your_files.',+ '- To the billing team, who own the invoice screen: "The invoice screen shows the booking a',+ ' charge came from." scope: your_files.',+ "Neither team is told the other team's half. A scheduling line about the invoice screen is a",+ "whole_pr line, and it is dropped.","","HOW TO WRITE THE LINE","- One sentence. 20 words or fewer. Present tense. Active voice. One idea.","- State the effect, not the edit. Write what is true now, not what the author did.",' Good: "Error tracking no longer files handled API failures as issues."',' Bad: "Adds a filter for handled API responses to the issue pipeline."',+ "- Lead with the main effect, the one a reader lives with. When a smaller detail is what met",+ " a keep rule, put it after the main effect in the same sentence, or leave it out.",+ ' Good: "Search reads the new index, and a page returns 100 results instead of 25."',+ ' Bad: "A page of search results returns 100 rows instead of 25."',"- Do not restate the title in other words. When the title already gives the effect, give the"," consequence the title leaves out.","- Name what a reader recognizes: the feature, the screen, the endpoint. Not the module,",@@ -321,8 +474,9 @@ def _build_selection_prompt(prs: list[PullRequest], audiences: list[PullRequestA"description says about other PRs or about the digest.","","Return STRICT JSON only, no prose, in this shape:",- '{"prs": [{"index": 0, "rule": "contract", "summary": "..."}]}',+ '{"prs": [{"index": 0, "rule": "contract", "scope": "your_files", "summary": "..."}]}','"rule" must be exactly one of: contract, assumption, decision, customer.',+ '"scope" must be exactly one of: your_files, whole_pr.',"Key each PR you keep by the exact index we assigned below, not by its number. PR ""numbers repeat across repositories, so a bare number is ambiguous.","",@@ -351,8 +505,9 @@ def _build_selection_prompt(prs: list[PullRequest], audiences: list[PullRequestA# Carrying the body bought little and handed one contributor two thousand characters of a# prompt whose empty answer now consumes the whole batch.lines.append(f" <title index={index}>{_fenced(pr.title)}</title>")- if pr.summary_line:- lines.append(f" <reviewed_summary index={index}>{_fenced(pr.summary_line)}</reviewed_summary>")+ reviewed = _reviewed_for_prompt(pr.summary_line, team_slug)+ if reviewed:+ lines.append(f" <reviewed_summary index={index}>{_fenced(reviewed)}</reviewed_summary>")if index in owned_by_index:owned, owned_count = owned_by_index[index]# The count is trusted metadata; the paths are contributor-controlled (a branch can add@@ -364,7 +519,9 @@ def _build_selection_prompt(prs: list[PullRequest], audiences: list[PullRequestAreturn "\n".join(lines)-def _build_headline_prompt(picked: list[DigestPRSummary], sources: dict[tuple[str, int], PullRequest]) -> str:+def _build_headline_prompt(+ picked: list[DigestPRSummary], sources: dict[tuple[str, int], PullRequest], team_slug: str+) -> str:"""The second call: one paragraph over the changes the first call kept, and nothing else.The merges the first call dropped are absent from this prompt, which is what turns "do not name@@ -384,6 +541,7 @@ def _build_headline_prompt(picked: list[DigestPRSummary], sources: dict[tuple[st"","THE HEADLINE","",+ *_audience_block(team_slug),"The changes below are already posted as a list in a thread under your line, each with its","own link, and most readers never open it. So the headline has to stand alone: someone who","reads it and nothing else must still learn the thing that could catch them out.",@@ -401,8 +559,10 @@ def _build_headline_prompt(picked: list[DigestPRSummary], sources: dict[tuple[st"- No bullets, no numbered points, no line breaks, and no headings. Plain sentences only.","- Open with what is true now. Do not open with a count, a date, or the word digest.","- Name the area in the words the team uses, so a reader can tell whether it touches them.",- "- Return an empty string when everything below is routine. The thread still carries the",- " lines, and a channel post that promises news it does not have costs more than silence.",+ "- Always write the paragraph. Everything below already cleared the bar for the thread, so",+ " there is something here worth a line in the channel.",+ "- When there is one change below, do not restate its line. The reader has that sentence in",+ " the thread under yours. Say why it matters to them, and what they would do about it.","",*_STYLE_RULES,"",@@ -419,8 +579,9 @@ def _build_headline_prompt(picked: list[DigestPRSummary], sources: dict[tuple[stfor pr in picked:lines.append(f"- <title>{_fenced(pr.title)}</title>")source = sources.get((pr.repository, pr.pr_number))- if source is not None and source.summary_line:- lines.append(f" <reviewed_summary>{_fenced(source.summary_line)}</reviewed_summary>")+ reviewed = _reviewed_for_prompt(source.summary_line, team_slug) if source is not None else ""+ if reviewed:+ lines.append(f" <reviewed_summary>{_fenced(reviewed)}</reviewed_summary>")lines.append(f" <line>{_fenced(pr.summary)}</line>")return "\n".join(lines)@@ -509,14 +670,20 @@ def _change_line(raw: Any, pr: PullRequest) -> str:which is why it sits last."""line = raw.strip() if isinstance(raw, str) else ""- return line or pr.summary_line or pr.title+ return line or _whole_change_sentence(pr.summary_line) or pr.title-def _parse_selection(content: str, prs_by_index: dict[int, PullRequest]) -> list[DigestPRSummary]:+def _parse_selection(+ content: str, prs_by_index: dict[int, PullRequest], partial_indexes: frozenset[int]+) -> list[DigestPRSummary]:"""Map the model's JSON back onto captured PRs by the index we assigned. Unknown indexes ignored.Keying on a per-PR index (not pr_number) keeps a team digest spanning multiple repos fromcollapsing repo-a#123 and repo-b#123 into one entry — PR numbers are only unique within a repo.++ ``partial_indexes`` names the merges this audience owns only part of, where a line about the+ whole pull request is another team's news. The caller computes it rather than this function,+ because the audience rows only match ``prs_by_index`` positionally."""data = json.loads(_strip_code_fence(content))picked: list[DigestPRSummary] = []@@ -540,6 +707,13 @@ def _parse_selection(content: str, prs_by_index: dict[int, PullRequest]) -> list# response where nothing survives this raises below and falls back to the plain list.logger.info("stamphog_digest_pr_dropped_without_rule", pr_number=pr.pr_number, rule=repr(rule))continue+ scope = item.get("scope")+ if index in partial_indexes and scope != SCOPE_YOUR_FILES:+ # This team owns part of the merge, and the model did not claim the line is about that+ # part. A missing or misspelled scope reads the same way as whole_pr here, because the+ # claim is what the check is for and an absent one is not a claim.+ logger.info("stamphog_digest_pr_dropped_wrong_scope", pr_number=pr.pr_number, scope=repr(scope))+ continuepicked.append(DigestPRSummary(pr_number=pr.pr_number,@@ -564,26 +738,52 @@ 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.+def _partly_owned(pr: PullRequest, audience: PullRequestAudience) -> bool:+ """True when this team owns some, but not all, of the merge's changed files.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.+ row an older engine wrote. A count of zero is therefore not partial ownership: a repo-declared+ audience asked for every merge in its repository, and a row carrying no count says nothing+ either way. Both are left to the model with no rule of ours applied to them."""+ return 0 < audience.owned_file_count < pr.changed_files+++def _grazed(pr: PullRequest, audience: PullRequestAudience | None) -> bool:+ """True when one file of a large change reached this team, so the team was swept, not targeted."""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."""+@frozen+class _AudienceMerges:+ """The merges one audience is told about, with its rows still positionally matched.++ ``partial_indexes`` names the positions the team owns only part of, for the scope check. They+ are read off the same walk that decided which positions survive, because the prompt hands the+ model those positions as its indexes.+ """++ prs: list[PullRequest]+ audiences: list[PullRequestAudience] | None+ partial_indexes: frozenset[int]+++def _drop_unaddressed(+ prs: list[PullRequest], audiences: list[PullRequestAudience] | None, team_slug: str+) -> _AudienceMerges:+ """The merges this audience is actually told about.++ Two rules, both about a merge this team owns only part of, and both applied before any model+ reads it. A graze reached the team through a single file of a large change. A merge whose+ reviewed summary names owning teams and not this one was described by a reviewer that had the+ diff and found nothing to say about this team's files, so it is somebody else's news.+ """if not audiences:- return prs, audiences+ return _AudienceMerges(prs=prs, audiences=audiences, partial_indexes=frozenset())- kept_prs = []- kept_audiences = []+ kept_prs: list[PullRequest] = []+ kept_audiences: list[PullRequestAudience] = []+ partial_indexes: set[int] = set()for pr, audience in zip(prs, audiences):if _grazed(pr, audience):logger.info(@@ -593,29 +793,41 @@ def _drop_grazes(changed_files=pr.changed_files,)continue+ partly_owned = _partly_owned(pr, audience)+ if partly_owned and _addressed_summary(_split_clauses(pr.summary_line), team_slug) is None:+ logger.info(+ "stamphog_digest_no_clause_for_team",+ pr_number=pr.pr_number,+ audience_key=audience.audience_key,+ )+ continue+ if partly_owned:+ partial_indexes.add(len(kept_prs))kept_prs.append(pr)kept_audiences.append(audience)- return kept_prs, kept_audiences+ return _AudienceMerges(prs=kept_prs, audiences=kept_audiences, partial_indexes=frozenset(partial_indexes))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``. 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.+ grazed the team, and one the reviewer addressed to other teams alone, are both dropped here+ before any model reads them. What survives goes to the prompt with its file sample and with the+ reviewed text written for this team, 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:+ team_slug = _audience_team_slug(audiences)+ told = _drop_unaddressed(prs, audiences, team_slug)+ if not told.prs:return _build_summary(considered, [])- team_id = prs[0].team_id+ team_id = told.prs[0].team_idtry:client = build_anthropic_client("stamphog",@@ -625,12 +837,13 @@ def summarize_merged_prs(prs: list[PullRequest], audiences: list[PullRequestAudidistinct_id=team_distinct_id(team_id),)picked = _parse_selection(- _complete(client, team_id, _build_selection_prompt(prs, audiences)),- dict(enumerate(prs)),+ _complete(client, team_id, _build_selection_prompt(told.prs, told.audiences, team_slug)),+ dict(enumerate(told.prs)),+ told.partial_indexes,)except Exception as e:logger.warning("stamphog_digest_summarize_fallback", team_id=team_id, error=str(e))- return _fallback_summary(prs, considered)+ return _fallback_summary(told.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@@ -638,7 +851,7 @@ def summarize_merged_prs(prs: list[PullRequest], audiences: list[PullRequestAudisummary = _build_summary(considered, picked)if not summary.prs:return summary- return replace(summary, headline=_request_headline(client, team_id, summary.prs, prs))+ return replace(summary, headline=_request_headline(client, team_id, summary.prs, told.prs, team_slug))def _complete(client: Any, team_id: int, prompt: str, *, max_tokens: int = _DIGEST_MAX_TOKENS) -> str:@@ -653,7 +866,9 @@ def _complete(client: Any, team_id: int, prompt: str, *, max_tokens: int = _DIGEreturn "".join(block.text for block in response.content if getattr(block, "type", "") == "text")-def _request_headline(client: Any, team_id: int, picked: list[DigestPRSummary], prs: list[PullRequest]) -> str:+def _request_headline(+ client: Any, team_id: int, picked: list[DigestPRSummary], prs: list[PullRequest], team_slug: str+) -> str:"""The channel paragraph, or "" when the second call fails or gives nothing worth posting.Failures here are swallowed rather than taken to the deterministic fallback. The selection call@@ -664,7 +879,7 @@ def _request_headline(client: Any, team_id: int, picked: list[DigestPRSummary],sources = {(pr.repo_config.repository, pr.pr_number): pr for pr in prs}try:bounded = client.with_options(timeout=_HEADLINE_TIMEOUT_SECONDS, max_retries=_HEADLINE_MAX_RETRIES)- prompt = _build_headline_prompt(picked, sources)+ prompt = _build_headline_prompt(picked, sources, team_slug)return _parse_headline(_complete(bounded, team_id, prompt, max_tokens=_HEADLINE_MAX_TOKENS))except Exception as e:logger.warning("stamphog_digest_headline_fallback", team_id=team_id, error=str(e))diff --git a/products/stamphog/backend/logic/digest_runs.py b/products/stamphog/backend/logic/digest_runs.pyindex 3372ddb69226..22cc04f0438b 100644--- a/products/stamphog/backend/logic/digest_runs.py+++ b/products/stamphog/backend/logic/digest_runs.py@@ -249,7 +249,15 @@ def _claim_and_partition(if (destination := resolve_destination(context, audience_key, repository)) is not None}if not destination_by_repo:- logger.info("stamphog_digest_no_destination", team_id=team_id, audience_key=audience_key)+ # Warning rather than info because nothing else reports this: the merges stay unclaimed and+ # expire after DIGEST_LOOKBACK_DAYS. The repositories name the registries that were read, so+ # a slug that is misspelled or no longer a live GitHub team is identifiable from the log.+ logger.warning(+ "stamphog_digest_no_destination",+ team_id=team_id,+ audience_key=audience_key,+ repositories=sorted(context.registry_by_repo),+ )return []with transaction.atomic(using=write_db):diff --git a/products/stamphog/backend/logic/reviewer.py b/products/stamphog/backend/logic/reviewer.pyindex 4df8d2660150..91c21c1996bb 100644--- a/products/stamphog/backend/logic/reviewer.py+++ b/products/stamphog/backend/logic/reviewer.py@@ -23,8 +23,12 @@ from __future__ import annotationsimport jsonfrom dataclasses import field+import structlog+from posthog.dataclasses import frozen+logger = structlog.get_logger(__name__)+# Final-verdict strings the engine emits (review_pr.Pipeline.final_verdict) mapped# onto the contract's ReviewVerdict values. Anything unrecognized escalates —# never silently approve on a verdict we can't trust.@@ -51,9 +55,9 @@ _LEGACY_VERDICT_MAP = {}-# Mirrors the engine's VERDICT_SCHEMA cap (products/stamphog/packages/pr-approval-agent/reviewer.py) and the-# stamphog_reviewrun column width.-CHANGE_SUMMARY_MAX_CHARS = 200+# Mirrors the engine's VERDICT_SCHEMA cap (products/stamphog/packages/pr-approval-agent/reviewer.py).+# The columns that hold this text are TextField, so the schema is the only width it must respect.+CHANGE_SUMMARY_MAX_CHARS = 600@frozen@@ -87,9 +91,10 @@ class ReviewerVerdict:# The engine-rendered comment body (reasoning + judgment bullets + gate# mechanics), posted verbatim when present.review_body: str = ""- # One-sentence plain-language description of what the change does, written- # in the sandbox where the diff is available. Feeds the daily digest. Blank- # when the engine predates the field, which the digest tolerates.+ # Plain-language description of what the change does, written in the sandbox where the diff is+ # available: one sentence about the whole change, plus one clause per owning team when more+ # than one team owns files in it. Feeds the daily digest, which reads the clause addressed to+ # its own audience. Blank when the engine predates the field, which the digest tolerates.change_summary: str = ""# The engine version the output reports, for analytics segmentation.stamphog_version: str = ""@@ -190,7 +195,12 @@ def _parse_rich(obj: dict) -> ReviewerVerdict:reasoning = str(reviewer.get("reasoning", "")).strip()# Clipped rather than rejected: the engine caps this at CHANGE_SUMMARY_MAX_CHARS, but the# value crosses a trust boundary, so the server does not rely on the sandbox honoring it.- change_summary = str(reviewer.get("change_summary", "")).strip()[:CHANGE_SUMMARY_MAX_CHARS]+ # Warned about because a clip inside the last per-team clause drops that team's merge from the+ # digest with nothing else to see it.+ change_summary = str(reviewer.get("change_summary", "")).strip()+ if len(change_summary) > CHANGE_SUMMARY_MAX_CHARS:+ logger.warning("stamphog_change_summary_clipped", length=len(change_summary), limit=CHANGE_SUMMARY_MAX_CHARS)+ change_summary = change_summary[:CHANGE_SUMMARY_MAX_CHARS]issues = reviewer.get("issues") or []showstoppers = [str(i) for i in issues] if isinstance(issues, list) else [str(issues)]diff --git a/products/stamphog/backend/migrations/0006_change_summaries_hold_a_clause_per_team.py b/products/stamphog/backend/migrations/0006_change_summaries_hold_a_clause_per_team.pynew file mode 100644index 000000000000..72b2485ea612--- /dev/null+++ b/products/stamphog/backend/migrations/0006_change_summaries_hold_a_clause_per_team.py@@ -0,0 +1,26 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ """Drop the width from the reviewed change summary, which now carries a clause per owning team.++ varchar(200) to text is binary-coercible in Postgres, so neither table is rewritten and no row+ is read. Each ALTER still takes a brief ACCESS EXCLUSIVE lock while it updates the catalog.+ """++ dependencies = [+ ("stamphog", "0005_index_digest_runs_by_audience"),+ ]++ operations = [+ migrations.AlterField(+ model_name="pullrequest",+ name="summary_line",+ field=models.TextField(blank=True, default=""),+ ),+ migrations.AlterField(+ model_name="reviewrun",+ name="change_summary",+ field=models.TextField(blank=True, default=""),+ ),+ ]diff --git a/products/stamphog/backend/migrations/max_migration.txt b/products/stamphog/backend/migrations/max_migration.txtindex 4ac1e7dd9ac2..deba719591e4 100644--- a/products/stamphog/backend/migrations/max_migration.txt+++ b/products/stamphog/backend/migrations/max_migration.txt@@ -1 +1 @@-0005_index_digest_runs_by_audience+0006_change_summaries_hold_a_clause_per_teamdiff --git a/products/stamphog/backend/models.py b/products/stamphog/backend/models.pyindex 793338507c49..868e93ef973c 100644--- a/products/stamphog/backend/models.py+++ b/products/stamphog/backend/models.py@@ -112,10 +112,11 @@ class PullRequest(ProductTeamModel):# Digest bucket resolved by the audience cascade (see logic/audiences.py) — stamped only# when the merged PR is digest-eligible (stamphog approved a run); the digest filters on it.audience_key = models.CharField(max_length=255, blank=True)- # What the change does, in one sentence, copied from the run that approved the merged head.- # Written in the sandbox with the diff in hand, which the daily digest no longer has. Blank- # when the engine predates the field; the digest falls back to the PR title.- summary_line = models.CharField(max_length=200, blank=True, default="")+ # What the change does, copied from the run that approved the merged head. One sentence, plus+ # one clause per owning team when more than one team owns files in the merge. Written in the+ # sandbox with the diff in hand, which the daily digest no longer has. Blank when the engine+ # predates the field; the digest falls back to the PR title.+ summary_line = models.TextField(blank=True, default="")digest_run = models.ForeignKey("DigestRun", on_delete=models.SET_NULL, null=True, related_name="pull_requests")# Historical: the sticky comment a verdict used to be written into. Verdicts are reviews now, so# nothing writes this any more — it holds the last comment id from before that change. Kept@@ -214,10 +215,12 @@ class ReviewRun(ProductTeamModel):)gate_result = models.JSONField(null=True)output = models.JSONField(default=dict)- # One sentence on what the change does, from the reviewer's structured verdict. Its own field- # rather than a slice of `output`, which mixes reviewer stdout with PR patches and policy- # contents. Copied onto the PullRequest when the approved head is the one that merges.- change_summary = models.CharField(max_length=200, blank=True, default="")+ # What the change does, from the reviewer's structured verdict: one sentence, plus one clause+ # per owning team when more than one team owns files in the merge. Its own field rather than a+ # slice of `output`, which mixes reviewer stdout with PR patches and policy contents. Copied+ # onto the PullRequest when the approved head is the one that merges. The width lives in the+ # reviewer schema (logic/reviewer.CHANGE_SUMMARY_MAX_CHARS), not in the column.+ change_summary = models.TextField(blank=True, default="")error = models.TextField(blank=True)# What we posted back to the SCM once the verdict was decided — recorded so a# re-review can find and update its own artifacts, and for audit. Populated bydiff --git a/products/stamphog/backend/tests/test_digest.py b/products/stamphog/backend/tests/test_digest.pyindex 75c9279dc0de..e3b7e6400c1c 100644--- a/products/stamphog/backend/tests/test_digest.py+++ b/products/stamphog/backend/tests/test_digest.py@@ -19,6 +19,7 @@ from posthog.models.integration import Integrationfrom posthog.models.scoping import team_scopefrom products.stamphog.backend.facade.enums import AudienceReason, ChannelResolutionSource, DigestRunStatus+from products.stamphog.backend.logic.audiences import REPO_AUDIENCE_PREFIXfrom products.stamphog.backend.logic.channel_resolution import (Destination,RoutingContext,@@ -33,9 +34,14 @@ from products.stamphog.backend.logic.digest import (GRAZE_CHANGED_FILES,MAX_DIGEST_PRS,MAX_FALLBACK_PRS,+ SCOPE_YOUR_FILES,DigestPRSummary,DigestSummary,+ _audience_team_slug,+ _build_headline_prompt,+ _build_selection_prompt,_build_summary,+ _fallback_summary,_parse_selection,summarize_merged_prs,)@@ -788,6 +794,15 @@ def test_the_digest_call_names_its_product_team_and_source() -> None:assert "extra_headers" not in selection_call and "user" not in selection_call+def _audience(owned_count: int, reason: AudienceReason = AudienceReason.OWNED) -> PullRequestAudience:+ return PullRequestAudience(+ audience_key=AUDIENCE,+ reason=reason,+ owned_files=[f"a{i}.py" for i in range(owned_count)],+ owned_file_count=owned_count,+ )++@pytest.mark.parametrize("owned_count,changed_files,dropped",[@@ -807,16 +822,10 @@ def test_a_merge_that_only_grazed_the_team_never_reaches_the_model(grazed = _pr_stub("o/r", 1, "Swept in", "https://github.com/o/r/pull/1")grazed.changed_files = changed_filesowned = _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."}]})+ audiences = [_audience(owned_count), _audience(1)]+ selection = json.dumps(+ {"prs": [{"index": 0, "rule": "contract", "scope": SCOPE_YOUR_FILES, "summary": "The first one."}]}+ )client = _recording_llm_client([selection, json.dumps({"headline": "Something shipped."})])with patch("products.stamphog.backend.logic.digest.build_anthropic_client", return_value=client):@@ -829,6 +838,188 @@ def test_a_merge_that_only_grazed_the_team_never_reaches_the_model(assert summary.considered == 2+ "audience,claim,kept",+ [+ (_audience(3), {"scope": "whole_pr"}, False),+ (_audience(3), {}, False),+ (_audience(3), {"scope": 42}, False),+ (_audience(3), {"scope": SCOPE_YOUR_FILES}, True),+ (_audience(8), {}, True),+ (_audience(0, AudienceReason.REPO_DECLARED), {}, True),+ ],+ ids=[+ "a_line_about_the_whole_pr_is_not_this_teams_news",+ "and_neither_is_one_that_claims_no_perspective",+ "nor_one_whose_claim_is_not_even_a_string",+ "a_line_written_from_the_owned_files_stays",+ "a_team_owning_every_changed_file_claims_nothing",+ "and_a_repo_declared_audience_has_no_files_to_claim",+ ],+)+def test_a_line_about_another_teams_half_of_a_merge_is_dropped(+ audience: PullRequestAudience, claim: dict[str, Any], kept: bool+) -> None:+ # The model names the perspective in its answer, so the code can check it here.+ #+ # The partly owned merge goes first so a check that dropped by position rather than by the index+ # the model was given would take the wrong entry with it.+ partly = _pr_stub("o/r", 1, "Adds a facade the other product calls", "https://github.com/o/r/pull/1")+ partly.changed_files = 8+ ours = _pr_stub("o/r", 2, "Ours", "https://github.com/o/r/pull/2")+ ours.changed_files = 2+ entry = {"index": 0, "rule": "contract", "summary": "The other team's feature ships.", **claim}+ selection = json.dumps(+ {+ "prs": [+ entry,+ {"index": 1, "rule": "contract", "scope": SCOPE_YOUR_FILES, "summary": "Our own area changed."},+ ]+ }+ )+ client = _recording_llm_client([selection, json.dumps({"headline": "Something shipped."})])++ with patch("products.stamphog.backend.logic.digest.build_anthropic_client", return_value=client):+ summary = summarize_merged_prs([partly, ours], [audience, _audience(2)])++ ours_line = (2, "Our own area changed.")+ expected = [(1, "The other team's feature ships."), ours_line] if kept else [ours_line]+ assert [(pr.pr_number, pr.summary) for pr in summary.prs] == expected+++_WHOLE_CHANGE = "Uploads pause when a workspace spends the daily quota."+_OUR_CLAUSE = "the upload path asks a limiter before it writes."+_THEIR_CLAUSE = "@PostHog/team-billing: the counters moved."+_MULTI_TEAM_SUMMARY = f"{_WHOLE_CHANGE} @PostHog/{AUDIENCE}: {_OUR_CLAUSE} {_THEIR_CLAUSE}"+_OTHER_TEAM_SUMMARY = f"{_WHOLE_CHANGE} {_THEIR_CLAUSE}"+++ "summary_line,audience,changed_files,expected",+ [+ (_MULTI_TEAM_SUMMARY, _audience(3), 8, f"{_WHOLE_CHANGE} {_OUR_CLAUSE}"),+ (_OTHER_TEAM_SUMMARY, _audience(2), 2, _WHOLE_CHANGE),+ (+ _MULTI_TEAM_SUMMARY,+ PullRequestAudience(audience_key=f"{REPO_AUDIENCE_PREFIX}{REPO}", reason=AudienceReason.REPO_DECLARED),+ 8,+ _WHOLE_CHANGE,+ ),+ (+ f"The CLI moves to @posthog/cli: the old binary is gone. @PostHog/{AUDIENCE}: {_OUR_CLAUSE} {_THEIR_CLAUSE}",+ _audience(3),+ 8,+ "",+ ),+ (+ f"{_WHOLE_CHANGE[:-1]} @PostHog/{AUDIENCE}: {_OUR_CLAUSE[:-1]} {_THEIR_CLAUSE}",+ _audience(3),+ 8,+ "",+ ),+ (+ f"{_WHOLE_CHANGE} @PostHog/{AUDIENCE}: {_OUR_CLAUSE} "+ f"@PostHog/team-billing: the counters moved. @PostHog/{AUDIENCE}: reads them.",+ _audience(3),+ 8,+ f"{_WHOLE_CHANGE} {_OUR_CLAUSE}",+ ),+ ],+ ids=[+ "a_team_owning_part_of_the_merge_reads_its_own_clause",+ "a_team_owning_all_of_it_reads_the_whole_change_sentence",+ "and_so_does_a_repo_that_declared_its_own_channel",+ "a_handle_that_does_not_open_a_sentence_discards_the_summary_rather_than_leaking_it",+ "and_so_does_a_clause_written_without_a_period_before_it",+ "a_handle_named_again_inside_another_clause_does_not_replace_the_teams_own",+ ],+)+def test_the_prompt_carries_only_the_reviewed_text_written_for_this_audience(+ summary_line: str, audience: PullRequestAudience, changed_files: int, expected: str+) -> None:+ # The reviewer holds the diff, so it decides what each team hears and writes them a clause each.+ # Picking that clause here, rather than asking the model to ignore the others, is what makes+ # another team's half of the merge unreachable: it is not in the prompt to be picked.+ pr = _pr_stub("o/r", 1, "Ship it", "https://github.com/o/r/pull/1")+ pr.changed_files = changed_files+ pr.summary_line = summary_line++ prompt = _build_selection_prompt([pr], [audience], _audience_team_slug([audience]))++ if expected:+ assert f"<reviewed_summary index=0>{expected}</reviewed_summary>" in prompt+ else:+ assert "<reviewed_summary index=0>" not in prompt+ assert "team-billing" not in prompt+ assert "the counters moved" not in prompt+++def test_a_merge_the_reviewer_wrote_this_team_no_clause_for_never_reaches_the_model() -> None:+ # The reviewer named the owning teams and this team was not one of them, so it had the diff and+ # found nothing to say about this team's files. Dropping it here costs the team silence; posting+ # it costs them the other team's announcement in their own channel.+ #+ # The dropped merge goes first so a filter that forgot to renumber the index map would resolve+ # the model's index 0 to the wrong PR.+ unaddressed = _pr_stub("o/r", 1, "Somebody else's half", "https://github.com/o/r/pull/1")+ unaddressed.changed_files = 8+ unaddressed.summary_line = (+ "Invoices show the booking a charge came from. @PostHog/team-billing: the screen reads a facade."+ )+ ours = _pr_stub("o/r", 2, "Ours", "https://github.com/o/r/pull/2")+ ours.changed_files = 2+ selection = json.dumps(+ {"prs": [{"index": 0, "rule": "contract", "scope": SCOPE_YOUR_FILES, "summary": "Our own area changed."}]}+ )+ client = _recording_llm_client([selection, json.dumps({"headline": "Something shipped."})])++ with patch("products.stamphog.backend.logic.digest.build_anthropic_client", return_value=client):+ summary = summarize_merged_prs([unaddressed, ours], [_audience(3), _audience(2)])++ assert "Somebody else's half" not in client.prompts[0]+ assert [(pr.pr_number, pr.summary) for pr in summary.prs] == [(2, "Our own area changed.")]+ # The scope line still counts every merge the audience claimed, the way the graze rule leaves it.+ assert summary.considered == 2+++def test_the_selection_prompt_asks_for_the_perspective_the_code_checks() -> None:+ # The two halves of this rule sit in different files. The code drops a partly owned merge whose+ # line does not claim the team's own files, so a prompt that stopped asking for that claim would+ # empty those teams' digests without failing anything.+ pr = _pr_stub("o/r", 1, "Ship it", "https://github.com/o/r/pull/1")+ pr.changed_files = 8++ prompt = _build_selection_prompt([pr], [_audience(3)], AUDIENCE)++ assert SCOPE_YOUR_FILES in prompt+ assert "whole_pr" in prompt+ assert '"scope": "your_files"' in prompt # the shape the answer is read out of+ # The audience is the only thing in either prompt that says whose side the line is written+ # from, now that the clause it reads is picked in code rather than named in the prompt.+ assert f"the team `{AUDIENCE}`" in prompt+++def test_the_headline_prompt_asks_for_a_paragraph_every_time() -> None:+ # An empty headline on a single-change digest makes the renderer promote that change's own+ # line, so the channel post and the first thread line become the same sentence.+ picked = [+ DigestPRSummary(+ pr_number=1,+ title="Ship it",+ url="https://github.com/o/r/pull/1",+ author_login="dev",+ summary="The scanner stops at 24 months.",+ repository="o/r",+ )+ ]++ prompt = _build_headline_prompt(picked, {}, AUDIENCE)++ assert "empty string" not in prompt+ assert "do not restate its line" in prompt+ assert f"the team `{AUDIENCE}`" in prompt++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 a@@ -908,11 +1099,29 @@ def test_only_a_string_becomes_a_change_line(raw_summary: Any, expected: str) ->pr.summary_line = "The reviewer's own sentence."content = json.dumps({"prs": [{"index": 0, "rule": "contract", "summary": raw_summary}]})- picked = _parse_selection(content, {0: pr})+ picked = _parse_selection(content, {0: pr}, frozenset())assert [p.summary for p in picked] == [expected]+def test_the_paths_that_skip_the_model_drop_the_other_teams_clauses() -> None:+ # The reviewed summary carries one clause per owning team now, and two paths post it without a+ # model picking this team's clause out of it: a malformed entry, and the outage fallback.+ pr = _pr_stub("o/r", 1, "The author's own claim.", "https://github.com/o/r/pull/1")+ pr.summary_line = (+ "Uploads pause when a workspace spends its quota. "+ "@PostHog/team-storage: the upload path asks a limiter first. "+ "@PostHog/team-billing: the counters live in that limiter."+ )+ whole_change = "Uploads pause when a workspace spends its quota."+ content = json.dumps({"prs": [{"index": 0, "rule": "contract", "summary": None}]})++ picked = _parse_selection(content, {0: pr}, frozenset())++ assert [p.summary for p in picked] == [whole_change]+ assert [p.summary for p in _fallback_summary([pr], 1).prs] == [whole_change]++@parameterized.expand([("empty_list_is_intentional_filtering", '{"prs": []}', True),@@ -937,10 +1146,10 @@ def test_only_a_genuinely_empty_result_posts_nothing(_name: str, content: str, a# an empty post instead of falling back to the deterministic list.prs_by_index = {0: _pr_stub("PostHog/posthog", 1, "Title", "https://example.com/1")}if accepted:- assert _parse_selection(content, prs_by_index) == []+ assert _parse_selection(content, prs_by_index, frozenset()) == []else:with pytest.raises(ValueError):- _parse_selection(content, prs_by_index)+ _parse_selection(content, prs_by_index, frozenset())@pytest.mark.parametrize(diff --git a/products/stamphog/backend/tests/test_logic.py b/products/stamphog/backend/tests/test_logic.pyindex 7ec34a79b654..82135c4eefbd 100644--- a/products/stamphog/backend/tests/test_logic.py+++ b/products/stamphog/backend/tests/test_logic.py@@ -722,7 +722,9 @@ class OwnedFilePromptTests(SimpleTestCase):)for a in resolved]- assert "your_files index=0 count=5 of 5" in _build_selection_prompt([pr], audiences)+ prompt = _build_selection_prompt([pr], audiences, "team-devex")++ assert "your_files index=0 count=5 of 5" in promptdef 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 titlediff --git a/products/stamphog/packages/pr-approval-agent/reviewer.py b/products/stamphog/packages/pr-approval-agent/reviewer.pyindex 49c8ebfcb6aa..4d1b403e2672 100644--- a/products/stamphog/packages/pr-approval-agent/reviewer.py+++ b/products/stamphog/packages/pr-approval-agent/reviewer.py@@ -150,9 +150,13 @@ VERDICT_SCHEMA = {"type": "array","items": {"type": "string"},},+ # The digest splits the per-team clauses back out of this text on the handles they+ # open with (_TEAM_CLAUSE_RE in products/stamphog/backend/logic/digest.py). A clause+ # that regex does not recognize takes its team's merge out of that team's digest, so+ # the clause shape asked for below is a contract with that parser."change_summary": {"type": "string",- "maxLength": 200,+ "maxLength": 600,},},"required": ["verdict", "reasoning", "risk", "issues", "change_summary"],@@ -272,17 +276,36 @@ _REVIEWER_SCAFFOLD_TAIL = "\n" + textwrap.dedent(Do NOT suggest splitting PRs or restructuring to avoid gates.The "change_summary" field is the one place you DO describe what the code- does. One sentence, at most 200 characters, plain language, for a teammate- reading a daily digest who was never on the PR. Say what changed and what- it means for someone using or maintaining that area. No verdict, no risk- assessment, no gate mechanics — those belong in "reasoning". Write it in- your own words: the verbatim-reproduction rule in the security notice covers- this field too, so never quote the diff, title, or description back. Judge- from the diff rather than from what the description claims.+ does. Plain language, for a teammate reading a daily digest who was never on+ the PR. Say what changed and what it means for someone using or maintaining+ that area. No verdict, no risk assessment, no gate mechanics — those belong+ in "reasoning". Write it in your own words: the verbatim-reproduction rule in+ the security notice covers this field too, so never quote the diff, title, or+ description back. Judge from the diff rather than from what the description+ claims. Keep the whole field under 600 characters.++ The first sentence is about the whole change, and says what is true now.+ When the Ownership block's "Files per team" names more than one team, add one+ clause per team after that sentence. Open each clause with that team's handle+ exactly as the Ownership block spells it, such as "@PostHog/team-replay:",+ in plain text with the colon right after it (no bold, no backticks), and do+ not write any other "@name/name:" token anywhere in this field. End the+ sentence before each clause with a period, an exclamation mark, or a+ question mark, and start the clause right after it. A handle that does not+ open a sentence is not read as a clause, and the whole field is then thrown+ away rather than shown to a team it was not written for.+ Say what is true now in the files that team owns. Each team is shown its+ own clause and no other, so a clause has to hold on its own. Leave a team out+ when the diff does not tell you what its files now do: silence is better than+ a guess. Leave a team out as well when every file it owns is one a build step+ generated, because nobody on that team edited anything. With several teams,+ keep each clause short so they all fit: a clause cut off at the limit costs+ that team its line.Examples:- "Trend charts can now be given a fixed y-axis range instead of autoscaling."- "Alert check history records the actual delivery receipt, so a silent send failure is visible."- "The cohort query builder no longer 500s on an empty cohort; it returns an empty result."+ - Two teams own files in one merge: "Uploads pause when a workspace spends its daily quota instead of failing. @PostHog/team-storage: the upload path asks a shared limiter before it writes, and answers with a retry-after. @PostHog/team-billing: the quota counters move into that limiter, so the invoice job reads them from one place."Your output is constrained to a JSON schema with verdict, reasoning,risk, issues, and change_summary fields. Fill them according to the rules@@ -815,9 +838,15 @@ class Reviewer:summary = cl.get("ownership_summary", "")on_team = cl.get("author_on_owning_team", True)per_team = ownership.get("team_file_counts", {})+ generated_per_team = ownership.get("team_generated_file_counts", {})lines = [f"Ownership: {summary}"]if per_team:lines.append(f" Files per team: {json.dumps(per_team)}")+ # A build step writes these, so a team whose whole stake is generated files was not touched+ # by the change. The digest drops such a team from its audiences, and the change_summary+ # rule below tells the reviewer to write it no clause, so the two agree on who is an owner.+ if generated_per_team:+ lines.append(f" Of those, files a build step generated: {json.dumps(generated_per_team)}")# The team-membership note only makes sense when teams own the paths;# for individual-only ownership the summary already says who they are.if teams and not on_team:diff --git a/products/tasks/product.yaml b/products/tasks/product.yamlindex a6614a1c7119..f627b6743ffb 100644--- a/products/tasks/product.yaml+++ b/products/tasks/product.yaml@@ -1,3 +1,3 @@name: Tasksowners:- - team-posthog-code+ - team-posthog-desktop