:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(devex): distributed owners.yaml ownership with a single resolver (#68872)
Julian Bezfdce1b17f458
diff --git a/.agents/owners.yaml b/.agents/owners.yamlnew file mode 100644index 000000000000..d744f52d2194--- /dev/null+++ b/.agents/owners.yaml@@ -0,0 +1,5 @@+version: 1+owners: []+rules:+ - match: '/*'+ owners: team-devexdiff --git a/.agents/skills/establishing-code-ownership/SKILL.md b/.agents/skills/establishing-code-ownership/SKILL.mdindex 133919e45198..5f0cd9daed59 100644--- a/.agents/skills/establishing-code-ownership/SKILL.md+++ b/.agents/skills/establishing-code-ownership/SKILL.md@@ -1,66 +1,61 @@---name: establishing-code-ownership-description: Determine which PostHog team owns a file, directory, or code path, or enumerate all code a team owns (via `products/*/product.yaml` and `.github/CODEOWNERS(-soft)?`). Use when assigning a reviewer, attributing a bug or slow query to a team, routing work, scoping a team-wide audit, or answering "who owns X" / "what does team Y own".+description: Determine which PostHog team owns a file, directory, or code path, or enumerate all code a team owns (via distributed `owners.yaml`, `products/*/product.yaml`, and `.github/CODEOWNERS`). Use when assigning a reviewer, attributing a bug or slow query to a team, routing work, scoping a team-wide audit, or answering "who owns X" / "what does team Y own".---# Establishing code ownership-Two sources, checked in order:+Ownership is resolved by one tool — `hogli owners:*` — over distributed `owners.yaml` files.+Don't re-parse the ownership files by hand; the resolver owns the semantics and is what CI enforces.-1. **`products/*/product.yaml`: source of truth under `products/`.** Lists owning team(s) under `owners:` as bare slugs (the CODEOWNERS handle minus `@PostHog/`: `conversations`, `logs`, `team-self-driving`, …) and owns **all** of `products/<name>/**`. Lives in the dir it owns, so never stale.-2. **`.github/CODEOWNERS` + [`CODEOWNERS-soft`](../../../.github/CODEOWNERS-soft): backup for paths outside `products/`.** [`CODEOWNERS`](../../../.github/CODEOWNERS) is hard/blocking (mostly infra); `CODEOWNERS-soft` carries most product mappings for shared code (backend, frontend scenes, generated artifacts, overrides).+## Fast path: `hogli owners:*`-## Fast path: `ownership.js`--[`ownership.js`](ownership.js) automates the deterministic repo-file resolution for both lookups. It finds the repo root from its own location (cwd- and worktree-independent) and enumerates tracked files via `git ls-files`. Run it first, then fall back to the manual reasoning below for what it can't resolve.+Dev machines have flox/hogli, so shell straight to the resolver.```bash-S=.agents/skills/establishing-code-ownership/ownership.js-node $S file posthog/hogql/printer.py # who owns this file (pass --all to see every matching CODEOWNERS rule)-node $S team team-surveys # every tracked file the team owns (slug or @PostHog/ handle both work)-node $S unowned # every tracked file with no owner (append path prefixes to scope, e.g. `unowned products/ frontend/`)+hogli owners:who posthog/hogql/printer.py # who owns this path (+ the file that decided it)+hogli owners:resolve --json posthog/api/survey.py products/surveys/backend/api.py # batch, JSON keyed by path+hogli owners:unowned # every tracked file with no owner (append a prefix to scope: `owners:unowned products/`)```-For glob matching it uses the vendored, GitHub-faithful matcher [`.github/scripts/codeowners.js`](../../../.github/scripts/codeowners.js) (a zero-dependency JS port of [hmarr/codeowners](https://github.com/hmarr/codeowners)), the same matcher the reviewer auto-assigner runs in CI, so answers track what CI assigns rather than a separate reimplementation. That matcher reproduces GitHub's own CODEOWNERS rules: a slash-free pattern matches at any depth, a trailing slash matches a directory and its contents, and `dir/*` matches only direct children. So a `CODEOWNERS-soft` entry the script shows as unowned is genuinely dead — both CI and GitHub skip it too, not a quirk of a stricter local matcher.--Precedence: `product.yaml` for `products/<name>/**`; else a blocking `CODEOWNERS` owner; else the last-matching `CODEOWNERS-soft` rule. A blocking `CODEOWNERS` glob with **no owner** (a reset, e.g. `posthog/hogql/database/schema/**`) only clears the blocking owner, it does not erase a soft mapping. `file` prints the source line behind each answer.--It does **not** trace generated files to their source's owner, consult the handbook, or search Slack. When it returns no owner (or the path is a generated file), keep going with the steps below.--## path → team (who owns this file?)+`owners:who` prints the resolved `owners`, the `status`, the derived Slack channel, and `source` — the `owners.yaml`/`product.yaml` file that decided the answer.+`owners:resolve` takes paths as arguments or newline-delimited on stdin, so you can pipe a file list: `git ls-files posthog/hogql | hogli owners:resolve --json`.+No hogli/flox available? The dependency-light fallback needs only pyyaml: `git ls-files posthog/hogql | PYTHONPATH=tools/owners python -m posthog_owners` (stdin paths → the same JSON).-1. **Under `products/<name>/`?** Read that `product.yaml` `owners:`; prefix each slug with `@PostHog/` (`team-replay` → `@PostHog/team-replay`). This beats any matching CODEOWNERS entry. No CODEOWNERS entry for a product path is fine, not a gap.-2. **Else grep the CODEOWNERS files** (`CODEOWNERS-soft` first, then `CODEOWNERS`). Precedence is **last-match-wins**, so take the latest/most-specific matching glob, not the first hit.-3. **No match?** It's covered by a broader parent glob, or unresolved; fall back to the handbook (below). State which source the answer came from.+## Resolution algorithm (what the resolver does)-**Generated files** often have no CODEOWNERS entry; trace to the input they're generated from and use that owner (e.g. `services/mcp/src/tools/generated/<x>.ts` comes from `products/<name>/mcp/tools.yaml`). Distinguish:+For a path, it walks from the repo root down to the path collecting ownership files, then merges them **nearest-file-wins**:-- **Logical owner**: the team owning the _source_, the answer to report.-- **Literal GitHub auto-assignment**: who CODEOWNERS requests on that exact path; for an unpinned generated file, a broad parent rule or nobody.+1. **`owners.yaml` — the canonical, distributed source.** Each directory can carry one. Fields (`owners`, `status`, `inherit`, per-path `rules`) fall through to the nearest ancestor unless overridden. `inherit: false` cuts the walk (Gerrit's `set noparent`) — nothing above it contributes. Within a file, `rules:` are last-match-wins. `owners: null` means **unowned by design** (exempt from the coverage check), distinct from a directory with no file at all (genuinely unowned).+2. **`products/<name>/product.yaml` — an accepted alias.** When a product dir has no `owners.yaml`, its `product.yaml` `owners:` list is read as the ownership for `products/<name>/**` (every other `product.yaml` field is ignored). A dir with both files is a lint error; `owners.yaml` wins.+3. **`.github/CODEOWNERS` — blocking approvals, never part of the walk.** It keeps GitHub-native semantics, stays hand-maintained (mostly infra, e.g. `team-security`), and is enforced by GitHub itself. The resolver does **not** read it — when you need to know whether a blocking approval is additionally required, consult the file directly. It never changes the resolved `owners`, and nothing here writes to it.-When they differ, report the logical owner and flag the gap so the operator can decide whether to pin it in `CODEOWNERS-soft`.+Owners are a mixed list of **team slugs** (`team-devex`, `conversations`, `logs` — the GitHub team handle minus `@PostHog/`) and **`@handles`** for individuals; the first entry is the primary owner.## team → code (what does this team own?)-Check both sources or you'll miss code:+There's no single "team → files" command; resolve the tree and filter by slug:-1. **Grep every `products/*/product.yaml` for the slug**; each hit is all of that `products/<name>/**`. One team often owns several, so don't stop at the first.-2. **Grep `CODEOWNERS-soft` (and `CODEOWNERS`) for the handle** (`@PostHog/team-surveys`, …) for everything outside `products/`.--**Owned paths span backend AND `frontend/src/...`.** Cover both, or say up front you're doing one side.+```bash+git ls-files | hogli owners:resolve --json | jq -r 'to_entries[] | select(.value.owners | index("team-surveys")) | .key'+```-**Verify CODEOWNERS-soft paths on disk.** They drift (a moved product leaves old paths behind); `product.yaml` doesn't. For any missing path, the code likely relocated into a `products/<name>/` the team already owns; flag the stale entry to the operator rather than silently substituting.+Also grep `products/*/product.yaml` for the slug — each hit is all of that `products/<name>/**`; one team often owns several, so don't stop at the first.+Owned paths span backend **and** `frontend/src/...`; cover both, or say up front you're doing one side.-## Last resort: feature-ownership handbook+## Generated files-If neither `product.yaml` nor CODEOWNERS resolves it, consult the [feature-ownership handbook](https://posthog.com/handbook/engineering/feature-ownership) (teams to product areas). It's a genuine last resort: coarse-grained (broad areas, not files) and hand-maintained (lags repo moves and reorgs). Prefer the repo files, and flag any handbook-sourced answer as possibly stale.+A generated artifact often resolves to a broad parent owner or nobody.+Trace it to the input it's generated from and report **that** team as the logical owner (e.g. `services/mcp/src/tools/generated/<x>.ts` comes from `products/<name>/mcp/tools.yaml`).+Distinguish the logical owner (the team owning the source — the answer to report) from the literal resolver result on the generated path, and flag the gap so the operator can decide whether to pin it with a `rules:` entry.-## Even-last-er resort: ask Slack+## Last resort: feature-ownership handbook, then Slack-If even the handbook fails and the Slack MCP is available, search Slack. It's the least authoritative source (opinions, stale threads), so verify against the repo files and flag the answer as Slack-sourced.+If neither the resolver nor `product.yaml` resolves it, consult the [feature-ownership handbook](https://posthog.com/handbook/engineering/feature-ownership) — coarse-grained (broad areas, not files) and hand-maintained, so prefer the repo files and flag any handbook-sourced answer as possibly stale.+If even that fails and the Slack MCP is available, search Slack — least authoritative (opinions, stale threads), so verify against the repo files and flag the answer as Slack-sourced.## Slug vs handle-- **Handle** (CODEOWNERS): `@PostHog/<slug>`, e.g. `@PostHog/team-replay`.-- **Slug** (`product.yaml`): handle minus `@PostHog/`, e.g. `team-replay`.+- **Handle** (`CODEOWNERS`): `@PostHog/<slug>`, e.g. `@PostHog/team-replay`.+- **Slug** (`owners.yaml` / `product.yaml`): handle minus `@PostHog/`, e.g. `team-replay`.- **Not uniform**: some carry `team-` (`team-self-driving`), some don't (`conversations`, `logs`). If a name doesn't resolve, try both forms.diff --git a/.agents/skills/establishing-code-ownership/ownership.js b/.agents/skills/establishing-code-ownership/ownership.jsdeleted file mode 100755index 4a81be8bba6f..000000000000--- a/.agents/skills/establishing-code-ownership/ownership.js+++ /dev/null@@ -1,280 +0,0 @@-#!/usr/bin/env node--// Resolve PostHog code ownership from products/*/product.yaml + CODEOWNERS.-//-// Resolution order (mirrors the establishing-code-ownership skill):-// 1. A file under products/<name>/ is owned by that product.yaml's `owners:`-// (beats any CODEOWNERS entry). Products without a product.yaml fall through.-// 2. Otherwise the CODEOWNERS files decide. Within each file the last matching-// glob wins. Across the two files a blocking CODEOWNERS owner wins when-// present, else the CODEOWNERS-soft owner applies. A blocking glob with no-// owner (a reset, used so product teams can edit infra-owned trees) clears-// only the blocking owner; it does not erase a soft mapping.-// 3. No owner from either file means unowned.-//-// Glob matching is NOT reimplemented here: it uses the vendored, GitHub-faithful-// matcher in .github/scripts/codeowners.js (a JS port of hmarr/codeowners), the-// same matcher PostHog's reviewer auto-assigner runs in CI, so answers stay in-// lockstep with what CI assigns. It reproduces GitHub's own CODEOWNERS rules (a-// slash-free pattern matches at any depth, a trailing slash matches a directory-// and its contents, `dir/*` matches only direct children), so a dead entry here-// is dead for GitHub too — not a quirk of a stricter local matcher.-//-// Usage:-// ownership.js file <path>... [--all] who owns these files-// ownership.js team <slug-or-handle> [prefix...] every tracked file a team owns-// ownership.js unowned [prefix...] every tracked file with no owner-//-// Data goes to stdout; counts and notes go to stderr (so you can pipe stdout).--const fs = require('fs')-const path = require('path')-const { execFileSync } = require('child_process')--function findRepoRoot(start) {- let dir = start- for (;;) {- if (fs.existsSync(path.join(dir, '.github', 'CODEOWNERS'))) {- return dir- }- const parent = path.dirname(dir)- if (parent === dir) {- throw new Error('could not locate repo root (no .github/CODEOWNERS found above this script)')- }- dir = parent- }-}--const REPO_ROOT = findRepoRoot(__dirname)-const { CodeOwners, pathMatchesPattern } = require(path.join(REPO_ROOT, '.github', 'scripts', 'codeowners.js'))--// Bare product.yaml slug -> @PostHog/<slug>; an explicit @handle is left as-is.-function toHandle(owner) {- return owner.startsWith('@') ? owner : `@PostHog/${owner}`-}--// @PostHog/team-x or @team-x or team-x -> team-x (for comparison).-function toSlug(owner) {- if (owner.startsWith('@PostHog/')) {return owner.slice('@PostHog/'.length)}- if (owner.startsWith('@')) {return owner.slice(1)}- return owner-}--function parseCodeowners(file, label) {- if (!fs.existsSync(file)) {return []}- const rules = []- fs.readFileSync(file, 'utf8')- .split('\n')- .forEach((raw, idx) => {- const line = raw.trim()- if (!line || line.startsWith('#')) {return}- const tokens = line.split(/\s+/)- rules.push({- pattern: tokens[0],- owners: tokens.slice(1),- source: label,- lineno: idx + 1,- })- })- return rules-}--// Pull the `owners:` value out of a product.yaml without a YAML dependency.-// Handles all three forms: block list, inline list, and a bare scalar.-function parseProductOwners(content) {- const owners = []- let inOwners = false- for (const raw of content.split('\n')) {- const line = raw.replace(/\s+#.*$/, '').trimEnd()- if (!line.trim() || /^\s*#/.test(raw)) {continue}- const ownersMatch = line.match(/^owners\s*:\s*(.*)$/)- if (ownersMatch) {- const rest = ownersMatch[1].trim()- if (rest.startsWith('[')) {- const close = rest.lastIndexOf(']')- const inner = rest.slice(1, close === -1 ? rest.length : close)- for (const item of inner.split(',')) {- const value = item.trim().replace(/^["']|["']$/g, '')- if (value) {owners.push(value)}- }- } else if (rest) {- owners.push(rest.replace(/^["']|["']$/g, ''))- } else {- inOwners = true // block list follows on the next lines- }- continue- }- if (!inOwners) {continue}- const m = line.match(/^\s+-\s+(.+?)$/)- if (m) {- owners.push(m[1].replace(/^["']|["']$/g, '').trim())- continue- }- if (/^\S/.test(raw)) {inOwners = false}- }- return owners-}--function loadProductOwners(root) {- const map = new Map()- const productsDir = path.join(root, 'products')- if (!fs.existsSync(productsDir)) {return map}- for (const entry of fs.readdirSync(productsDir, { withFileTypes: true })) {- if (!entry.isDirectory()) {continue}- const yaml = path.join(productsDir, entry.name, 'product.yaml')- if (!fs.existsSync(yaml)) {continue}- const owners = parseProductOwners(fs.readFileSync(yaml, 'utf8'))- .filter((slug) => slug && slug !== 'team-CHANGEME') // a bootstrap placeholder, not a real team- .map(toHandle)- if (owners.length) {map.set(entry.name, owners)}- }- return map-}--function src(rule) {- return `${rule.source}:${rule.lineno} (${rule.pattern})`-}--class Resolver {- constructor(root) {- this.root = root- this.productOwners = loadProductOwners(root)- this.softRules = parseCodeowners(path.join(root, '.github', 'CODEOWNERS-soft'), 'CODEOWNERS-soft')- this.hardRules = parseCodeowners(path.join(root, '.github', 'CODEOWNERS'), 'CODEOWNERS')- this.rules = this.softRules.concat(this.hardRules)- // CodeOwners precompiles a matcher per rule, so the full-repo passes- // (team/unowned) test thousands of files without recompiling. matchingRule- // returns the same rich rule objects parsed above (with source + lineno).- this.softMatcher = new CodeOwners(this.softRules)- this.hardMatcher = new CodeOwners(this.hardRules)- }-- resolve(file) {- if (file.startsWith('products/')) {- const name = file.split('/')[1]- if (name && this.productOwners.has(name)) {- return { owners: this.productOwners.get(name), source: `products/${name}/product.yaml`, reset: false }- }- }- const hard = this.hardMatcher.matchingRule(file)- if (hard && hard.owners.length) {return { owners: hard.owners, source: src(hard), reset: false }}- const soft = this.softMatcher.matchingRule(file)- if (soft && soft.owners.length) {return { owners: soft.owners, source: src(soft), reset: false }}- const reset = hard || soft- if (reset) {return { owners: [], source: src(reset), reset: true }}- return { owners: [], source: null, reset: false }- }-- allMatches(file) {- // Degrade on a malformed pattern (e.g. a `***` typo) instead of throwing,- // matching how resolve() handles rules via the safe CodeOwners matchers.- return this.rules.filter((rule) => {- try {- return pathMatchesPattern(rule.pattern, file)- } catch {- return false- }- })- }-}--function listTrackedFiles(root, prefixes) {- const args = ['ls-files', '-z']- if (prefixes.length) {args.push('--', ...prefixes)}- const out = execFileSync('git', args, { cwd: root, maxBuffer: 1024 * 1024 * 512 }).toString('utf8')- return out.split('\0').filter(Boolean)-}--// Turn a user-supplied path into a normalized repo-relative one. Prefers the-// repo-relative reading (the documented contract) so the answer doesn't depend-// on cwd; only falls back to cwd-relative when that is clearly what was meant.-// A return value starting with "../" means the input points outside the repo.-function normalizeInputPath(root, raw) {- const repoRel = path.posix.normalize(raw.split(path.sep).join('/').replace(/^\/+/, ''))- if (!path.isAbsolute(raw)) {- const underRoot = fs.existsSync(path.join(root, repoRel))- const underCwd = fs.existsSync(path.join(process.cwd(), raw))- if (underRoot || !underCwd) {return repoRel}- }- const abs = path.isAbsolute(raw) ? raw : path.resolve(process.cwd(), raw)- return path.relative(root, abs).split(path.sep).join('/')-}--function cmdFile(resolver, paths, showAll) {- for (const raw of paths) {- const rel = normalizeInputPath(resolver.root, raw)- if (rel.startsWith('../') || path.isAbsolute(rel)) {- console.error(`warning: ${raw} is outside the repo root; ownership only covers tracked repo files`)- }- const res = resolver.resolve(rel)- console.info(rel)- if (res.owners.length) {- console.info(` owners: ${res.owners.join(', ')}`)- console.info(` source: ${res.source}`)- } else if (res.reset) {- console.info(' owners: none (ownership explicitly cleared)')- console.info(` source: ${res.source}`)- } else {- console.info(' owners: none (no product.yaml or CODEOWNERS match)')- }- if (showAll) {- const matches = resolver.allMatches(rel)- if (matches.length) {- console.info(' all CODEOWNERS matches (last wins):')- for (const rule of matches) {- const owners = rule.owners.length ? rule.owners.join(', ') : '(reset)'- console.info(` ${rule.source}:${rule.lineno} ${rule.pattern} -> ${owners}`)- }- }- }- }-}--function cmdTeam(resolver, team, prefixes) {- const target = toSlug(team).toLowerCase()- const files = listTrackedFiles(resolver.root, prefixes)- const owned = files.filter((f) => resolver.resolve(f).owners.some((o) => toSlug(o).toLowerCase() === target))- for (const f of owned) {console.info(f)}- console.error(`${owned.length} file(s) owned by ${team}`)-}--function cmdUnowned(resolver, prefixes) {- const files = listTrackedFiles(resolver.root, prefixes)- const unowned = files.filter((f) => resolver.resolve(f).owners.length === 0)- for (const f of unowned) {console.info(f)}- console.error(`${unowned.length} unowned of ${files.length} tracked file(s)`)-}--function usage(message) {- if (message) {console.error(`error: ${message}`)}- console.error('usage:')- console.error(' ownership.js file <path>... [--all] who owns these files')- console.error(' ownership.js team <slug-or-handle> [prefix...] every tracked file a team owns')- console.error(' ownership.js unowned [prefix...] every tracked file with no owner')- process.exit(message ? 2 : 0)-}--function main(argv) {- const [command, ...rest] = argv- if (!command || command === '-h' || command === '--help') {usage()}- const resolver = new Resolver(REPO_ROOT)- if (command === 'file') {- const paths = rest.filter((a) => a !== '--all')- if (!paths.length) {usage('file needs at least one path')}- cmdFile(resolver, paths, rest.includes('--all'))- } else if (command === 'team') {- if (!rest.length) {usage('team needs a slug or handle')}- cmdTeam(resolver, rest[0], rest.slice(1))- } else if (command === 'unowned') {- cmdUnowned(resolver, rest)- } else {- usage(`unknown command: ${command}`)- }-}--try {- main(process.argv.slice(2))-} catch (err) {- console.error(`error: ${err.message}`)- process.exit(1)-}diff --git a/.agents/skills/owners.yaml b/.agents/skills/owners.yamlnew file mode 100644index 000000000000..ca30252af6dc--- /dev/null+++ b/.agents/skills/owners.yaml@@ -0,0 +1,5 @@+version: 1+owners: []+rules:+ - match: '/ingestion-*/'+ owners: team-ingestiondiff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 82f9775219d6..241072b0a4ee 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -360,6 +360,9 @@ jobs:- 'products/tasks/backend/temporal/**/*'product_yamls:- 'products/*/product.yaml'+ - '**/owners.yaml'+ # Resolver changes must re-run the owners.yaml lint too.+ - 'tools/owners/**'openapi_types:# Generated OpenAPI types - validate they match schema- 'frontend/src/generated/**/*'@@ -821,7 +824,8 @@ jobs:# Consolidates checks that previously each spun up their own runner.repo-checks:needs: [changes]- if: needs.changes.outputs.backend == 'true' && github.event_name != 'push'+ # product_yamls: ownership-only PRs still need the owners.yaml lint below.+ if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.product_yamls == 'true') && github.event_name != 'push'timeout-minutes: 10permissions:contents: read@@ -844,6 +848,12 @@ jobs:run: ./bin/hogli product:bootstrap spline_reticulator --non-interactive- name: Lint product structurerun: ./bin/hogli product:lint --all+ # Distributed owners.yaml tree: schema, product.yaml/owners.yaml+ # conflicts, dead rule globs, coverage (warn-only). No --live, so no+ # secrets — fork PRs get validated too (the --live slug check runs in+ # the fork-gated validate-product-yamls job instead).+ - name: Lint owners.yaml files+ run: ./bin/hogli owners:lint- name: Check version specifiersrun: python .github/scripts/check-version-specifiers.py- name: Check IDOR model coverage@@ -909,6 +919,10 @@ jobs:exit 0fi./bin/hogli product:lint:owners "${existing[@]}"+ - name: Validate owners.yaml identities against GitHub+ env:+ GH_TOKEN: ${{ steps.app-token.outputs.token }}+ run: ./bin/hogli owners:lint --live# Migration validation and OpenAPI type generation.# This job needs Docker + DB — it checks out master first to run baselinediff --git a/.dockerignore b/.dockerignoreindex 522b437da6a8..904a63fe1be8 100644--- a/.dockerignore+++ b/.dockerignore@@ -85,6 +85,7 @@ services/agent-tests!tailwind.config.js!tools/hogli!tools/openapi-codegen+!tools/owners!tsconfig.json!unit.json.tplcommon/*/*/node_modulesdiff --git a/.gitattributes b/.gitattributesindex 3e12e0ddaad7..fe075f24f4f6 100644--- a/.gitattributes+++ b/.gitattributes@@ -5,9 +5,6 @@CONTRIBUTING.md export-ignoreCODE_OF_CONDUCT.md export-ignore-# Format the soft CODEOWNERS file with CODEOWNERS syntax highlighting on GitHub.-.github/CODEOWNERS-soft linguist-language=CODEOWNERS-# Generated code: exclude from GitHub Linguist stats and suppress diffs.frontend/src/generated/** linguist-generatedfrontend/src/lib/posthog-typed.ts linguist-generateddiff --git a/.github/CODEOWNERS b/.github/CODEOWNERSindex 417995e27494..a93f1d4902a3 100644--- a/.github/CODEOWNERS+++ b/.github/CODEOWNERS@@ -33,9 +33,17 @@ posthog/hogql/database/test/__snapshots__/test_database.ambr.github/scripts/assign-reviewers.js @PostHog/team-security# The vendored CODEOWNERS matcher the auto-assigner (and the ownership skill) depend on..github/scripts/codeowners.js @PostHog/team-security+# The distributed-ownership resolver the auto-assigner executes on that same+# pull_request_target event (via `python -m posthog_owners`), with tools/owners+# as the privileged sys.path root. Anything importable placed in that tree can+# shadow stdlib/pyyaml for the privileged process — top-level modules (yaml.py),+# shadow packages (yaml/__init__.py), and extension modules (yaml.so, *.pyd)+# alike — so the whole directory is gated rather than enumerating suffixes.+tools/owners/** @PostHog/team-security# And of course modifying this file can bring us problems so let's have the security team own it.-# This does not affect CODEOWNERS-soft which is used for assigning non-required reviewers and it's much safer to change.+# This does not affect the distributed owners.yaml files, which drive non-required reviewer+# assignment and are much safer to change.CODEOWNERS @PostHog/team-security# PR approval agent — can auto-approve PRs, so changes need reviewdiff --git a/.github/CODEOWNERS-soft b/.github/CODEOWNERS-softdeleted file mode 100644index 1f5897d8099c..000000000000--- a/.github/CODEOWNERS-soft+++ /dev/null@@ -1,390 +0,0 @@-# If a file is set here, then PRs will tag for the team's approval but will not block PRs.-#-# For top-level product ownership (`products/<name>/**`), prefer setting `owners`-# in `products/<name>/product.yaml` — the auto-assigner reads those files and-# applies them as soft codeowners. This file is for sub-folder overrides,-# secondary reviewers, and ownership of paths outside `products/`.--# Surveys - owned by @PostHog/team-surveys-frontend/src/scenes/settings/environment/SurveySettings.tsx @PostHog/team-surveys-frontend/src/scenes/surveys/ @PostHog/team-surveys-ee/surveys/ @PostHog/team-surveys-posthog/tasks/stop_surveys_reached_target.py @PostHog/team-surveys-posthog/tasks/update_survey_adaptive_sampling.py @PostHog/team-surveys-posthog/tasks/update_survey_iteration.py @PostHog/team-surveys-posthog/tasks/test/test_stop_surveys_reached_target.py @PostHog/team-surveys-posthog/tasks/test/test_update_survey_adaptive_sampling.py @PostHog/team-surveys-posthog/tasks/test/test_update_survey_iteration.py @PostHog/team-surveys-posthog/templates/surveys @PostHog/team-surveys--# Product Tours - owned by @PostHog/team-surveys-products/product_tours/** @PostHog/team-surveys-frontend/src/toolbar/product-tours/** @PostHog/team-surveys--# Nodejs Services - ownership is split between ingestion and workflows teams-nodejs/tests/ @PostHog/team-ingestion-nodejs/src/ingestion/ @PostHog/team-ingestion-nodejs/src/ingestion/pipelines/sessionreplay/ @PostHog/team-replay @PostHog/team-ingestion-# Rust session-replay anonymizer (native counterpart of the sessionreplay anonymize pipeline)-rust/replay-anonymizer-node/** @PostHog/team-ai-research-nodejs/src/cdp/ @PostHog/team-workflows-nodejs/src/session-replay/recording-rasterizer/ @PostHog/team-replay--# CDP / Workflows - owned by @PostHog/team-workflows-posthog/cdp/** @PostHog/team-workflows-posthog/models/messaging.py @PostHog/team-workflows-posthog/temporal/messaging/ @PostHog/team-workflows-frontend/src/scenes/data-pipelines/ @PostHog/team-workflows-frontend/src/scenes/hog-functions/ @PostHog/team-workflows--# Platform email infrastructure - owned by @PostHog/team-platform-features-# The shared SMTP/HTTP send path, email settings, and platform-level emails (e.g. daily/weekly-# project digests). Product-specific emails keep their own owners via more specific entries-# (workflows messaging above; weekly digest temporal workflow and AI observability templates below).-posthog/email.py @PostHog/team-platform-features-posthog/settings/email.py @PostHog/team-platform-features-posthog/tasks/email.py @PostHog/team-platform-features-posthog/tasks/email_utils.py @PostHog/team-platform-features-posthog/helpers/email_utils.py @PostHog/team-platform-features--# Web Analytics - owned by @PostHog/team-web-analytics-frontend/src/scenes/web-analytics/** @PostHog/team-web-analytics-posthog/models/web_preaggregated/** @PostHog/team-web-analytics-posthog/models/channel_type/** @PostHog/team-web-analytics-frontend/src/toolbar/web-vitals/** @PostHog/team-web-analytics-rust/common/cookieless/** @PostHog/team-web-analytics-nodejs/src/ingestion/cookieless/** @PostHog/team-web-analytics-frontend/src/scenes/marketing-analytics/ @PostHog/team-web-analytics--# Heatmaps - owned by @PostHog/team-web-analytics-frontend/src/scenes/heatmaps/** @PostHog/team-web-analytics-frontend/src/lib/components/heatmaps/** @PostHog/team-web-analytics-frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts @PostHog/team-web-analytics-posthog/heatmaps/** @PostHog/team-web-analytics-posthog/hogql/database/schema/heatmaps.py @PostHog/team-web-analytics-nodejs/src/ingestion/heatmaps/ @PostHog/team-web-analytics--# Analytics Platform - owned by @PostHog/team-analytics-platform-posthog/dags/locations/analytics*platform.py @PostHog/team-analytics-platform-ee/tasks/subscriptions/** @PostHog/team-analytics-platform-frontend/src/scenes/data-management/schema/** @PostHog/team-analytics-platform-frontend/src/scenes/dashboard/ @PostHog/team-analytics-platform-posthog/api/schema_property_group.py @PostHog/team-analytics-platform-posthog/hogql_queries/sessions_query_runner.py @PostHog/team-analytics-platform-posthog/hogql_queries/sessions_timeline_query_runner.py @PostHog/team-analytics-platform-posthog/dags/sessions.py @PostHog/team-analytics-platform-ee/clickhouse/materialized_columns/** @PostHog/team-analytics-platform-posthog/tasks/alerts/** @PostHog/team-analytics-platform-posthog/temporal/alerts/ @PostHog/team-analytics-platform-posthog/temporal/exports/ @PostHog/team-analytics-platform-frontend/src/scenes/alerts/ @PostHog/team-analytics-platform-frontend/src/scenes/health-alerts/ @PostHog/team-analytics-platform-frontend/src/scenes/exports/ @PostHog/team-analytics-platform-frontend/src/scenes/subscriptions/ @PostHog/team-analytics-platform-frontend/src/scenes/sessions/ @PostHog/team-analytics-platform--# Revenue Analytics - owned by @rafaeelaudibert and @PostHog/team-web-analytics-products/revenue_analytics/** @rafaeelaudibert @PostHog/team-web-analytics--# Feature Flags (Rust evaluator + remaining monolith tests) - owned by @PostHog/team-feature-flags-# Note: the Django models and API moved to products/feature_flags/ (covered by products/feature_flags/product.yaml).-rust/feature-flags/ @PostHog/team-feature-flags-rust/flags-consumer/ @PostHog/team-feature-flags-rust/flags_read_store_migrations/ @PostHog/team-feature-flags-posthog/test/test_feature_flag_analytics.py @PostHog/team-feature-flags--# Cohorts - owned by @PostHog/team-feature-flags-posthog/api/cohort.py @PostHog/team-feature-flags-posthog/models/cohortmembership/ @PostHog/team-feature-flags-frontend/src/scenes/cohorts/ @PostHog/team-feature-flags-posthog/tasks/calculate_cohort.py @PostHog/team-feature-flags-posthog/hogql_queries/hogql_cohort_query.py @PostHog/team-feature-flags--# Auto-label scope mappings - owned by @PostHog/team-feature-flags so mappings-# can change without editing the Auto Assign Labels workflow or its script-.github/auto-assign-labels.json @PostHog/team-feature-flags--# Feature Flags frontend - owned by @PostHog/team-feature-flags-frontend/src/scenes/feature-flags/ @PostHog/team-feature-flags-frontend/src/scenes/FeatureFlagPermissions.tsx @PostHog/team-feature-flags-posthog/tasks/early_access_feature.py @PostHog/team-feature-flags--# Data warehouse - owned by @PostHog/team-data-stack-products/warehouse_sources/backend/temporal/data_imports/** @PostHog/team-warehouse-sources-posthog/warehouse/** @PostHog/team-data-stack-products/data_warehouse/** @PostHog/team-data-stack-frontend/src/scenes/data-warehouse/** @PostHog/team-data-stack-posthog/management/commands/generate_source_configs.py @PostHog/team-warehouse-sources-frontend/src/scenes/data-management/ @PostHog/team-warehouse-sources-posthog/settings/data_warehouse.py @PostHog/team-data-stack-frontend/src/scenes/models/** @PostHog/team-data-modeling-posthog/temporal/data_modeling/** @PostHog/team-data-modeling--# HogQL - owned by @PostHog/team-data-tools-# and also hard owned by the @PostHog/hogql on `CODEOWNERS` file-posthog/hogql/** @PostHog/team-data-tools-posthog/hogql_queries/hogql_query_runner.py @PostHog/team-data-tools-rust/hogql/ @PostHog/team-data-tools--# Tracing/Metrics — owned by @PostHog/logs (logs itself comes from products/logs/product.yaml)-products/tracing/** @PostHog/logs-products/metrics/** @PostHog/logs-posthog/temporal/logs_alerting/ @PostHog/logs--# Error Tracking - owned by @PostHog/team-error-tracking-products/error_tracking/backend/** @PostHog/team-error-tracking-products/error_tracking/frontend/** @PostHog/team-error-tracking-products/error_tracking/mcp/** @PostHog/team-error-tracking-products/error_tracking/skills/** @PostHog/team-error-tracking-cli/** @PostHog/team-error-tracking-rust/cymbal/** @PostHog/team-error-tracking-rust/cymbal-resolution/** @PostHog/team-error-tracking-rust/cymbal-proto/** @PostHog/team-error-tracking-rust/common/symbol_data/** @PostHog/team-error-tracking--# Notebooks - owned by @PostHog/team-data-tools-frontend/src/scenes/notebooks/ @PostHog/team-data-tools-frontend/src/lib/components/RichContentEditor/ @PostHog/team-data-tools--# Comments - owned by @PostHog/team-platform-features-frontend/src/scenes/comments/ @PostHog/team-platform-features-posthog/api/comments.py @PostHog/team-platform-features-posthog/models/comment/ @PostHog/team-platform-features--# Authentication, audit logs, activity, approvals, access control - owned by @PostHog/team-platform-features-# Note: backend authentication stays hard-owned by @PostHog/team-security on CODEOWNERS.-frontend/src/scenes/authentication/ @PostHog/team-platform-features-frontend/src/scenes/audit-logs/ @PostHog/team-platform-features-frontend/src/scenes/activity/ @PostHog/team-platform-features-posthog/models/activity_logging/ @PostHog/team-platform-features-frontend/src/scenes/approvals/ @PostHog/team-platform-features-frontend/src/scenes/resource-transfer/ @PostHog/team-platform-features-posthog/api/resource_transfer.py @PostHog/team-platform-features-posthog/models/resource_transfer/ @PostHog/team-platform-features-posthog/rbac/ @PostHog/team-platform-features--# Session Replay python files - owned by @PostHog/team-replay-posthog/session_recordings/**/*.py @PostHog/team-replay-ee/session_recordings/ @PostHog/team-replay--# Session Replay frontend - owned by @PostHog/team-replay-frontend/src/scenes/session-recordings/ @PostHog/team-replay-posthog/temporal/session_replay/ @PostHog/team-replay--# Product onboarding - owned by @PostHog/team-growth-frontend/src/scenes/onboarding/ @PostHog/team-growth-frontend/src/scenes/startups/ @PostHog/team-growth-frontend/src/scenes/wizard/ @PostHog/team-growth-frontend/src/scenes/welcome/ @PostHog/team-growth-frontend/src/scenes/oauth/ @PostHog/team-growth-frontend/src/scenes/agentic/ @PostHog/team-growth-frontend/src/scenes/project-homepage/ @PostHog/team-growth-frontend/src/scenes/health/ @PostHog/team-growth--# Per-product onboarding SDK docs override the general onboarding owner above-# (last-match-wins, so these must come after the onboarding rule to take effect).-frontend/src/scenes/onboarding/sdks/surveys/ @PostHog/team-surveys--# Settings & project administration - owned by @PostHog/team-growth-frontend/src/scenes/settings/ @PostHog/team-growth-frontend/src/scenes/organization/ @PostHog/team-growth-frontend/src/scenes/project/ @PostHog/team-growth-# instance/ admin scenes are team-growth's, except QueryPerformance (team-experiments).-# The assign-reviewers script unions the owners of every matching rule — it does NOT-# apply last-match-wins — so growth must be scoped to its specific subfolders rather-# than the whole instance/ dir, or growth gets tagged on QueryPerformance PRs too.-frontend/src/scenes/instance/AsyncMigrations/ @PostHog/team-growth-frontend/src/scenes/instance/DeadLetterQueue/ @PostHog/team-growth-frontend/src/scenes/instance/SystemStatus/ @PostHog/team-growth-frontend/src/scenes/instance/QueryPerformance/ @PostHog/team-experiments--# Weekly digest - owned by @PostHog/team-growth-posthog/temporal/weekly_digest @PostHog/team-growth-posthog/temporal/tests/weekly_digest @PostHog/team-growth--# AI observability - owned by @PostHog/team-ai-observability-Dockerfile.llm-analytics @PostHog/team-ai-observability-docs/onboarding/ai-observability/** @PostHog/team-ai-observability-frontend/src/scenes/onboarding/sdks/ai-observability/ @PostHog/team-ai-observability-nodejs/src/ingestion/ai/ @PostHog/team-ai-observability-nodejs/src/ai-observability/ @PostHog/team-ai-observability-posthog/hogql/database/schema/ai_events.py @PostHog/team-ai-observability-posthog/hogql_queries/ai/ @PostHog/team-ai-observability-posthog/models/ai_events/ @PostHog/team-ai-observability-posthog/tasks/ai_observability_usage_report.py @PostHog/team-ai-observability-posthog/tasks/test/test_ai_observability_usage_report.py @PostHog/team-ai-observability-posthog/templates/email/ai_observability_*.html @PostHog/team-ai-observability-posthog/temporal/ai_observability/ @PostHog/team-ai-observability-products/ai_observability/** @PostHog/team-ai-observability-products/llm_analytics/backend/migrations/** @PostHog/team-ai-observability-services/mcp/src/generated/ai_observability/ @PostHog/team-ai-observability-services/mcp/src/tools/generated/ai_observability.ts @PostHog/team-ai-observability-services/mcp/src/tools/aiObservability/ @PostHog/team-ai-observability-services/mcp/src/ui-apps/apps/generated/llm-costs.tsx @PostHog/team-ai-observability--# Prompt management - shared between @PostHog/team-ai-observability and @PostHog/team-experiments-products/ai_observability/frontend/prompts/ @PostHog/team-ai-observability @PostHog/team-experiments-products/ai_observability/backend/models/llm_prompt.py @PostHog/team-ai-observability @PostHog/team-experiments-posthog/**/*llm_prompt*.py @PostHog/team-ai-observability @PostHog/team-experiments--# LLM Gateway - owned by @PostHog/team-ai-gateway-nodejs/src/ingestion/pipelines/ai/costs/ @PostHog/team-ai-observability @PostHog/team-ai-gateway-nodejs/src/ingestion/pipelines/ai/costs/scripts/ @PostHog/team-ai-gateway-nodejs/src/ingestion/pipelines/ai/costs/providers/ @PostHog/team-ai-gateway-products/ai_observability/backend/api/proxy.py @PostHog/team-ai-gateway-products/ai_observability/backend/api/test/test_proxy.py @PostHog/team-ai-gateway-products/ai_observability/frontend/playground/ @PostHog/team-ai-gateway-services/llm-gateway/ @PostHog/team-ai-gateway--# DevEx-adjacent files - owned by @PostHog/team-devex-.github/workflows/** @PostHog/team-devex-.github/workflows/ci-llm-gateway.yml @PostHog/team-devex @PostHog/team-ai-gateway-.github/workflows/llm-gateway-cd.yml @PostHog/team-devex @PostHog/team-ai-gateway-.github/workflows/update-ai-costs.yml @PostHog/team-devex @PostHog/team-ai-gateway-.github/workflows/cd-llm-analytics-image.yml @PostHog/team-devex @PostHog/team-ai-observability-.github/actions/** @PostHog/team-devex-.github/dependabot.yml @PostHog/team-devex-.github/pull_request_template.md @PostHog/team-devex-Dockerfile @PostHog/team-devex-docker-compose*.yml @PostHog/team-devex-.prettierrc @PostHog/team-devex-.test_quarantine.json @PostHog/team-devex-posthog/management/migration_analysis/ @PostHog/team-devex-tools/hogli/ @PostHog/team-devex-tools/hogli-commands/ @PostHog/team-devex-hogli.yaml @PostHog/team-devex-tach.toml @PostHog/team-devex-bin/ @PostHog/team-devex-bin/start-llm-gateway @PostHog/team-devex @PostHog/team-ai-gateway-CODEOWNERS-soft @PostHog/team-devex-CODEOWNERS @PostHog/team-devex-CLAUDE.md @PostHog/team-devex-AGENTS.md @PostHog/team-devex-.claude/ @PostHog/team-devex-.agents/* @PostHog/team-devex-.claude/agents/ingestion/ @PostHog/team-ingestion-.agents/skills/ingestion-*/ @PostHog/team-ingestion-.agents/skills/manage-dashboard-widgets/ @PostHog/team-analytics-platform-tools/pr-approval-agent/ @PostHog/team-devex-tools/phrocs/ @PostHog/team-devex-tools/query-performance-ai/ @PostHog/team-analytics-platform-greptile.json @PostHog/team-devex-docs/published/handbook/engineering/developing-locally.md @PostHog/team-devex--# Product Analytics - owned by @PostHog/team-product-analytics-frontend/src/scenes/insights/ @PostHog/team-product-analytics-frontend/src/scenes/trends/ @PostHog/team-product-analytics-frontend/src/scenes/funnels/ @PostHog/team-product-analytics-frontend/src/scenes/retention/ @PostHog/team-product-analytics-frontend/src/scenes/paths/ @PostHog/team-product-analytics-frontend/src/scenes/paths-v2/ @PostHog/team-product-analytics-frontend/src/scenes/saved-insights/ @PostHog/team-product-analytics-frontend/src/scenes/actions/ @PostHog/team-product-analytics-frontend/src/scenes/annotations/ @PostHog/team-product-analytics-frontend/src/scenes/groups/ @PostHog/team-product-analytics-frontend/src/scenes/persons/ @PostHog/team-product-analytics-frontend/src/scenes/persons-management/ @PostHog/team-product-analytics-posthog/api/event_definition.py @PostHog/team-product-analytics-posthog/api/event.py @PostHog/team-product-analytics-posthog/api/element.py @PostHog/team-product-analytics-posthog/api/person.py @PostHog/team-product-analytics-posthog/models/action/ @PostHog/team-product-analytics-posthog/hogql_queries/insights/ @PostHog/team-product-analytics-posthog/hogql_queries/groups/ @PostHog/team-product-analytics-posthog/hogql_queries/events_query_runner.py @PostHog/team-product-analytics-posthog/hogql_queries/actors_query_runner.py @PostHog/team-product-analytics-posthog/hogql_queries/property_values_query_runner.py @PostHog/team-product-analytics-ee/clickhouse/views/groups.py @PostHog/team-product-analytics-ee/clickhouse/queries/related_actors_query.py @PostHog/team-product-analytics-posthog/temporal/product_analytics/ @PostHog/team-product-analytics-frontend/src/scenes/themes/ @PostHog/team-product-analytics-posthog/taxonomy/ @PostHog/team-product-analytics--# MCP Analytics - owned by @PostHog/team-mcp-analytics-posthog/temporal/mcp_analytics/ @PostHog/team-mcp-analytics--# Experiments - owned by @PostHog/team-experiments-frontend/src/scenes/experiments/ @PostHog/team-experiments-posthog/temporal/experiments/ @PostHog/team-experiments-ee/clickhouse/queries/experiments/ @PostHog/team-experiments--# Data modeling - owned by @PostHog/team-data-modeling-frontend/src/scenes/data-model/ @PostHog/team-data-modeling-posthog/hogql_queries/endpoints/ @PostHog/team-data-modeling--# Signals / PostHog AI - owned by @PostHog/team-self-driving-frontend/src/scenes/max/ @PostHog/team-self-driving-frontend/src/scenes/inbox/ @PostHog/team-self-driving-ee/hogai/ @PostHog/team-self-driving-ee/support_sidebar_max/ @PostHog/team-self-driving-posthog/models/ai/** @PostHog/team-self-driving-posthog/hogql_queries/document_embeddings_query_runner.py @PostHog/team-self-driving--# Billing - owned by @PostHog/team-billing-frontend/src/scenes/billing/ @PostHog/team-billing-frontend/src/scenes/coupons/ @PostHog/team-billing-ee/billing/ @PostHog/team-billing-ee/api/billing.py @PostHog/team-billing-posthog/tasks/sync_billing.py @PostHog/team-billing-posthog/tasks/usage_report.py @PostHog/team-billing-posthog/temporal/usage_report/ @PostHog/team-billing-posthog/temporal/quota_limiting/ @PostHog/team-billing--# Query performance (merged into Analytics Platform) - owned by @PostHog/team-analytics-platform-posthog/queries/ @PostHog/team-analytics-platform-posthog/caching/ @PostHog/team-analytics-platform-posthog/hogql/database/schema/sessions*.py @PostHog/team-analytics-platform-posthog/models/raw_sessions/** @PostHog/team-analytics-platform-posthog/models/sessions/** @PostHog/team-analytics-platform--# Ingestion (persons identity pipeline) - owned by @PostHog/team-ingestion-posthog/temporal/delete_persons/ @PostHog/team-ingestion-posthog/temporal/sync_person_distinct_ids/ @PostHog/team-ingestion-posthog/tasks/split_person.py @PostHog/team-ingestion-posthog/models/person/** @PostHog/team-ingestion-posthog/dags/detach_distinct_id.py @PostHog/team-ingestion-posthog/dags/fix_missing_person_overrides.py @PostHog/team-ingestion-posthog/dags/fix_person_id_overrides.py @PostHog/team-ingestion-posthog/dags/person_property_reconciliation.py @PostHog/team-ingestion--# Ingestion (Rust capture + Kafka + property defs) - owned by @PostHog/team-ingestion-rust/capture/ @PostHog/team-ingestion-rust/ingestion-consumer/ @PostHog/team-ingestion-rust/kafka-deduplicator/ @PostHog/team-ingestion-rust/kafka-assigner/ @PostHog/team-ingestion-rust/kafka-assigner-proto/ @PostHog/team-ingestion-rust/property-defs-rs/ @PostHog/team-ingestion-rust/property-vals-rs/ @PostHog/team-ingestion--# Personhog (persons gRPC service) - owned by @PostHog/team-ingestion-rust/personhog-router/ @PostHog/team-ingestion-rust/personhog-replica/ @PostHog/team-ingestion-rust/personhog-leader/ @PostHog/team-ingestion-rust/personhog-writer/ @PostHog/team-ingestion-rust/personhog-coordination/ @PostHog/team-ingestion-rust/personhog-common/ @PostHog/team-ingestion-rust/personhog-proto/ @PostHog/team-ingestion-rust/behavioral_cohorts_migrations/ @PostHog/team-ingestion--# User interviews - owned by individuals (no team); product.yaml only auto-assigns team slugs-products/user_interviews/** @pauldambra @fivestarspicy @ksvat--# OpenAPI / drf-spectacular tooling - owned by @PostHog/team-devex-posthog/api/documentation.py @PostHog/team-devex-posthog/api/mixins.py @PostHog/team-devex-posthog/management/commands/find_enum_collisions.py @PostHog/team-devex--# Managed reverse proxy - owned by @PostHog/team-platform-features-# Placed last so these paths win over the broad frontend/src/scenes/settings/ rule (last-match-wins).-posthog/models/proxy_record.py @PostHog/team-platform-features-posthog/api/proxy_record.py @PostHog/team-platform-features-posthog/api/proxy_record_diagnostics.py @PostHog/team-platform-features-posthog/api/test/test_proxy_record.py @PostHog/team-platform-features-posthog/api/test/test_proxy_record_diagnostics.py @PostHog/team-platform-features-posthog/temporal/proxy_service/ @PostHog/team-platform-features-posthog/templates/email/proxy_provisioned.html @PostHog/team-platform-features-frontend/src/scenes/settings/environment/ManagedReverseProxy.tsx @PostHog/team-platform-features-frontend/src/scenes/settings/environment/ProxySDKSetup.tsx @PostHog/team-platform-features-frontend/src/scenes/settings/environment/proxyLogic.ts @PostHog/team-platform-features-frontend/src/scenes/settings/environment/proxyLogic.test.ts @PostHog/team-platform-features-frontend/src/lib/components/ReverseProxyChecker/ @PostHog/team-platform-featuresdiff --git a/.github/auto-assign-labels.json b/.github/auto-assign-labels.jsonindex 3dc065628e38..83df39925b73 100644--- a/.github/auto-assign-labels.json+++ b/.github/auto-assign-labels.json@@ -1,5 +1,5 @@{- "_comment": "Maps a PR's conventional-commit scope (the part in parens of `type(scope): summary`) to labels the Auto Assign Labels workflow applies. Owned by @PostHog/team-feature-flags via CODEOWNERS-soft, so mappings can change without editing the workflow or script. Scopes are matched case-insensitively. Labels must already exist in the repo. Add a new object to `rules` to map more scopes.",+ "_comment": "Maps a PR's conventional-commit scope (the part in parens of `type(scope): summary`) to labels the Auto Assign Labels workflow applies. Owned by @PostHog/team-feature-flags via owners.yaml, so mappings can change without editing the workflow or script. Scopes are matched case-insensitively. Labels must already exist in the repo. Add a new object to `rules` to map more scopes.","rules": [{"scopes": ["flags", "feature-flags"],diff --git a/.github/owners.yaml b/.github/owners.yamlnew file mode 100644index 000000000000..9c05b532a1bb--- /dev/null+++ b/.github/owners.yaml@@ -0,0 +1,16 @@+version: 1+owners: []+rules:+ - match: ['/CODEOWNERS', '/actions/']+ owners: team-devex+ - match: '/auto-assign-labels.json'+ owners: team-feature-flags+ - match: ['/dependabot.yml', '/pull_request_template.md', '/workflows/']+ owners: team-devex+ - match: '/workflows/cd-llm-analytics-image.yml'+ owners: [team-devex, team-ai-observability]+ - match:+ - '/workflows/ci-llm-gateway.yml'+ - '/workflows/llm-gateway-cd.yml'+ - '/workflows/update-ai-costs.yml'+ owners: [team-devex, team-ai-gateway]diff --git a/.github/scripts/assign-reviewers.js b/.github/scripts/assign-reviewers.jsindex 4badf43425c1..9962de088079 100644--- a/.github/scripts/assign-reviewers.js+++ b/.github/scripts/assign-reviewers.js@@ -1,7 +1,7 @@#!/usr/bin/env node-const fs = require('fs')-const { parse, pathMatchesPattern } = require('./codeowners')+const { spawnSync } = require('child_process')+const { pathMatchesPattern } = require('./codeowners')// Tunable knobs for how aggressively we trim the reviewer list. Kept in one// place so adjusting noise levels doesn't require re-reading the logic. All@@ -38,97 +38,52 @@ const CONFIG = {commentMarker: '<!-- auto-assign-reviewers -->',}-function parseCodeowners(codeownersPath) {- if (!fs.existsSync(codeownersPath)) {- throw new Error(`No CODEOWNERS file found at "${codeownersPath}"`)+// Ownership is resolved by the shared hogli resolver (distributed owners.yaml ++// product.yaml aliases), never re-parsed here — one semantics, many consumers.+// We shell out to its dependency-light JSON entrypoint: pipe the changed+// filenames in, get back `{path: {owners, status, slack, source}}`. The workflow+// provides python3 + pyyaml and checks out master, so the resolver reads the same+// owners.yaml tree CI enforces.+function resolveOwners(filenames) {+ if (filenames.length === 0) {+ return {}}- // Rules with no owner are reset directives that only matter for hard/soft- // precedence (see ownership.js); the assigner only cares about owned rules.- return parse(fs.readFileSync(codeownersPath, 'utf8')).rules.filter((rule) => rule.owners.length > 0)-}--// Minimal parser for the `owners:` list in products/<name>/product.yaml.-// We don't depend on a YAML library because this script runs from a bare CI-// checkout; the schema is simple and validated elsewhere by hogli.-function parseOwnersFromProductYaml(content) {- const owners = []- let inOwners = false-- for (const rawLine of content.split('\n')) {- const line = rawLine.replace(/\s+#.*$/, '').trimEnd()-- // Skip blank lines and full-line comments; neither should terminate the- // owners block. Inline comments are already stripped above; the regex- // requires preceding whitespace, so we handle column-0 comments here.- if (!line.trim() || /^\s*#/.test(rawLine)) {- continue- }-- if (/^owners\s*:\s*$/.test(line)) {- inOwners = true- continue- }-- if (!inOwners) {- continue- }-- const listMatch = line.match(/^\s+-\s+(.+?)$/)- if (listMatch) {- owners.push(listMatch[1].replace(/^["']|["']$/g, '').trim())- continue- }-- // A new top-level key terminates the owners block.- if (/^\S/.test(rawLine)) {- inOwners = false- }+ const python = process.env.OWNERS_RESOLVER_PYTHON || 'python3'+ // Insert the package dir on sys.path *after* interpreter startup instead of+ // via PYTHONPATH: a PYTHONPATH entry is scanned by the `site` module at+ // startup, so an unprotected sitecustomize.py/usercustomize.py added there+ // later would execute in this pull_request_target context. Post-startup+ // insertion never triggers those hooks; stdlib-shadow modules in that dir+ // are blocked by the CODEOWNERS entry on tools/owners. -I (isolated mode)+ // additionally drops the implicit CWD sys.path entry, so an unprotected+ // repo-root yaml.py can't shadow PyYAML either; the setup-python+ // interpreter's site-packages (where the workflow installs pyyaml) stays+ // importable.+ const launcher =+ "import sys, runpy; sys.path.insert(0, 'tools/owners'); runpy.run_module('posthog_owners', run_name='__main__')"+ const result = spawnSync(python, ['-I', '-c', launcher], {+ input: filenames.join('\n'),+ encoding: 'utf8',+ maxBuffer: 64 * 1024 * 1024,+ })+ if (result.error) {+ throw new Error(`Could not run owners resolver: ${result.error.message}`)}-- return owners-}--function loadProductYamlRules(productsDir = 'products') {- const rules = []-- if (!fs.existsSync(productsDir)) {- return rules+ if (result.status !== 0) {+ throw new Error(`owners resolver exited ${result.status}:\n${result.stderr || result.stdout}`)}+ return JSON.parse(result.stdout)+}- const entries = fs.readdirSync(productsDir, { withFileTypes: true })-- for (const entry of entries) {- if (!entry.isDirectory()) {- continue- }-- const yamlPath = `${productsDir}/${entry.name}/product.yaml`- if (!fs.existsSync(yamlPath)) {- continue- }-- const content = fs.readFileSync(yamlPath, 'utf8')- const slugs = parseOwnersFromProductYaml(content)-- const owners = []- for (const slug of slugs) {- // Guard against slugs that already include an `@` prefix, otherwise- // we'd build `@PostHog/@PostHog/team-foo`, which GitHub silently- // refuses to resolve and reviewer assignment is dropped.- if (!slug || slug === 'team-CHANGEME' || slug.startsWith('@')) {- continue- }- owners.push(`@PostHog/${slug}`)- }-- if (owners.length === 0) {- continue- }-- rules.push({ pattern: `${productsDir}/${entry.name}/**`, owners })+// The resolver emits bare team slugs (`team-foo`) and `@handle` individuals.+// Normalize to the CODEOWNERS token shape the rest of the assigner speaks —+// `@PostHog/<slug>` for teams, `@handle` for users — then classify.+function mapResolvedOwner(rawOwner) {+ if (!rawOwner) {+ return null}-- return rules+ const token = rawOwner.startsWith('@') ? rawOwner : `@PostHog/${rawOwner}`+ return classifyOwner(token)}// Glob matching lives in the vendored, GitHub-faithful matcher (./codeowners.js,@@ -228,41 +183,60 @@ function classifyOwner(owner) {return null}-// Build a footprint per owner: which rule patterns matched, which (non-excluded)-// files they own in this diff, and the total lines changed across those files.-// Pure function; takes already-fetched files so it's trivially testable.-function computeOwnerFootprints(rules, changedFiles, config = CONFIG) {+// Build a footprint per owner from the resolver's per-file result: which+// owners.yaml/product.yaml sources pulled them in, which (non-excluded) files+// they own in this diff, and the total lines changed across those files. Pure+// function; takes the already-fetched files and the resolver map so it's+// trivially testable. `resolutionByPath` maps filename -> {owners, source, ...}.+function computeOwnerFootprints(resolutionByPath, changedFiles, config = CONFIG) {const relevantFiles = changedFiles.filter((file) => !isExcludedFile(file.filename, config.excludedPatterns))const footprints = new Map()- for (const rule of rules) {- const matched = relevantFiles.filter((file) => fileMatchesPattern(file.filename, rule.pattern))- if (matched.length === 0) {+ for (const file of relevantFiles) {+ const resolution = resolutionByPath[file.filename]+ // status: generated/vendored is the structured form of the excluded+ // patterns above — such trees have owners for lookup, but shouldn't+ // pull reviewers in or count toward substantive thresholds. Ownership+ // metadata files are exempt: an owners.yaml edit inside a generated+ // tree still changes future routing and must reach a reviewer.+ const basename = file.filename.split('/').pop()+ const isOwnershipFile = basename === 'owners.yaml' || basename === 'product.yaml'+ if (+ !isOwnershipFile &&+ resolution &&+ (resolution.status === 'generated' || resolution.status === 'vendored')+ ) {+ continue+ }+ const owners = (resolution && resolution.owners) || []+ if (owners.length === 0) {continue}+ // The source is the owners.yaml/product.yaml that decided this file — the+ // actionable locator we surface instead of a glob pattern.+ const source = (resolution && resolution.source) || '(unresolved source)'+ const lines = file.additions + file.deletions- for (const owner of rule.owners) {- const resolved = classifyOwner(owner)+ for (const rawOwner of owners) {+ const resolved = mapResolvedOwner(rawOwner)if (!resolved) {continue}- let footprint = footprints.get(owner)+ let footprint = footprints.get(resolved.owner)if (!footprint) {footprint = {- owner,+ owner: resolved.owner,type: resolved.type,name: resolved.name,- patterns: new Set(),- files: new Map(), // filename -> changed lines, deduped across rules+ patterns: new Set(), // resolver source locators, shown in the demotion comment+ files: new Map(), // filename -> changed lines}- footprints.set(owner, footprint)+ footprints.set(resolved.owner, footprint)}- footprint.patterns.add(rule.pattern)- for (const file of matched) {- footprint.files.set(file.filename, file.additions + file.deletions)- }+ footprint.patterns.add(source)+ footprint.files.set(file.filename, lines)}}@@ -370,9 +344,9 @@ function buildReviewerComment(requested, demoted, config = CONFIG) {'',...demoted.map(formatSkippedOwner),'',- 'Soft owners come from ' +- '[`CODEOWNERS-soft`](https://github.com/PostHog/posthog/blob/master/.github/CODEOWNERS-soft) ' +- "and each product's `product.yaml`. Generated files and lockfiles are ignored when deciding ownership.",+ "Soft owners come from each directory's `owners.yaml` and each product's `product.yaml` " ++ '(resolved nearest-file-wins). The locator after each owner is the file that decided it. ' ++ 'Generated files and lockfiles are ignored when deciding ownership.',].join('\n')}@@ -409,23 +383,25 @@ async function assignReviewers(teams, users) {const response = await post(payload)- // GitHub returns 422 for the whole batch if *any* requested team isn't a- // collaborator on the repo (teams get renamed, deleted, or never set up,- // CODEOWNERS-soft and product.yaml drift). Salvage by retrying users +- // each team independently so valid entries still land, and log the bad- // slugs so they're visible in the action log as cleanup nudges.- if (response.status === 422 && teams.length > 0) {+ // GitHub returns 422 for the whole batch if *any* requested team or user+ // isn't assignable on the repo (teams get renamed or deleted, individual+ // @handles go stale or leave, owners.yaml and product.yaml drift). Salvage+ // by retrying every user and team independently so valid entries still+ // land, and log the bad ones so they're visible as cleanup nudges.+ if (response.status === 422) {const errorText = await response.text()console.warn(`⚠️ 422 on bulk request, retrying individually:\n${errorText}`)- if (users.length > 0) {- const r = await post({ reviewers: users })- if (!r.ok) {- throw new Error(`GitHub API error assigning users: ${r.status} ${r.statusText}\n${await r.text()}`)+ const dropped = []+ for (const user of users) {+ const r = await post({ reviewers: [user] })+ if (r.status === 422) {+ dropped.push(`@${user}`)+ } else if (!r.ok) {+ throw new Error(`GitHub API error assigning user '${user}': ${r.status} ${r.statusText}\n${await r.text()}`)}}- const dropped = []for (const team of teams) {const r = await post({ team_reviewers: [team] })if (r.status === 422) {@@ -439,8 +415,8 @@ async function assignReviewers(teams, users) {if (dropped.length > 0) {console.warn(- `⚠️ Dropped ${dropped.length} stale team(s): ${dropped.join(', ')}. ` +- `Fix product.yaml / CODEOWNERS-soft so these get assigned next time.`+ `⚠️ Dropped ${dropped.length} stale reviewer(s): ${dropped.join(', ')}. ` ++ `Fix product.yaml / owners.yaml so these get assigned next time.`)}console.info('✅ Reviewers assigned (with fallback)')@@ -576,18 +552,20 @@ async function main() {}try {- const codeownersPath = '.github/CODEOWNERS-soft'- // products/<name>/product.yaml is the source of truth for product team- // ownership; we layer those rules on top of CODEOWNERS-soft so the file- // only needs to carry sub-folder overrides and secondary reviewers.- const rules = [...parseCodeowners(codeownersPath), ...loadProductYamlRules()]const changedFiles = await getChangedFiles()console.info(`Found ${changedFiles.length} changed files:`)changedFiles.forEach((file) => console.info(` ${file.filename} (+${file.additions} -${file.deletions})`))console.info()- const footprints = computeOwnerFootprints(rules, changedFiles)+ // Resolve ownership for the files that actually count (excluded ones can't+ // pull in a reviewer, so don't waste a resolver round-trip on them).+ const relevantFilenames = changedFiles+ .filter((file) => !isExcludedFile(file.filename))+ .map((file) => file.filename)+ const resolutionByPath = resolveOwners(relevantFilenames)++ const footprints = computeOwnerFootprints(resolutionByPath, changedFiles)const { requested, demoted } = classifyOwners(footprints)const teams = requested.filter((f) => f.type === 'team').map((f) => f.name)diff --git a/.github/scripts/assign-reviewers.test.js b/.github/scripts/assign-reviewers.test.jsindex 9fd16ecb078a..3f9911c41341 100644--- a/.github/scripts/assign-reviewers.test.js+++ b/.github/scripts/assign-reviewers.test.js@@ -1,3 +1,8 @@+// Run with: node --test .github/scripts/assign-reviewers.test.js++const test = require('node:test')+const assert = require('node:assert/strict')+const {CONFIG,isExcludedFile,@@ -16,263 +21,326 @@ const file = (filename, additions = 0, deletions = 0) => ({additions,deletions,})-const rule = (pattern, ...owners) => ({ pattern, owners })--describe('assign-reviewers', () => {- describe('isExcludedFile', () => {- test.each([- ['frontend/src/generated/core/api.ts', true],- ['frontend/src/generated/core/api.schemas.ts', true],- ['products/surveys/frontend/generated/api.zod.ts', true],- ['services/mcp/src/tools/generated/surveys.ts', true],- ['pnpm-lock.yaml', true],- ['rust/Cargo.lock', true],- ['uv.lock', true],- ['posthog/api/test/__snapshots__/test_survey.ambr', true],- ['frontend/src/scenes/x/Component.test.tsx.snap', true],- ['nodejs/src/ingestion/pipelines/ai/costs/providers/canonical-providers.ts', true],- ['nodejs/src/ingestion/pipelines/ai/costs/providers/llm-costs.json', true],- ['nodejs/src/ingestion/pipelines/ai/costs/providers/manual-providers.ts', false],- ['posthog/api/survey.py', false],- ['frontend/src/scenes/surveys/Survey.tsx', false],- ])('%s -> %s', (filename, expected) => {- expect(isExcludedFile(filename)).toBe(expected)- })- })+// A resolver result entry: bare team slugs / @handles plus the deciding source.+const resolved = (owners, source) => ({ owners, source, status: 'active', slack: null })- describe('fileMatchesPattern', () => {- test.each([- // a trailing slash is a directory boundary, not a name prefix- ['posthog/models/ai/utils.py', 'posthog/models/ai/', true],- ['posthog/models/ai/sub/deep.py', 'posthog/models/ai/', true],- ['posthog/models/ai_events/event.py', 'posthog/models/ai/', false],- ['posthog/models/person/util.py', 'posthog/models/person/', true],- ['posthog/models/person_overrides/x.py', 'posthog/models/person/', false],- ['posthog/models/personal_api_key.py', 'posthog/models/person/', false],- // /** is bounded to the directory, same as a trailing slash- ['posthog/models/ai/utils.py', 'posthog/models/ai/**', true],- ['posthog/models/ai_events/event.py', 'posthog/models/ai/**', false],- // a single star stays within one path segment- ['posthog/dags/sessions.py', 'posthog/dags/*.py', true],- ['posthog/dags/sub/sessions.py', 'posthog/dags/*.py', false],- // exact-file patterns match only that file- ['posthog/api/person.py', 'posthog/api/person.py', true],- ['posthog/api/person_other.py', 'posthog/api/person.py', false],- ])('%s vs %s', (filename, pattern, expected) => {- expect(fileMatchesPattern(filename, pattern)).toBe(expected)- })- })+// Asserts that actual contains all key/value pairs from partial (shallow per key, deep per value).+function assertMatchObject(actual, partial) {+ for (const [key, expected] of Object.entries(partial)) {+ assert.deepEqual(actual[key], expected)+ }+}- describe('classifyOwner', () => {- test.each([- ['@PostHog/team-surveys', { type: 'team', name: 'team-surveys', owner: '@PostHog/team-surveys' }],- ['@rafaeelaudibert', { type: 'user', name: 'rafaeelaudibert', owner: '@rafaeelaudibert' }],- ['not-an-owner', null],- ])('%s', (input, expected) => {- expect(classifyOwner(input)).toEqual(expected)- })+for (const [filename, expected] of [+ ['frontend/src/generated/core/api.ts', true],+ ['frontend/src/generated/core/api.schemas.ts', true],+ ['products/surveys/frontend/generated/api.zod.ts', true],+ ['services/mcp/src/tools/generated/surveys.ts', true],+ ['pnpm-lock.yaml', true],+ ['rust/Cargo.lock', true],+ ['uv.lock', true],+ ['posthog/api/test/__snapshots__/test_survey.ambr', true],+ ['frontend/src/scenes/x/Component.test.tsx.snap', true],+ ['nodejs/src/ingestion/pipelines/ai/costs/providers/canonical-providers.ts', true],+ ['nodejs/src/ingestion/pipelines/ai/costs/providers/llm-costs.json', true],+ ['nodejs/src/ingestion/pipelines/ai/costs/providers/manual-providers.ts', false],+ ['posthog/api/survey.py', false],+ ['frontend/src/scenes/surveys/Survey.tsx', false],+]) {+ test(`isExcludedFile: ${filename} -> ${expected}`, () => {+ assert.equal(isExcludedFile(filename), expected)})+}- describe('teamSlugToLabel', () => {- test.each([- ['team-product-analytics', 'team/product-analytics'],- ['team-infra', 'team/infra'],- ['rafaeelaudibert', null],- ['', null],- ])('%s -> %s', (name, expected) => {- expect(teamSlugToLabel(name)).toBe(expected)- })+for (const [file, pattern, expected] of [+ // a trailing slash is a directory boundary, not a name prefix+ ['posthog/models/ai/utils.py', 'posthog/models/ai/', true],+ ['posthog/models/ai/sub/deep.py', 'posthog/models/ai/', true],+ ['posthog/models/ai_events/event.py', 'posthog/models/ai/', false],+ ['posthog/models/person/util.py', 'posthog/models/person/', true],+ ['posthog/models/person_overrides/x.py', 'posthog/models/person/', false],+ ['posthog/models/personal_api_key.py', 'posthog/models/person/', false],+ // /** is bounded to the directory, same as a trailing slash+ ['posthog/models/ai/utils.py', 'posthog/models/ai/**', true],+ ['posthog/models/ai_events/event.py', 'posthog/models/ai/**', false],+ // a single star stays within one path segment+ ['posthog/dags/sessions.py', 'posthog/dags/*.py', true],+ ['posthog/dags/sub/sessions.py', 'posthog/dags/*.py', false],+ // exact-file patterns match only that file+ ['posthog/api/person.py', 'posthog/api/person.py', true],+ ['posthog/api/person_other.py', 'posthog/api/person.py', false],+]) {+ test(`fileMatchesPattern: ${file} vs ${pattern}`, () => {+ assert.equal(fileMatchesPattern(file, pattern), expected)})+}- describe('partitionExternalTeams', () => {- test('labels product-analytics, still requests every other team', () => {- const { toLabel, toRequest } = partitionExternalTeams([- 'team-product-analytics',- 'team-web-analytics',- 'team-infra',- ])- expect(toLabel).toEqual(['team-product-analytics'])- expect(toRequest).toEqual(['team-web-analytics', 'team-infra'])- })-- test('no product-analytics owner → nothing labelled, all requested', () => {- const { toLabel, toRequest } = partitionExternalTeams(['team-web-analytics', 'team-infra'])- expect(toLabel).toEqual([])- expect(toRequest).toEqual(['team-web-analytics', 'team-infra'])- })+test('classifyOwner: @PostHog/team-surveys', () => {+ assert.deepEqual(classifyOwner('@PostHog/team-surveys'), {+ type: 'team',+ name: 'team-surveys',+ owner: '@PostHog/team-surveys',})-- describe('computeOwnerFootprints', () => {- test('ignores generated/excluded files when matching ownership', () => {- const rules = [- rule('posthog/api/survey.py', '@PostHog/team-surveys'),- rule('frontend/src/generated/**', '@PostHog/team-devex'),- ]- const files = [file('posthog/api/survey.py', 40, 10), file('frontend/src/generated/core/api.ts', 999, 999)]-- const footprints = computeOwnerFootprints(rules, files)-- expect(footprints).toHaveLength(1)- expect(footprints[0]).toMatchObject({- owner: '@PostHog/team-surveys',- type: 'team',- fileCount: 1,- lines: 50,- })- })-- test('dedupes a file owned via multiple rules and sums lines once', () => {- const rules = [- rule('posthog/hogql/**', '@PostHog/team-data-tools'),- rule('posthog/hogql/printer.py', '@PostHog/team-data-tools'),- ]- const files = [file('posthog/hogql/printer.py', 5, 3)]-- const [footprint] = computeOwnerFootprints(rules, files)-- expect(footprint.fileCount).toBe(1)- expect(footprint.lines).toBe(8)- expect(footprint.patterns).toEqual(expect.arrayContaining(['posthog/hogql/**', 'posthog/hogql/printer.py']))- })+})+test('classifyOwner: @rafaeelaudibert', () => {+ assert.deepEqual(classifyOwner('@rafaeelaudibert'), {+ type: 'user',+ name: 'rafaeelaudibert',+ owner: '@rafaeelaudibert',})+})+test('classifyOwner: not-an-owner', () => {+ assert.equal(classifyOwner('not-an-owner'), null)+})- describe('isSubstantive', () => {- test.each([- [{ lines: 50, fileCount: 1 }, true],- [{ lines: 2, fileCount: 5 }, true],- [{ lines: 2, fileCount: 1 }, false],- [{ lines: CONFIG.substantiveLines, fileCount: 1 }, true],- [{ lines: 0, fileCount: CONFIG.substantiveFiles }, true],- ])('%o -> %s', (footprint, expected) => {- expect(isSubstantive(footprint)).toBe(expected)- })- })+test('teamSlugToLabel: team-product-analytics -> team/product-analytics', () => {+ assert.equal(teamSlugToLabel('team-product-analytics'), 'team/product-analytics')+})+test('teamSlugToLabel: team-infra -> team/infra', () => {+ assert.equal(teamSlugToLabel('team-infra'), 'team/infra')+})+test('teamSlugToLabel: rafaeelaudibert -> null', () => {+ assert.equal(teamSlugToLabel('rafaeelaudibert'), null)+})+test('teamSlugToLabel: empty string -> null', () => {+ assert.equal(teamSlugToLabel(''), null)+})- describe('classifyOwners', () => {- const fp = (owner, lines, fileCount = 1, type = 'team') => ({- owner,- type,- name: owner.replace('@PostHog/', '').replace('@', ''),- patterns: [owner],- fileCount,- lines,- })-- test('a single matched owner is always requested, even when tiny', () => {- const { requested, demoted } = classifyOwners([fp('@PostHog/team-a', 1)])- expect(requested).toHaveLength(1)- expect(demoted).toHaveLength(0)- })-- test('demotes owners below the substantive bar but keeps substantive ones', () => {- const { requested, demoted } = classifyOwners([fp('@PostHog/team-big', 120), fp('@PostHog/team-small', 2)])- expect(requested.map((f) => f.owner)).toEqual(['@PostHog/team-big'])- expect(demoted.map((f) => f.owner)).toEqual(['@PostHog/team-small'])- expect(demoted[0].reason).toBe('minor')- })-- test('promotes the largest owner when all are below the bar', () => {- const { requested, demoted } = classifyOwners([- fp('@PostHog/team-a', 1),- fp('@PostHog/team-b', 4),- fp('@PostHog/team-c', 2),- ])- expect(requested.map((f) => f.owner)).toEqual(['@PostHog/team-b'])- // The promoted owner is a clean request, not a demotion.- expect(requested[0].reason).toBeUndefined()- expect(demoted.map((f) => f.owner)).toEqual(['@PostHog/team-c', '@PostHog/team-a'])- })-- test('caps requested teams at maxTeamsRequested, demoting the smallest', () => {- const footprints = Array.from({ length: CONFIG.maxTeamsRequested + 3 }, (_, i) =>- fp(`@PostHog/team-${i}`, 50 + i)- )- const { requested, demoted } = classifyOwners(footprints)-- expect(requested.filter((f) => f.type === 'team')).toHaveLength(CONFIG.maxTeamsRequested)- expect(demoted).toHaveLength(3)- // Largest footprints are kept; the three smallest are demoted as capped.- expect(requested.some((f) => f.owner === `@PostHog/team-${footprints.length - 1}`)).toBe(true)- expect(demoted.map((f) => f.owner)).toEqual(- expect.arrayContaining(['@PostHog/team-0', '@PostHog/team-1', '@PostHog/team-2'])- )- expect(demoted.every((f) => f.reason === 'capped')).toBe(true)- })-- test('never caps explicit users even when teams overflow the cap', () => {- // All substantive, so the cap (teams-only) is the only thing that can demote.- const teams = Array.from({ length: CONFIG.maxTeamsRequested + 2 }, (_, i) =>- fp(`@PostHog/team-${i}`, 50 + i)- )- const users = [fp('@user-a', 20, 1, 'user'), fp('@user-b', 20, 1, 'user')]- const { requested, demoted } = classifyOwners([...teams, ...users])-- // Both users survive the cap...- expect(- requested- .filter((f) => f.type === 'user')- .map((f) => f.owner)- .sort()- ).toEqual(['@user-a', '@user-b'])- // ...while the smallest teams beyond the cap are demoted.- expect(requested.filter((f) => f.type === 'team')).toHaveLength(CONFIG.maxTeamsRequested)- expect(demoted.map((f) => f.owner)).toEqual(expect.arrayContaining(['@PostHog/team-0', '@PostHog/team-1']))- expect(demoted.every((f) => f.type === 'team')).toBe(true)- })+test('partitionExternalTeams: labels product-analytics, still requests every other team', () => {+ const { toLabel, toRequest } = partitionExternalTeams([+ 'team-product-analytics',+ 'team-web-analytics',+ 'team-infra',+ ])+ assert.deepEqual(toLabel, ['team-product-analytics'])+ assert.deepEqual(toRequest, ['team-web-analytics', 'team-infra'])+})++test('partitionExternalTeams: no product-analytics owner → nothing labelled, all requested', () => {+ const { toLabel, toRequest } = partitionExternalTeams(['team-web-analytics', 'team-infra'])+ assert.deepEqual(toLabel, [])+ assert.deepEqual(toRequest, ['team-web-analytics', 'team-infra'])+})++test('computeOwnerFootprints: ignores generated/excluded files and maps bare slugs to @PostHog handles', () => {+ const resolution = {+ 'posthog/api/survey.py': resolved(['team-surveys'], 'products/surveys/product.yaml'),+ // Excluded before resolution, but assert it can't leak in even if present.+ 'frontend/src/generated/core/api.ts': resolved(['team-devex'], 'owners.yaml'),+ }+ const files = [file('posthog/api/survey.py', 40, 10), file('frontend/src/generated/core/api.ts', 999, 999)]++ const footprints = computeOwnerFootprints(resolution, files)++ assert.equal(footprints.length, 1)+ assertMatchObject(footprints[0], {+ owner: '@PostHog/team-surveys',+ type: 'team',+ fileCount: 1,+ lines: 50,+ patterns: ['products/surveys/product.yaml'],})+})++test('computeOwnerFootprints: skips resolutions with generated/vendored status', () => {+ const resolution = {+ 'posthog/api/survey.py': resolved(['team-surveys'], 'products/surveys/product.yaml'),+ 'some/generated/tree/file.ts': { ...resolved(['team-devex'], 'some/generated/owners.yaml'), status: 'generated' },+ 'vendor/lib/thing.js': { ...resolved(['team-devex'], 'vendor/owners.yaml'), status: 'vendored' },+ }+ // An ownership file inside a generated tree resolves with that status too,+ // but editing it changes future routing — it must not be skipped.+ resolution['some/generated/owners.yaml'] = {+ ...resolved(['team-devex'], 'owners.yaml'),+ status: 'generated',+ }+ const files = [+ file('posthog/api/survey.py', 40, 10),+ file('some/generated/tree/file.ts', 500, 500),+ file('vendor/lib/thing.js', 300, 0),+ file('some/generated/owners.yaml', 3, 0),+ ]++ const footprints = computeOwnerFootprints(resolution, files)++ assert.equal(footprints.length, 2)+ assertMatchObject(footprints[0], { owner: '@PostHog/team-surveys', fileCount: 1, lines: 50 })+ assertMatchObject(footprints[1], { owner: '@PostHog/team-devex', fileCount: 1, lines: 3 })+})++test('computeOwnerFootprints: accumulates files and sources per owner, and requests @handle individuals as users', () => {+ const resolution = {+ 'posthog/hogql/printer.py': resolved(['team-data-tools'], 'posthog/hogql/owners.yaml'),+ 'posthog/hogql/parser.py': resolved(['team-data-tools', '@webjunkie'], 'posthog/hogql/owners.yaml'),+ }+ const files = [file('posthog/hogql/printer.py', 5, 3), file('posthog/hogql/parser.py', 2, 0)]++ const footprints = computeOwnerFootprints(resolution, files)- describe('buildReviewerComment', () => {- const requested = [- {- owner: '@PostHog/team-surveys',- fileCount: 2,- lines: 135,- patterns: ['products/surveys/**'],- },- ]- const demoted = [- {- owner: '@PostHog/team-data-tools',- fileCount: 1,- lines: 2,- patterns: ['posthog/hogql/**'],- reason: 'minor',- },- ]-- test('returns null when no owner was dropped', () => {- expect(buildReviewerComment(requested, [])).toBeNull()- expect(buildReviewerComment([...requested, requested[0]], [])).toBeNull()- })-- test('lists each skipped owner as a bullet with its matched rule, not raw counts', () => {- const body = buildReviewerComment(requested, demoted)- expect(body).toContain(CONFIG.commentMarker)- expect(body).toContain('- `@PostHog/team-data-tools` (`posthog/hogql/**`)')- expect(body).toContain('they only have minor changes here')- // No count theater: file/line numbers are internal-only, and no table.- expect(body).not.toMatch(/\d+ files/)- expect(body).not.toContain('| Lines |')- })-- test('explains the reviewer cap when an owner was capped out', () => {- const cappedDemoted = [{ ...demoted[0], reason: 'capped' }]- const body = buildReviewerComment(requested, cappedDemoted)- expect(body).toContain('the reviewer list was getting long')- })-- test('truncates long pattern lists', () => {- const manyDemoted = [- {- owner: '@PostHog/team-x',- fileCount: 1,- lines: 1,- patterns: ['a/**', 'b/**', 'c/**', 'd/**', 'e/**'],- reason: 'minor',- },- ]- const body = buildReviewerComment(requested, manyDemoted)- expect(body).toContain('(+3 more)')- })+ const team = footprints.find((f) => f.owner === '@PostHog/team-data-tools')+ assertMatchObject(team, { type: 'team', fileCount: 2, lines: 10 })+ assert.deepEqual(team.patterns, ['posthog/hogql/owners.yaml'])++ const user = footprints.find((f) => f.owner === '@webjunkie')+ assertMatchObject(user, { type: 'user', name: 'webjunkie', fileCount: 1, lines: 2 })+})++for (const [footprint, expected] of [+ [{ lines: 50, fileCount: 1 }, true],+ [{ lines: 2, fileCount: 5 }, true],+ [{ lines: 2, fileCount: 1 }, false],+ [{ lines: CONFIG.substantiveLines, fileCount: 1 }, true],+ [{ lines: 0, fileCount: CONFIG.substantiveFiles }, true],+]) {+ test(`isSubstantive: ${JSON.stringify(footprint)} -> ${expected}`, () => {+ assert.equal(isSubstantive(footprint), expected)})+}++const fp = (owner, lines, fileCount = 1, type = 'team') => ({+ owner,+ type,+ name: owner.replace('@PostHog/', '').replace('@', ''),+ patterns: [owner],+ fileCount,+ lines,+})++test('classifyOwners: a single matched owner is always requested, even when tiny', () => {+ const { requested, demoted } = classifyOwners([fp('@PostHog/team-a', 1)])+ assert.equal(requested.length, 1)+ assert.equal(demoted.length, 0)+})++test('classifyOwners: demotes owners below the substantive bar but keeps substantive ones', () => {+ const { requested, demoted } = classifyOwners([fp('@PostHog/team-big', 120), fp('@PostHog/team-small', 2)])+ assert.deepEqual(+ requested.map((f) => f.owner),+ ['@PostHog/team-big']+ )+ assert.deepEqual(+ demoted.map((f) => f.owner),+ ['@PostHog/team-small']+ )+ assert.equal(demoted[0].reason, 'minor')+})++test('classifyOwners: promotes the largest owner when all are below the bar', () => {+ const { requested, demoted } = classifyOwners([+ fp('@PostHog/team-a', 1),+ fp('@PostHog/team-b', 4),+ fp('@PostHog/team-c', 2),+ ])+ assert.deepEqual(+ requested.map((f) => f.owner),+ ['@PostHog/team-b']+ )+ // The promoted owner is a clean request, not a demotion.+ assert.equal(requested[0].reason, undefined)+ assert.deepEqual(+ demoted.map((f) => f.owner),+ ['@PostHog/team-c', '@PostHog/team-a']+ )+})++test('classifyOwners: caps requested teams at maxTeamsRequested, demoting the smallest', () => {+ const footprints = Array.from({ length: CONFIG.maxTeamsRequested + 3 }, (_, i) =>+ fp(`@PostHog/team-${i}`, 50 + i)+ )+ const { requested, demoted } = classifyOwners(footprints)++ assert.equal(requested.filter((f) => f.type === 'team').length, CONFIG.maxTeamsRequested)+ assert.equal(demoted.length, 3)+ // Largest footprints are kept; the three smallest are demoted as capped.+ assert.equal(+ requested.some((f) => f.owner === `@PostHog/team-${footprints.length - 1}`),+ true+ )+ for (const expected of ['@PostHog/team-0', '@PostHog/team-1', '@PostHog/team-2']) {+ assert.ok(demoted.some((f) => f.owner === expected))+ }+ assert.equal(+ demoted.every((f) => f.reason === 'capped'),+ true+ )+})++test('classifyOwners: never caps explicit users even when teams overflow the cap', () => {+ // All substantive, so the cap (teams-only) is the only thing that can demote.+ const teams = Array.from({ length: CONFIG.maxTeamsRequested + 2 }, (_, i) =>+ fp(`@PostHog/team-${i}`, 50 + i)+ )+ const users = [fp('@user-a', 20, 1, 'user'), fp('@user-b', 20, 1, 'user')]+ const { requested, demoted } = classifyOwners([...teams, ...users])++ // Both users survive the cap...+ assert.deepEqual(+ requested+ .filter((f) => f.type === 'user')+ .map((f) => f.owner)+ .sort(),+ ['@user-a', '@user-b']+ )+ // ...while the smallest teams beyond the cap are demoted.+ assert.equal(requested.filter((f) => f.type === 'team').length, CONFIG.maxTeamsRequested)+ for (const expected of ['@PostHog/team-0', '@PostHog/team-1']) {+ assert.ok(demoted.some((f) => f.owner === expected))+ }+ assert.equal(+ demoted.every((f) => f.type === 'team'),+ true+ )+})++const requested = [+ {+ owner: '@PostHog/team-surveys',+ fileCount: 2,+ lines: 135,+ patterns: ['products/surveys/**'],+ },+]+const demoted = [+ {+ owner: '@PostHog/team-data-tools',+ fileCount: 1,+ lines: 2,+ patterns: ['posthog/hogql/**'],+ reason: 'minor',+ },+]++test('buildReviewerComment: returns null when no owner was dropped', () => {+ assert.equal(buildReviewerComment(requested, []), null)+ assert.equal(buildReviewerComment([...requested, requested[0]], []), null)+})++test('buildReviewerComment: lists each skipped owner as a bullet with its matched rule, not raw counts', () => {+ const body = buildReviewerComment(requested, demoted)+ assert.ok(body.includes(CONFIG.commentMarker))+ assert.ok(body.includes('- `@PostHog/team-data-tools` (`posthog/hogql/**`)'))+ assert.ok(body.includes('they only have minor changes here'))+ // No count theater: file/line numbers are internal-only, and no table.+ assert.ok(!/\d+ files/.test(body))+ assert.ok(!body.includes('| Lines |'))+})++test('buildReviewerComment: explains the reviewer cap when an owner was capped out', () => {+ const cappedDemoted = [{ ...demoted[0], reason: 'capped' }]+ const body = buildReviewerComment(requested, cappedDemoted)+ assert.ok(body.includes('the reviewer list was getting long'))+})++test('buildReviewerComment: truncates long pattern lists', () => {+ const manyDemoted = [+ {+ owner: '@PostHog/team-x',+ fileCount: 1,+ lines: 1,+ patterns: ['a/**', 'b/**', 'c/**', 'd/**', 'e/**'],+ reason: 'minor',+ },+ ]+ const body = buildReviewerComment(requested, manyDemoted)+ assert.ok(body.includes('(+3 more)'))})diff --git a/.github/workflows/auto-assign-reviewers.yml b/.github/workflows/auto-assign-reviewers.ymlindex d3516bc3d4f7..c9b647a2fc2c 100644--- a/.github/workflows/auto-assign-reviewers.yml+++ b/.github/workflows/auto-assign-reviewers.yml@@ -48,6 +48,22 @@ jobs:# Resolve the node-versions manifest on the app token, not the shared per-repo GITHUB_TOKEN buckettoken: ${{ steps.app-token.outputs.token || github.token }}+ # The assigner shells out to the owners resolver+ # (`python -m posthog_owners`) for ownership. That entrypoint+ # only needs pyyaml, so set up python and install just that — no full+ # project sync in this node-first workflow.+ - name: Setup Python+ uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0+ with:+ python-version: '3.13'++ # Exact pin: this pull_request_target workflow runs with an app token,+ # so a floating version must not be able to pull fresh code at run time.+ # -I (isolated mode) keeps the checkout's CWD off sys.path, so a+ # repo-root pip.py can never shadow the real pip here.+ - name: Install resolver dependency+ run: python -I -m pip install --quiet 'pyyaml==6.0.2'+# Script runs from master branch (protected), but can diff against PR branch- name: Run reviewer assignment scriptenv:diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 23f12b11a960..e5e058b58fb0 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -272,10 +272,14 @@ jobs:tasks_temporal:- 'products/tasks/backend/temporal/**/*'product_yamls:- # Validates owner team slugs against PostHog/posthog collaborator teams.- # Costs one GitHub API call; gated here so we only pay it when ownership- # actually changes. Drives the validate-product-yamls job below.+ # Validates owner team slugs against PostHog/posthog collaborator teams,+ # and lints the distributed owners.yaml files (schema, conflicts, dead+ # globs, coverage). Costs one GitHub API call; gated here so we only pay+ # it when ownership actually changes. Drives the validate-product-yamls job.- 'products/*/product.yaml'+ - '**/owners.yaml'+ # Resolver changes must re-run the owners.yaml lint too.+ - 'tools/owners/**'openapi_types:# Generated OpenAPI types - validate they match schema- 'frontend/src/generated/**/*'@@ -904,7 +908,8 @@ jobs:# Consolidates checks that previously each spun up their own runner.repo-checks:needs: [changes]- if: needs.changes.outputs.backend == 'true'+ # product_yamls: ownership-only PRs still need the owners.yaml lint below.+ if: needs.changes.outputs.backend == 'true' || needs.changes.outputs.product_yamls == 'true'timeout-minutes: 10outputs:deterministic_failure: ${{ steps.deterministic-failure.outputs.deterministic_failure || 'false' }}@@ -971,6 +976,13 @@ jobs:- name: Lint product structurerun: ./bin/hogli product:lint --all+ # Distributed owners.yaml tree: schema, product.yaml/owners.yaml+ # conflicts, dead rule globs, coverage (warn-only). No --live, so no+ # secrets — fork PRs get validated too (the --live slug check runs in+ # the fork-gated validate-product-yamls job instead).+ - name: Lint owners.yaml files+ run: ./bin/hogli owners:lint+- name: Check version specifiersrun: python .github/scripts/check-version-specifiers.py@@ -1076,9 +1088,14 @@ jobs:names=$(for n in $names; do [ -f "products/$n/product.yaml" ] && printf '%s ' "$n"; done | xargs)if [ -z "$names" ]; thenecho "No existing product.yaml files in diff after filtering"- exit 0+ else+ ./bin/hogli product:lint:owners $namesfi- ./bin/hogli product:lint:owners $names++ - name: Validate owners.yaml identities against GitHub+ env:+ GH_TOKEN: ${{ steps.app-token.outputs.token }}+ run: ./bin/hogli owners:lint --live# Migration validation.# This job needs Docker + DB — it checks out master first to run baselinediff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.ymlindex aba0ca8f3929..8fb515316b01 100644--- a/.github/workflows/ci-python.yml+++ b/.github/workflows/ci-python.yml@@ -66,6 +66,7 @@ jobs:# hogli CLI changes need validation- 'tools/hogli/**'- 'tools/hogli-commands/hogli_commands/**'+ - 'tools/owners/**'- 'hogli.yaml'- 'bin/**'# Dev tools with dedicated pytest steps below@@ -194,6 +195,11 @@ jobs:run: |pytest tools/hogli-commands/hogli_commands/tests -v --junitxml=junit-hogli-commands.xml+ - name: Run owners resolver tests+ shell: bash+ run: |+ pytest tools/owners/tests -v --junitxml=junit-owners.xml+- name: Run query-performance-ai testsshell: bashrun: |@@ -212,6 +218,7 @@ jobs:path: |junit-hogli.xmljunit-hogli-commands.xml+ junit-owners.xmljunit-query-performance-ai.xmljunit-pr-approval-agent.xmldiff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.ymlindex 8916dd8d7984..8a0964a54ba1 100644--- a/.github/workflows/ci-scripts.yml+++ b/.github/workflows/ci-scripts.yml@@ -63,6 +63,9 @@ jobs:- name: PR title labeler tests (Node)run: node --test .github/scripts/label-pr-from-title.test.js+ - name: Auto-assign reviewers tests (Node)+ run: node --test .github/scripts/assign-reviewers.test.js+- name: CI report section tests (Node)run: node --test .github/scripts/post-ci-sections.test.mjsdiff --git a/.stamphog/README.md b/.stamphog/README.mdindex 06b671811114..11ad874373c1 100644--- a/.stamphog/README.md+++ b/.stamphog/README.md@@ -6,7 +6,7 @@ Engine and policy are vendored into other repos (see the note in `tools/pr-appro## What lives here-- `policy.yml` - the global machine policy: deny categories, allow-list, size gate, tier thresholds, dismiss-time triviality rules, the folder delegation contract, and the ownership sources (the `gh-codeowners` and `ph-product` inputs that feed the reviewer's advisory team context, merged as a union). Trusted data. Each rule's `rationale` records why the rule became what it is (which false positives drove an exclusion, and when) - historical justification like a commit message, not a claim about the present.+- `policy.yml` - the global machine policy: deny categories, allow-list, size gate, tier thresholds, dismiss-time triviality rules, the folder delegation contract, and the ownership source (the `hogli-resolver` input that feeds the reviewer's advisory team context via the shared hogli resolver). Trusted data. Each rule's `rationale` records why the rule became what it is (which false positives drove an exclusion, and when) - historical justification like a commit message, not a claim about the present.- `review-guidance.md` - the trusted review-norms prose injected into the reviewer's system prompt. Ordinary repo-formatted markdown. Editing it changes the production prompt directly, so update deliberately - the `stamphog_policy` deny guarantees a human reviews every change.## Proposing a policy changediff --git a/.stamphog/policy.yml b/.stamphog/policy.ymlindex fbe8a80e8cd3..8999162971d2 100644--- a/.stamphog/policy.yml+++ b/.stamphog/policy.yml@@ -117,13 +117,15 @@ deny:- '\.nvmrc'stamphog_policy:description: "Stamphog's own policy files, engine, and gate inputs."- rationale: "Changes to the merge gate's own policy or engine always require human review - the gate cannot be trusted to approve edits to itself. Ownership sources (CODEOWNERS, product.yaml owners) are gate inputs: an ownership edit changes which team the reviewer treats as owning future PRs, and product.yaml would otherwise ride the .yaml allow-list to a T0 auto-approve (Jul 2026 review finding)."+ rationale: "Changes to the merge gate's own policy or engine always require human review - the gate cannot be trusted to approve edits to itself. Ownership sources (CODEOWNERS, owners.yaml, product.yaml owners) are gate inputs: an ownership edit changes which team the reviewer treats as owning future PRs, and owners.yaml/product.yaml would otherwise ride the .yaml allow-list to a T0 auto-approve (Jul 2026 review finding)."match:paths:- '\.stamphog/'- 'AGENT_APPROVALS\.md'- 'tools/pr-approval-agent/'+ - 'tools/owners/'- 'CODEOWNERS'+ - 'owners\.yaml'- 'product\.yaml'allow:path_patterns:@@ -202,16 +204,13 @@ familiarity:min_prior_prs: 5max_days_since_touch: 180# Ownership sources feeding the reviewer's team context - advisory only, never a-# gate. product.yaml is the canonical owner of products/<name>/** (per the-# CODEOWNERS-soft header), and the reviewer auto-assigner already merges both-# sources, so stamphog reads the same merged view (union across sources).-# Formats: gh-codeowners (a CODEOWNERS-soft file, last-match-wins) and ph-product-# (products/*/product.yaml owners). Sources are read from the master checkout-# (the workflow pins ref: master), so a PR editing them cannot influence its own-# review. Locators must stay repo-relative (no absolute paths, no '..').+# gate. The hogli-resolver source delegates to the shared hogli OwnersResolver,+# which walks the distributed owners.yaml / product.yaml files from the repo root+# (the `path` locator) and merges nearest-file-wins, so stamphog reads the same+# view the reviewer auto-assigner builds. Sources are read from the master+# checkout (the workflow pins ref: master), so a PR editing them cannot influence+# its own review. Locators must stay repo-relative (no absolute paths, no '..').ownership:sources:- - path: .github/CODEOWNERS-soft- format: gh-codeowners- - glob: products/*/product.yaml- format: ph-product+ - path: .+ format: hogli-resolverdiff --git a/.stamphog/review-guidance.md b/.stamphog/review-guidance.mdindex 221a04524504..f22682cd7dd5 100644--- a/.stamphog/review-guidance.md+++ b/.stamphog/review-guidance.md@@ -51,7 +51,7 @@ T1 sub-tiers (provided in the prompt):Calibrate scrutiny to the sub-tier. T1a should be quick.-Ownership (from CODEOWNERS-soft, non-blocking):+Ownership (from owners.yaml / product.yaml, non-blocking):- Author on owning team: not a concern- Author NOT on owning team: a routing signal, not a risk by itself@@ -61,7 +61,7 @@ Ownership (from CODEOWNERS-soft, non-blocking):Author familiarity (TRUSTED, computed by us from git history on the checkout):- When present, the prompt reports a familiarity band — STRONG or MODERATE — with the numbers behind it: the share of the modified lines the author last-touched, how many of the changed files they previously modified, their merged PRs in these paths over the last year, and days since their last touch. No band being reported means nothing either way — judge the PR as you always have; never treat missing familiarity as a mark against the author.-- STRONG familiarity counts like owning-team membership for the independent-assurance rule in risky territory. A change with tests and no outstanding concerns from a STRONG-familiarity author is one humans approve unchanged, even when CODEOWNERS-soft puts the files on another team.+- STRONG familiarity counts like owning-team membership for the independent-assurance rule in risky territory. A change with tests and no outstanding concerns from a STRONG-familiarity author is one humans approve unchanged, even when owners.yaml / product.yaml puts the files on another team.- MODERATE familiarity softens the ownership concern but does not replace team membership — lean it toward APPROVE on a borderline low-risk change, but on its own it does not count as assurance in risky territory.- Familiarity is judgment input, never a gate. It never overrides a deny rule or a refusal criterion, and its absence changes nothing.- When you REFUSE or ESCALATE and the prompt lists who is most familiar with the modified lines, name them as suggested reviewers in your next-steps.diff --git a/.vscode/settings.example.json b/.vscode/settings.example.jsonindex b497631e0782..a80f018768ef 100644--- a/.vscode/settings.example.json+++ b/.vscode/settings.example.json@@ -14,8 +14,7 @@"tailwindCSS.emmetCompletions": true,"tailwindCSS.rootFontSize": 16,"files.associations": {- "*.css": "tailwindcss",- "CODEOWNERS-soft": "CODEOWNERS"+ "*.css": "tailwindcss"},"mypy-type-checker.importStrategy": "fromEnvironment","mypy-type-checker.preferDaemon": true,diff --git a/Dockerfile b/Dockerfileindex c4e760408d4d..d45369d1bbd6 100644--- a/Dockerfile+++ b/Dockerfile@@ -166,6 +166,9 @@ RUN --mount=type=cache,id=uv-libxmlsec1.2.37-2,target=/root/.cache/uv \--mount=type=bind,source=uv.lock,target=uv.lock \--mount=type=bind,source=pyproject.toml,target=pyproject.toml \--mount=type=bind,source=tools/hogli,target=tools/hogli \+ # uv sync validates workspace membership even with --no-dev, so every+ # workspace member must be present in the build context.+ --mount=type=bind,source=tools/owners,target=tools/owners \uv sync --locked --no-dev --no-install-project --no-binary-package lxml --no-binary-package xmlsecENV PATH=/python-runtime/bin:$PATH \diff --git a/Dockerfile.llm-analytics b/Dockerfile.llm-analyticsindex 48243d8e1b61..43b4332862c3 100644--- a/Dockerfile.llm-analytics+++ b/Dockerfile.llm-analytics@@ -43,6 +43,9 @@ RUN --mount=type=cache,id=uv-libxmlsec1.2.37-2,target=/root/.cache/uv \--mount=type=bind,source=uv.lock,target=uv.lock \--mount=type=bind,source=pyproject.toml,target=pyproject.toml \--mount=type=bind,source=tools/hogli,target=tools/hogli \+ # uv sync validates workspace membership even with --no-dev, so every+ # workspace member must be present in the build context.+ --mount=type=bind,source=tools/owners,target=tools/owners \uv sync --locked --no-dev --no-install-project --group sentiment --no-binary-package lxml --no-binary-package xmlsec# Copy project filesdiff --git a/docs/internal/ownership-model-proposal.md b/docs/internal/ownership-model-proposal.mdnew file mode 100644index 000000000000..ccf94f7a65ab--- /dev/null+++ b/docs/internal/ownership-model-proposal.md@@ -0,0 +1,251 @@+# Repo ownership model: distributed `owners.yaml`++Status: implemented (landed with the PR that introduced this document)++Design a single ownership source of truth that multiple consumers (review automation, CI validation, lookup CLIs, service catalogs, future tools) can read, instead of each tool re-parsing `CODEOWNERS-soft` and `product.yaml` on its own.++Scope decisions (locked):++- `owners.yaml` becomes the canonical ownership format.+- `.github/CODEOWNERS-soft` is deleted; the PR-assignment flow reads the new resolver instead.+- `products/*/product.yaml` stays and is an **accepted alias** of `owners.yaml` — its `owners:` key is a first-class ownership source, all other fields are ignored for ownership purposes.+- The hard `.github/CODEOWNERS` is left alone for now: hand-maintained, GitHub-enforced, out of the schema.+- Everything lands in **one PR**.++## 1. Survey of prior art++| System | Placement | Match resolution | Roles | Inheritance control | Metadata |+| --------------------------- | ------------------- | ---------------------------- | -------------------------- | -------------------------- | ----------------------------------------------------- |+| GitHub CODEOWNERS | one central file | last-match-wins (whole file) | none | none | none |+| GitLab CODEOWNERS | one central file | last-match-wins per section | sections + `@@role` refs | section-scoped | none |+| Gerrit/Chromium OWNERS | per directory | ancestor union | none (Gerrit labels) | `set noparent`, `per-file` | sibling DIR_METADATA (component, team contact) |+| Kubernetes/Prow OWNERS | per directory, YAML | ancestor union | `approvers` vs `reviewers` | `options.no_parent_owners` | `labels`, `emeritus_approvers`, root `OWNERS_ALIASES` |+| Backstage catalog-info.yaml | per component | explicit reference, no globs | typed `spec.owner` (Group) | n/a | open-ended annotations |++Lessons that shaped this proposal:++- Central single-file systems rot via pattern-order bugs: last-match-wins makes line order load-bearing, and a broad glob added late silently swallows earlier specific rules. Our own `CODEOWNERS-soft` already relies on deliberate ordering (the managed-reverse-proxy block must stay last).+- Per-directory files match the mental model ("who owns _this_ directory") and scale with a monorepo, but need a coverage audit tool since nothing forces a new directory to get an owner.+- The approver/reviewer split (Kubernetes) is the single most useful role distinction: "can gate a merge" vs "should see this PR" are different sets. We already have exactly this split — hard `CODEOWNERS` vs soft — just encoded as two separate files with different formats and different consumers.+- Chromium separates approval (OWNERS) from routing metadata (DIR_METADATA: team contact, bug component). Keeping "who approves" and "who to page/ping" in one schema but different fields avoids a second file.+- Kubernetes avoids GitHub Teams for grouping (no audit trail for membership) via a PR-reviewable `OWNERS_ALIASES` file. We _do_ want GitHub team slugs (the auto-assigner needs them), and we deliberately skip the alias layer: individuals appear inline as `@handles`, matching what `product.yaml` already allows.+- The compile-to-CODEOWNERS pattern (structured YAML as source, flat CODEOWNERS as build artifact) is common and keeps native platform integration for free.++## 2. What the repo has today++Two data sources, one shared matcher, four consumers — all hand-maintained.++**Sources**++- `.github/CODEOWNERS` (58 lines): blocking. Deliberately tiny, infra/security-critical trees only ("extraordinary justification" header). Uses owner-less lines as _resets_ to clear a blocking owner for a subtree (e.g. `posthog/hogql/database/schema/**`).+- `.github/CODEOWNERS-soft` (383 lines): non-blocking review tagging. Carries all product mapping for shared code outside `products/` (~25 teams). Header already says: product-level ownership belongs in `product.yaml`; this file is for sub-folder overrides, secondary reviewers, and paths outside `products/`.+- `products/*/product.yaml` (68 files): exactly two fields, `name` and `owners` (list of team slugs, occasionally `@individual`). Owns all of `products/<name>/**` and beats any CODEOWNERS entry in the resolution used by the ownership skill.++**Consumers and their parsers**++| Consumer | Reads | Parser |+| --------------------------------------------------------- | -------------------------- | ------------------------------------------------------------------------- |+| `.github/scripts/assign-reviewers.js` (CI auto-assign) | soft + product.yaml | vendored matcher + own YAML mini-parser |+| `hogli product:lint:owners` | product.yaml | own loader (`product_yaml.py`), validates slugs against live GitHub teams |+| `.agents/skills/establishing-code-ownership/ownership.js` | hard + soft + product.yaml | vendored matcher + own YAML mini-parser |+| `tools/pr-approval-agent/gates.py` | soft only | fully independent reimplementation |++The vendored matcher is `.github/scripts/codeowners.js` (a port of `hmarr/codeowners`, faithful to GitHub semantics).++**Gaps**++- Four parsers of the same two files; only two share the matcher. Drift is a when, not an if.+- Only `product.yaml` is CI-validated. Nothing checks that `CODEOWNERS-soft` globs still match existing files or that its team slugs exist (the assigner discovers dead teams at runtime via 422s).+- No schema for `product.yaml`; no oncall/Slack/escalation routing anywhere in the repo (handbook only).+- Consumers disagree about scope: the assigner and pr-approval-agent ignore the hard file; only the skill layers all three sources.+- No structured notion of generated/vendored/deprecated code — the assigner hardcodes an ignore list (`frontend/src/generated/**`, `*.ambr`, lockfiles, …).++## 3. Proposed canonical format: `owners.yaml`++One schema, distributed per directory. Under `products/`, the existing `product.yaml` **is** the ownership file (see the alias rule below) — no new files needed there.++```yaml+# owners.yaml — full form; every field except `owners` is optional+version: 1++# The one required field, same key and semantics as product.yaml.+# Ordered, mixed list of GitHub team slugs (minus @PostHog/) and+# '@handles'; the first entry is the primary owner, used for defaults+# like the derived Slack channel (see the `teams:` registry below).+# A single owner can be written bare: `owners: team-error-tracking`.+# Owners are tagged for review (non-blocking) and are the answer to+# "who owns this path".+owners: [team-error-tracking, '@pauldambra']++# Lifecycle of the code under this directory.+# active (default) | deprecated | generated | vendored+status: active++# When true (default), fields not set here fall through to the nearest+# ancestor owners.yaml. false = Gerrit's `set noparent`.+inherit: true++# Per-path overrides inside this directory, evaluated last-match-wins+# *within this file only*. owners, status, and inherit can be overridden+# per rule. `match` is one glob or a list of globs (each is its own+# boundary — the list is just shorthand for repeating owners/status).+rules:+ - match: 'generated/**'+ status: generated+ - match: 'vendor/**'+ status: vendored+ owners: null # explicit reset: unowned-by-design, lint-exempt+ - match: ['migrations/**', 'legacy/**']+ owners: [team-error-tracking, team-data-modeling]+```++The 90% case is two lines:++```yaml+# rust/owners.yaml+version: 1+owners: team-ingestion+```++### `product.yaml` as an accepted alias++`products/<name>/product.yaml` with an `owners:` key is read by the resolver as an `owners.yaml` with that same `owners:` list. Every other field in `product.yaml` (`name:` today, anything added later) is ignored for ownership purposes — `product.yaml` remains free to grow product metadata without touching the ownership schema. Rules:++- A directory may have `product.yaml`-with-`owners` **or** `owners.yaml`, never both — lint error.+- Sub-folder overrides inside a product use nested `owners.yaml` as anywhere else (e.g. `products/x/backend/migrations/owners.yaml`).+- The `team-CHANGEME` scaffold placeholder resolves to unowned, as all consumers already treat it.++This keeps all 68 products at zero migration cost and preserves `hogli product:lint:owners` unchanged.++### Slack derivation: measured, not assumed++Checked all 31 team slugs in use (CODEOWNERS + soft + product.yaml) against live Slack channels (2026-07):++- 24/31: `#<slug>` exists verbatim — every well-formed `team-*` slug.+- 3/31 (`clickhouse`, `conversations`, `batch-exports`): slug lacks the `team-` prefix but `#team-<slug>` exists — slug hygiene to fix during migration, not an override case.+- 4/31 need an explicit value: `team-posthog-code` → `#team-code`, `team-wizard` → `#team-wizard-and-docs`, `team-data-stack` → `#group-data-stack`, and `hogql`/`logs` have no team channel at all (`slack: false`).++So the derived default is right for ~87% of teams and the rest add one line to the root `teams:` registry (below). Guarding against a derived channel that doesn't exist is lint's job, not a per-file flag: `owners:lint` gets an opt-in Slack-API check mirroring the existing opt-in live GitHub-team validation.++#### The `teams:` registry (repo-root only)++The channel-to-team mapping is declared **once**, at the root, never per file — a team that owns paths across many directories should not restate its channel in each.+The **repo-root** `owners.yaml` may carry a `teams:` registry — a mapping of team slug to a single `slack` value (a string starting with `#`, or `false` to mean "no channel, don't derive"):++```yaml+# owners.yaml (repo root only)+teams:+ team-posthog-code:+ slack: '#team-code'+ team-data-stack:+ slack: '#group-data-stack'+ hogql:+ slack: false+```++`teams:` in any non-root `owners.yaml` is a schema error, and `product.yaml` aliases never carry it.+There is no per-path or per-file Slack override — the registry (plus the derived default) is the only way a channel is set.++The effective Slack channel for a path is resolved by this precedence chain, first match wins:++1. the registry entry for the **primary owner** (`owners[0]`), but only when it is a team slug (not an `@handle`) — a `false` entry suppresses derivation;+2. the derived `#<owners[0]>` when the primary owner is a team slug;+3. otherwise `None`.++The registry only changes how the resolver computes the channel; the wire format is unchanged — `slack` still flows through as the final string or `null`.++### Individuals, no alias layer++There is no `OWNERS_ALIASES` file. `owners:` takes GitHub team slugs or `@handles` directly — the same convention `product.yaml` already uses for `user_interviews`. Lint validates handles against org membership the same way it validates team slugs. The auto-assigner requests individual reviewers through the API's `reviewers` field (it currently skips `@`-entries entirely, so individuals only work via `CODEOWNERS-soft` today — this closes that gap and lets the soft-file wiring die with the file).++### Design choices, argued++- **Distributed, not central.** The repo already voted: `product.yaml` is per-directory and the soft file's own header pushes ownership toward it. Central files are what we're escaping (ordering bugs, merge conflicts on one hot file). The audit story ("show me everything") is a tool's job (`hogli owners:map`), not a file layout's.+- **Nearest-file-wins with per-field fallthrough, not ancestor union.** Kubernetes unions approvers up the tree because its bar is "someone must approve"; our soft model is "tag the right team, don't spam five". Union inheritance would tag `posthog/` owners on every deep PR. Override semantics also match what the ownership skill already implements (product.yaml beats CODEOWNERS). Fallthrough is per field: a child file that only sets `owners` still inherits `status` from its ancestor.+- **`rules:` are file-local.** Cross-file glob interactions are the CODEOWNERS footgun; here a glob can only override its own directory's defaults, so reading one file plus its ancestors fully explains any path.+- **`owners: null` is explicit, not absent.** Unowned must be a decision (vendored code, scratch dirs), never a default. The coverage check treats missing resolution as an error and `owners: null` as an exemption with a paper trail.+- **One `owners` list, no role split.** A `team`-vs-`reviewers` distinction (Kubernetes-style) was considered and dropped: with blocking out of scope, "who is responsible" and "who gets tagged" are the same set, and product.yaml already speaks `owners`. Ordering carries the only extra signal needed — first entry is the primary owner. A blocking role, if ever needed, is a new field later, not a split now.+- **`status:` replaces hardcoded ignore lists.** The assigner's generated-file ignore list, review-noise suppression, and future tooling (e.g. excluding vendored code from lint) all key off one field instead of N copies.++## 4. Resolution model++For a path `P`:++1. Walk from the repo root toward `P`, collecting every `owners.yaml` (or aliased `product.yaml`) on the way. If a file sets `inherit: false`, drop everything collected above it.+2. Effective config = shallow merge, nearest file winning per field (lists replace, never merge — predictability over cleverness).+3. Within the nearest file that has `rules:`, apply the last rule whose `match` glob (gitignore-style semantics, documented with the schema) matches `P` relative to that file's directory. Rule fields override the merged config.+4. Review tagging = resolved `owners`. Primary owner = its first entry.+5. No ownership file on the walk and no rule match → **unowned**, which fails the coverage check unless the path is under an `owners: null` rule.++**Consolidation vs distribution is a readability choice, not a semantic one.** A parent `owners.yaml` may own subtrees through anchored directory rules (`- match: '/rust/capture/'`), and a deeper `owners.yaml` still wins by nearest-file resolution. So a cluster of one-line child files and a single parent file with equivalent rules resolve identically; pick whichever reads better for that tree. `owners:lint` nudges toward folding when a directory accumulates enough single-purpose children.++The hard `.github/CODEOWNERS` stays outside this walk entirely. It keeps its own GitHub-native semantics and remains hand-maintained and GitHub-enforced; the resolver does **not** read it — blocking ownership is consulted manually (or via GitHub's own UI) when needed. It never influences the resolved `owners`, and nothing in this proposal writes to it.++## 5. Tool independence: one resolver, many consumers++The stability guarantee is architectural: **consumers never parse ownership files themselves.** One resolver library owns the semantics; everything else calls it.++- **Resolver**: single implementation in the installable `posthog-owners` package at `tools/owners/` exposing `resolve(path)`, `map()`, `unowned()` as a library, and `hogli owners:resolve --json <path...>` (paths also accepted on stdin) as the CLI. Rationale: hogli already lints ownership, and two of the four consumers are Python, so this makes lint, lookup, and the pr-approval agent native library callers with zero subprocess hops. Glob matching for `rules:` uses gitignore-style semantics implemented (and documented) here — the vendored JS matcher stays only for the hard-CODEOWNERS overlay parsing, or is replaced by an equivalent Python CODEOWNERS parser.+- **JS consumers** shell out to the CLI and read JSON — `assign-reviewers.js` feeds the PR's changed files in and gets resolved owners back; the `establishing-code-ownership` skill does the same. The auto-assign workflow gains a Python/uv setup step (it is node-only today). `gates.py` imports the library directly. No committed lock file, so no freshness-check machinery; if one is ever wanted (offline consumers, Backstage `catalog-info.yaml` emitters), it is a trivial fold over `map()` added later.+- **Validator**: `hogli owners:lint` — schema check, team slugs and `@handles` against the live GitHub org (reusing `product/gh.py`), dead `rules:` globs (match zero files), same-directory `product.yaml`/`owners.yaml` conflicts, reserved-location rejection (see below), and full-tree coverage (every `git ls-files` path resolves or is `owners: null`). It also prints advisory consolidation suggestions when it spots a cluster of single-purpose owners.yaml files a single parent could absorb (never affects the exit code).++**Reserved locations.** `owners.yaml` must not live in a directory whose own tooling globs every YAML file there — GitHub Actions/actionlint treat everything under `.github/workflows/` as a workflow, and the `services/mcp` generate-tools step globs YAML configs under `products/*/mcp/`. Lint rejects `owners.yaml` in those spots; hoist the ownership into the parent's `rules:` instead (e.g. a `/workflows/` rule in `.github/owners.yaml`).++- **Lookup**: `hogli owners:who <path>` / `owners:team <slug>` / `owners:unowned` — thin wrappers over the library; the `establishing-code-ownership` skill's `ownership.js` becomes a shim over the CLI (or is deleted in favor of it).++One tradeoff to acknowledge: today `.github/scripts/` sits behind the blocking `CODEOWNERS` (`team-security`), so changes to assignment logic require their approval. Moving the resolver out of `.github/scripts/` takes it out of that gate. Done — the resolver package (`tools/owners/posthog_owners/`) is under the blocking file, a deliberate exception to "leave CODEOWNERS alone" since the auto-assigner executes it on `pull_request_target`.++If the first consumer (say the auto-assigner) is ever replaced, the resolver, schema, and lint are untouched — only one caller changes. That is the "source of truth, not tool config" property.++### Portability: repo = data, app = resolver++Nothing in the resolver is PostHog-specific — `owners.yaml` is a repo-agnostic format, and the library needs only pyyaml and a way to load files.+That is why it ships as the standalone, installable `tools/owners` package (`posthog-owners`), which any repo can run without vendoring: `uvx --from "git+https://github.com/PostHog/posthog#subdirectory=tools/owners" owners lint`.+That last part is the seam: resolution walks an abstract file map, not the filesystem (the `owners:fmt` equivalence proof already runs the real resolver over an in-memory layout).+So when a consumer like stamphog becomes a hosted app that other repos enable without adding any code, the model is: **the repo contributes only ownership data; the resolver ships inside the app.**+A hosted reviewer fetches the default-branch tree (one API call), pulls just the ownership files (a few dozen blobs, cacheable per commit SHA), and resolves in-process.+Repos without `owners.yaml` fall back to a `CODEOWNERS` loader behind the same resolver interface — the glob semantics here are CODEOWNERS semantics already — and a repo with neither is simply unowned.++Two properties carry over intact.+Ownership is always read from the default branch, never the PR head, so a PR cannot rewrite ownership to approve itself.+And ownership _content_ stays in git even when enablement moves to a UI — a far-away ownership store is exactly what rots (§2); the UI configures which source and branch, never the data.++## Canonical placement (`owners:fmt`)++Because consolidation is a readability choice and not a semantic one (§4), the tree has many layouts that resolve identically, and it drifts between them as people fold and split by hand.+`owners:fmt` names the drift: it models ownership as a piecewise-constant function on the directory tree, where each `match`/`owners` statement is one _boundary_ (a change point) and the physical file that carries it is pure presentation.+Placing statements onto files optimally is a **capacitated facility-location** problem on the tree — open a file where a cluster of boundaries makes a dedicated file cheaper than carrying them all up as ancestor rules, otherwise fold them into the nearest existing carrier.++The cost model lives in module constants, so "canonical" is defined only relative to them: `ALPHA` (the price of a dedicated simple `owners.yaml` existing at all — pinned carriers like `product.yaml` manifests, non-simple files, glob files, and the repo root are free because they exist anyway), `GAMMA` (the per-level price of carrying a statement as an ancestor rule), and `MAX_RULES` (the split cap that forces a dedicated child file once a carrier gets too dense).+Glob rules are crosscutting rather than tree boundaries, so any file carrying one is pinned and passes through untouched.+Every run ends with a built-in equivalence proof: the proposed layout is simulated in memory and every tracked path re-resolved against it, which must match the current resolution exactly — a mismatch is a bug in `fmt`, not a suggestion.++`owners:fmt` is a **read-only oracle** — it never writes, and there is no `--write` flag.+The division of labor: `owners:lint`'s fold/split suggestions are the everyday incremental mechanism (with hysteresis, so small clusters don't thrash), `fmt` is the drift oracle you consult deliberately, and an actual reflow of files is a human decision, not something a formatter should apply on save.++## 6. The one PR++Everything lands atomically. The delivery order below is a review guide, not a merge sequence.++1. **Resolver + schema.** `tools/owners/` (resolution per §4), `hogli owners:resolve --json`, JSON-schema for `owners.yaml`.+2. **Convert `CODEOWNERS-soft` → distributed `owners.yaml`.** Mechanical translation of the 383 lines into per-directory files under `posthog/`, `frontend/src/scenes/`, `nodejs/`, `rust/`, `services/`, `ee/`, plugin-server, etc. Where the soft file relied on last-match ordering (e.g. the trailing managed-reverse-proxy block overriding a broad settings-scene rule), that intent becomes an explicit nested file or `rules:` entry — order-independence is the point. This was driven by a one-shot converter that ran during the PR and was removed once the conversion landed (it remains in the branch history).+3. **Equivalence proof.** A differ resolved every `git ls-files` path under (old: soft + product.yaml) and (new: owners.yaml + product.yaml) and asserted identical reviewer sets. It ran during the PR to verify the migration and was removed once the conversion landed; intentional divergences (there were a few — dead globs, stale teams the 422 fallback already skips) were listed explicitly in the PR description rather than slipping through.+4. **Flip consumers.**+ - `assign-reviewers.js`: replace soft-file parsing + `loadProductYamlRules` with a call to `hogli owners:resolve --json` (workflow gains a Python setup step). Substantive-owner thresholds, 5-team cap, comment/label behavior unchanged; `@handle` owners become individual review requests instead of being skipped. `status: generated` replaces the hardcoded ignore list.+ - `gates.py`: replace the private CODEOWNERS-soft parser with a direct library import.+ - `ownership.js` (skill): becomes a shim over the CLI; SKILL.md updated.+5. **Delete `.github/CODEOWNERS-soft`.** Also drop its entry from anything referencing it.+6. **Lint wiring.** `hogli owners:lint` + a CI job (extend the existing `validate-product-yamls` job rather than adding a new one). Coverage starts warn-only; ratchet to fail in a follow-up once `owners:unowned` is clean or explicitly `owners: null`.++Safety properties of the atomic switch:++- `auto-assign-reviewers.yml` runs on `pull_request_target` and always checks out **master**, so the new flow activates only at merge — no half-migrated window, and in-flight unrebased PRs are unaffected (the repo's CI-backwards-compat rule holds by construction).+- The hard `CODEOWNERS` and GitHub's native enforcement are untouched, so worst case on a resolver bug is wrong _soft_ tagging, which is recoverable and non-blocking.+- The equivalence differ is the review artifact: reviewers approve a proven-identical resolution plus an explicit list of intentional diffs, not 400 lines of glob translation on faith.++## 7. Open questions for maintainers++1. **Oncall routing**: resolved — dropped from v1. The Slack channel costs nothing (derived from the team slug by convention, with the root `teams:` registry overriding or setting `slack: false` where needed), but nothing consumes an oncall reference, so it is not carried. Re-adding it is additive once a consumer exists.+2. **Resolver ownership**: resolved — the resolver package is covered by the hard `CODEOWNERS` (see §5).+3. **Coverage gating cadence**: how soon after the PR to flip `owners:lint` coverage from warn to fail — immediately for _new_ directories (ratchet), or only once the whole tree is clean?+4. **Hard-CODEOWNERS future** (explicitly out of scope now): if blocking gates ever move into the schema, approver inheritance should probably union up the tree rather than nearest-wins — parked until `team-security` wants to revisit.diff --git a/ee/owners.yaml b/ee/owners.yamlnew file mode 100644index 000000000000..18896202cda4--- /dev/null+++ b/ee/owners.yaml@@ -0,0 +1,19 @@+version: 1+owners: []+rules:+ - match: ['/api/billing.py', '/billing/']+ owners: team-billing+ - match: '/clickhouse/materialized_columns/'+ owners: team-analytics-platform+ - match: ['/clickhouse/queries/related_actors_query.py', '/clickhouse/views/groups.py']+ owners: team-product-analytics+ - match: '/hogai/'+ owners: team-self-driving+ - match: '/session_recordings/'+ owners: team-replay+ - match: '/support_sidebar_max/'+ owners: team-self-driving+ - match: '/surveys/'+ owners: team-surveys+ - match: '/tasks/subscriptions/'+ owners: team-analytics-platformdiff --git a/frontend/src/lib/components/owners.yaml b/frontend/src/lib/components/owners.yamlnew file mode 100644index 000000000000..813403793f6c--- /dev/null+++ b/frontend/src/lib/components/owners.yaml@@ -0,0 +1,9 @@+version: 1+owners: []+rules:+ - match: '/ReverseProxyChecker/'+ owners: team-platform-features+ - match: '/RichContentEditor/'+ owners: team-data-tools+ - match: '/heatmaps/'+ owners: team-web-analyticsdiff --git a/frontend/src/scenes/owners.yaml b/frontend/src/scenes/owners.yamlnew file mode 100644index 000000000000..58fb1c21c5fc--- /dev/null+++ b/frontend/src/scenes/owners.yaml@@ -0,0 +1,97 @@+version: 1+owners: []+rules:+ - match: '/FeatureFlagPermissions.tsx'+ owners: team-feature-flags+ - match: '/actions/'+ owners: team-product-analytics+ - match: '/activity/'+ owners: team-platform-features+ - match: '/agentic/'+ owners: team-growth+ - match: '/alerts/'+ owners: team-analytics-platform+ - match: '/annotations/'+ owners: team-product-analytics+ - match: ['/approvals/', '/audit-logs/', '/authentication/']+ owners: team-platform-features+ - match: '/billing/'+ owners: team-billing+ - match: '/cohorts/'+ owners: team-feature-flags+ - match: '/comments/'+ owners: team-platform-features+ - match: '/coupons/'+ owners: team-billing+ - match: '/dashboard/'+ owners: team-analytics-platform+ - match: '/data-management/'+ owners: team-warehouse-sources+ - match: '/data-management/schema/'+ owners: team-analytics-platform+ - match: '/data-pipelines/'+ owners: team-workflows+ - match: '/data-warehouse/'+ owners: team-data-stack+ - match: '/experiments/'+ owners: team-experiments+ - match: '/exports/'+ owners: team-analytics-platform+ - match: '/feature-flags/'+ owners: team-feature-flags+ - match: ['/funnels/', '/groups/']+ owners: team-product-analytics+ - match: '/health-alerts/'+ owners: team-analytics-platform+ - match: '/health/'+ owners: team-growth+ - match: '/heatmaps/'+ owners: team-web-analytics+ - match: '/hog-functions/'+ owners: team-workflows+ - match: '/inbox/'+ owners: team-self-driving+ - match: '/insights/'+ owners: team-product-analytics+ - match: '/instance/'+ owners: team-growth+ - match: '/instance/QueryPerformance/'+ owners: team-experiments+ - match: '/marketing-analytics/'+ owners: team-web-analytics+ - match: '/max/'+ owners: team-self-driving+ - match: '/models/'+ owners: team-data-modeling+ - match: '/notebooks/'+ owners: team-data-tools+ - match: ['/oauth/', '/onboarding/']+ owners: team-growth+ - match: '/onboarding/legacy/sdks/ai-observability/'+ owners: team-ai-observability+ - match: '/onboarding/legacy/sdks/surveys/'+ owners: team-surveys+ - match: '/organization/'+ owners: team-growth+ - match: ['/paths-v2/', '/paths/', '/persons-management/', '/persons/']+ owners: team-product-analytics+ - match: ['/project-homepage/', '/project/']+ owners: team-growth+ - match: '/resource-transfer/'+ owners: team-platform-features+ - match: ['/retention/', '/saved-insights/']+ owners: team-product-analytics+ - match: '/session-recordings/'+ owners: team-replay+ - match: '/sessions/'+ owners: team-analytics-platform+ - match: ['/settings/', '/startups/']+ owners: team-growth+ - match: '/surveys/'+ owners: team-surveys+ - match: ['/themes/', '/trends/']+ owners: team-product-analytics+ - match: '/web-analytics/'+ owners: team-web-analytics+ - match: ['/welcome/', '/wizard/']+ owners: team-growthdiff --git a/frontend/src/scenes/settings/environment/owners.yaml b/frontend/src/scenes/settings/environment/owners.yamlnew file mode 100644index 000000000000..af5e84ace376--- /dev/null+++ b/frontend/src/scenes/settings/environment/owners.yaml@@ -0,0 +1,9 @@+version: 1+owners: []+rules:+ - match: ['/ManagedReverseProxy.tsx', '/ProxySDKSetup.tsx']+ owners: team-platform-features+ - match: '/SurveySettings.tsx'+ owners: team-surveys+ - match: ['/proxyLogic.test.ts', '/proxyLogic.ts']+ owners: team-platform-featuresdiff --git a/frontend/src/toolbar/owners.yaml b/frontend/src/toolbar/owners.yamlnew file mode 100644index 000000000000..f97d25a8cd06--- /dev/null+++ b/frontend/src/toolbar/owners.yaml@@ -0,0 +1,9 @@+version: 1+owners: []+rules:+ - match: '/elements/heatmapToolbarMenuLogic.ts'+ owners: team-web-analytics+ - match: '/product-tours/'+ owners: team-surveys+ - match: '/web-vitals/'+ owners: team-web-analyticsdiff --git a/hogli.yaml b/hogli.yamlindex 82c4896be41e..5eb8039a020a 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -1005,6 +1005,22 @@ tools:ci:preflight:click: hogli_commands.ci_preflight:ci_preflightdescription: Catch deterministic CI failures reachable from your diff before you push (advisory; --fix, --strict)+owners:+ owners:resolve:+ click: posthog_owners.cli:cmd_resolve+ description: Resolve ownership for paths (args or newline-delimited stdin); --json for machine output+ owners:who:+ click: posthog_owners.cli:cmd_who+ description: Show who owns a single path (owners, status, slack, source)+ owners:unowned:+ click: posthog_owners.cli:cmd_unowned+ description: List unowned tracked files, respecting owners:null exemptions (optional PREFIX)+ owners:lint:+ click: posthog_owners.cli:cmd_lint+ description: Validate owners.yaml schema, product.yaml conflicts, dead globs, coverage (--live checks the GitHub org)+ owners:fmt:+ click: posthog_owners.cli:cmd_fmt+ description: Dry-run oracle showing how the owners.yaml layout differs from canonical placement (never writes)devex:devex:feedback:click: hogli_commands.feedback:devex_feedbackdiff --git a/nodejs/src/ingestion/pipelines/ai/costs/owners.yaml b/nodejs/src/ingestion/pipelines/ai/costs/owners.yamlnew file mode 100644index 000000000000..49d36647eae8--- /dev/null+++ b/nodejs/src/ingestion/pipelines/ai/costs/owners.yaml@@ -0,0 +1,5 @@+version: 1+owners: [team-ai-observability, team-ai-gateway]+rules:+ - match: ['/providers/', '/scripts/']+ owners: team-ai-gatewaydiff --git a/nodejs/src/owners.yaml b/nodejs/src/owners.yamlnew file mode 100644index 000000000000..7f3a6827af97--- /dev/null+++ b/nodejs/src/owners.yaml@@ -0,0 +1,13 @@+version: 1+owners: []+rules:+ - match: '/ai-observability/'+ owners: team-ai-observability+ - match: '/cdp/'+ owners: team-workflows+ - match: '/ingestion/'+ owners: team-ingestion+ - match: '/ingestion/pipelines/sessionreplay/'+ owners: [team-replay, team-ingestion]+ - match: '/session-replay/recording-rasterizer/'+ owners: team-replaydiff --git a/owners.yaml b/owners.yamlnew file mode 100644index 000000000000..28841be3605c--- /dev/null+++ b/owners.yaml@@ -0,0 +1,58 @@+version: 1+owners: []+rules:+ - match: Dockerfile.llm-analytics+ owners: team-ai-observability+ - match:+ - Dockerfile+ - 'docker-compose*.yml'+ - '.prettierrc'+ - '.test_quarantine.json'+ - hogli.yaml+ - tach.toml+ - CLAUDE.md+ - AGENTS.md+ - bin/+ - greptile.json+ # Every owners.yaml routes to devex (unanchored: matches at any depth)+ # unless a nearer file or rule claims it — ownership-policy edits must+ # never go out for review unassigned.+ - owners.yaml+ owners: team-devex+ - match: '/.agents/skills/manage-dashboard-widgets/'+ owners: team-analytics-platform+ - match: '/.claude/'+ owners: team-devex+ - match: '/.claude/agents/ingestion/'+ owners: team-ingestion+ - match: '/bin/start-llm-gateway'+ owners: [team-devex, team-ai-gateway]+ - match: '/cli/'+ owners: team-error-tracking+ - match: '/docs/onboarding/ai-observability/'+ owners: team-ai-observability+ - match: '/docs/published/handbook/engineering/developing-locally.md'+ owners: team-devex+ - match: '/nodejs/tests/'+ owners: team-ingestion+ - match: '/posthog/helpers/email_utils.py'+ owners: team-platform-features+ - match: '/posthog/management/commands/find_enum_collisions.py'+ owners: team-devex+ - match: '/posthog/settings/data_warehouse.py'+ owners: team-data-stack+ - match: '/posthog/settings/email.py'+ owners: team-platform-features+ - match: '/posthog/test/test_feature_flag_analytics.py'+ owners: team-feature-flags+ - match: '/services/llm-gateway/'+ owners: team-ai-gateway+ - match:+ - '/tools/hogli-commands/'+ - '/tools/hogli/'+ - '/tools/owners/'+ - '/tools/phrocs/'+ - '/tools/pr-approval-agent/'+ owners: team-devex+ - match: '/tools/query-performance-ai/'+ owners: team-analytics-platformdiff --git a/posthog/api/owners.yaml b/posthog/api/owners.yamlnew file mode 100644index 000000000000..0cafbc9878e0--- /dev/null+++ b/posthog/api/owners.yaml@@ -0,0 +1,21 @@+version: 1+owners: []+rules:+ - match: '/cohort.py'+ owners: team-feature-flags+ - match: '/comments.py'+ owners: team-platform-features+ - match: '/documentation.py'+ owners: team-devex+ - match: ['/element.py', '/event.py', '/event_definition.py']+ owners: team-product-analytics+ - match: '/mixins.py'+ owners: team-devex+ - match: '/person.py'+ owners: team-product-analytics+ - match: ['/proxy_record.py', '/proxy_record_diagnostics.py', '/resource_transfer.py']+ owners: team-platform-features+ - match: '/schema_property_group.py'+ owners: team-analytics-platform+ - match: ['/test/test_proxy_record.py', '/test/test_proxy_record_diagnostics.py']+ owners: team-platform-featuresdiff --git a/posthog/dags/locations/owners.yaml b/posthog/dags/locations/owners.yamlnew file mode 100644index 000000000000..c5dac9cd0370--- /dev/null+++ b/posthog/dags/locations/owners.yaml@@ -0,0 +1,5 @@+version: 1+owners: []+rules:+ - match: '/analytics*platform.py'+ owners: team-analytics-platformdiff --git a/posthog/dags/owners.yaml b/posthog/dags/owners.yamlnew file mode 100644index 000000000000..1fc2de0dd565--- /dev/null+++ b/posthog/dags/owners.yaml@@ -0,0 +1,11 @@+version: 1+owners: []+rules:+ - match:+ - '/detach_distinct_id.py'+ - '/fix_missing_person_overrides.py'+ - '/fix_person_id_overrides.py'+ - '/person_property_reconciliation.py'+ owners: team-ingestion+ - match: '/sessions.py'+ owners: team-analytics-platformdiff --git a/posthog/hogql/database/schema/owners.yaml b/posthog/hogql/database/schema/owners.yamlnew file mode 100644index 000000000000..e236eceace27--- /dev/null+++ b/posthog/hogql/database/schema/owners.yaml@@ -0,0 +1,9 @@+version: 1+owners: []+rules:+ - match: '/heatmaps.py'+ owners: team-web-analytics+ - match: '/ai_events.py'+ owners: team-ai-observability+ - match: '/sessions*.py'+ owners: team-analytics-platformdiff --git a/posthog/hogql_queries/owners.yaml b/posthog/hogql_queries/owners.yamlnew file mode 100644index 000000000000..0f8d653b721c--- /dev/null+++ b/posthog/hogql_queries/owners.yaml@@ -0,0 +1,21 @@+version: 1+owners: []+rules:+ - match: '/actors_query_runner.py'+ owners: team-product-analytics+ - match: '/ai/'+ owners: team-ai-observability+ - match: '/document_embeddings_query_runner.py'+ owners: team-self-driving+ - match: '/endpoints/'+ owners: team-data-modeling+ - match: ['/events_query_runner.py', '/groups/']+ owners: team-product-analytics+ - match: '/hogql_cohort_query.py'+ owners: team-feature-flags+ - match: '/hogql_query_runner.py'+ owners: team-data-tools+ - match: ['/insights/', '/property_values_query_runner.py']+ owners: team-product-analytics+ - match: ['/sessions_query_runner.py', '/sessions_timeline_query_runner.py']+ owners: team-analytics-platformdiff --git a/posthog/models/owners.yaml b/posthog/models/owners.yamlnew file mode 100644index 000000000000..1c510af9e77c--- /dev/null+++ b/posthog/models/owners.yaml@@ -0,0 +1,31 @@+version: 1+owners: []+rules:+ - match: '/action/'+ owners: team-product-analytics+ - match: '/activity_logging/'+ owners: team-platform-features+ - match: '/ai/'+ owners: team-self-driving+ - match: '/ai_events/'+ owners: team-ai-observability+ - match: '/channel_type/'+ owners: team-web-analytics+ - match: '/cohortmembership/'+ owners: team-feature-flags+ - match: '/comment/'+ owners: team-platform-features+ - match: '/messaging.py'+ owners: team-workflows+ - match: '/person/'+ owners: team-ingestion+ - match: '/proxy_record.py'+ owners: team-platform-features+ - match: '/raw_sessions/'+ owners: team-analytics-platform+ - match: '/resource_transfer/'+ owners: team-platform-features+ - match: '/sessions/'+ owners: team-analytics-platform+ - match: '/web_preaggregated/'+ owners: team-web-analyticsdiff --git a/posthog/owners.yaml b/posthog/owners.yamlnew file mode 100644index 000000000000..2002fef44b02--- /dev/null+++ b/posthog/owners.yaml@@ -0,0 +1,27 @@+version: 1+owners: []+rules:+ - match: '/caching/'+ owners: team-analytics-platform+ - match: '/cdp/'+ owners: team-workflows+ - match: '/email.py'+ owners: team-platform-features+ - match: '/heatmaps/'+ owners: team-web-analytics+ - match: '/hogql/'+ owners: team-data-tools+ - match: '/management/migration_analysis/'+ owners: team-devex+ - match: '/queries/'+ owners: team-analytics-platform+ - match: '/rbac/'+ owners: team-platform-features+ - match: '/taxonomy/'+ owners: team-product-analytics+ - match: '/templates/surveys/'+ owners: team-surveys+ - match: '/warehouse/'+ owners: team-data-stack+ - match: '*llm_prompt*.py'+ owners: [team-ai-observability, team-experiments]diff --git a/posthog/session_recordings/owners.yaml b/posthog/session_recordings/owners.yamlnew file mode 100644index 000000000000..79d54bd2b037--- /dev/null+++ b/posthog/session_recordings/owners.yaml@@ -0,0 +1,5 @@+version: 1+owners: []+rules:+ - match: '/**/*.py'+ owners: team-replaydiff --git a/posthog/tasks/owners.yaml b/posthog/tasks/owners.yamlnew file mode 100644index 000000000000..1e82c8046d0a--- /dev/null+++ b/posthog/tasks/owners.yaml@@ -0,0 +1,28 @@+version: 1+owners: []+rules:+ - match: '/ai_observability_usage_report.py'+ owners: team-ai-observability+ - match: '/alerts/'+ owners: team-analytics-platform+ - match: ['/calculate_cohort.py', '/early_access_feature.py']+ owners: team-feature-flags+ - match: ['/email.py', '/email_utils.py']+ owners: team-platform-features+ - match: '/split_person.py'+ owners: team-ingestion+ - match: '/stop_surveys_reached_target.py'+ owners: team-surveys+ - match: '/sync_billing.py'+ owners: team-billing+ - match: '/test/test_ai_observability_usage_report.py'+ owners: team-ai-observability+ - match:+ - '/test/test_stop_surveys_reached_target.py'+ - '/test/test_update_survey_adaptive_sampling.py'+ - '/test/test_update_survey_iteration.py'+ - '/update_survey_adaptive_sampling.py'+ - '/update_survey_iteration.py'+ owners: team-surveys+ - match: '/usage_report.py'+ owners: team-billingdiff --git a/posthog/templates/email/owners.yaml b/posthog/templates/email/owners.yamlnew file mode 100644index 000000000000..04a3ed6a1b8b--- /dev/null+++ b/posthog/templates/email/owners.yaml@@ -0,0 +1,7 @@+version: 1+owners: []+rules:+ - match: '/ai_observability_*.html'+ owners: team-ai-observability+ - match: '/proxy_provisioned.html'+ owners: team-platform-featuresdiff --git a/posthog/temporal/owners.yaml b/posthog/temporal/owners.yamlnew file mode 100644index 000000000000..cb1b7b3743b8--- /dev/null+++ b/posthog/temporal/owners.yaml@@ -0,0 +1,37 @@+version: 1+owners: []+rules:+ - match: '/ai_observability/'+ owners: team-ai-observability+ - match: '/alerts/'+ owners: team-analytics-platform+ - match: '/data_modeling/'+ owners: team-data-modeling+ - match: '/delete_persons/'+ owners: team-ingestion+ - match: '/experiments/'+ owners: team-experiments+ - match: '/exports/'+ owners: team-analytics-platform+ - match: '/logs_alerting/'+ owners: logs+ - match: '/mcp_analytics/'+ owners: team-mcp-analytics+ - match: '/messaging/'+ owners: team-workflows+ - match: '/product_analytics/'+ owners: team-product-analytics+ - match: '/proxy_service/'+ owners: team-platform-features+ - match: '/quota_limiting/'+ owners: team-billing+ - match: '/session_replay/'+ owners: team-replay+ - match: '/sync_person_distinct_ids/'+ owners: team-ingestion+ - match: '/tests/weekly_digest/'+ owners: team-growth+ - match: '/usage_report/'+ owners: team-billing+ - match: '/weekly_digest/'+ owners: team-growthdiff --git a/products/ai_observability/backend/owners.yaml b/products/ai_observability/backend/owners.yamlnew file mode 100644index 000000000000..9d62fa04113e--- /dev/null+++ b/products/ai_observability/backend/owners.yaml@@ -0,0 +1,7 @@+version: 1+owners: []+rules:+ - match: ['/api/proxy.py', '/api/test/test_proxy.py']+ owners: team-ai-gateway+ - match: '/models/llm_prompt.py'+ owners: [team-ai-observability, team-experiments]diff --git a/products/ai_observability/frontend/prompts/owners.yaml b/products/ai_observability/frontend/prompts/owners.yamlnew file mode 100644index 000000000000..d97492f4798d--- /dev/null+++ b/products/ai_observability/frontend/prompts/owners.yaml@@ -0,0 +1,2 @@+version: 1+owners: [team-ai-observability, team-experiments]diff --git a/products/metrics/product.yaml b/products/metrics/product.yamlindex a80602d01a15..06ea2e7cc855 100644--- a/products/metrics/product.yaml+++ b/products/metrics/product.yaml@@ -1,3 +1,3 @@name: Metricsowners:- - team-devex+ - logsdiff --git a/products/product_tours/product.yaml b/products/product_tours/product.yamlindex f14f3cc5eb86..bd69707dd613 100644--- a/products/product_tours/product.yaml+++ b/products/product_tours/product.yaml@@ -1,3 +1,3 @@name: Product toursowners:- - team-growth+ - team-surveysdiff --git a/products/tracing/product.yaml b/products/tracing/product.yamlindex ade2a6759bf1..8704ad54c95d 100644--- a/products/tracing/product.yaml+++ b/products/tracing/product.yaml@@ -1,3 +1,3 @@name: Tracingowners:- - team-self-driving+ - logsdiff --git a/products/user_interviews/product.yaml b/products/user_interviews/product.yamlindex 43549f01eb41..68069e19f179 100644--- a/products/user_interviews/product.yaml+++ b/products/user_interviews/product.yaml@@ -1,8 +1,7 @@name: User interviews-# Individual owners (not a team) — quoted because YAML disallows a plain scalar-# starting with `@`. The assign-reviewers script soft-assigns these via CODEOWNERS-soft;-# product.yaml only treats team slugs as auto-reviewers, so listing people here keeps-# `owners` valid and documents ownership without tagging an unrelated team.+# Individual owners (not a team), quoted because YAML disallows a plain scalar+# starting with `@`. The ownership resolver treats `@handle` entries as individual+# owners, so these people get review-assigned without tagging an unrelated team.owners:- '@pauldambra'- '@fivestarspicy'diff --git a/products/wizard/product.yaml b/products/wizard/product.yamlindex 9d2463e350b5..39a442fc2f65 100644--- a/products/wizard/product.yaml+++ b/products/wizard/product.yaml@@ -1,3 +1,3 @@name: Wizardowners:- - team-wizard+ - team-growthdiff --git a/pyproject.toml b/pyproject.tomlindex d23be6345e82..86595dcc744c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -276,6 +276,9 @@ dev = ["testcontainers[mysql]~=4.14",# Developer CLI"hogli",+ # Distributed owners.yaml resolver — installed so hogli's owners:* commands and+ # the pr-approval gate can `import posthog_owners` from the main venv.+ "posthog-owners","libcst>=1.8.6,<2.0.0",]sentiment = [@@ -293,10 +296,11 @@ exclude-newer = "7 days"exclude-newer-package = { hogql-parser = false, hogql-parser-rs = false, posthoganalytics = false, pixelhog = false, django = false, modal = false, posthog-hogland = false }[tool.uv.workspace]-members = ["tools/hogli"]+members = ["tools/hogli", "tools/owners"][tool.uv.sources]hogli = { workspace = true }+posthog-owners = { workspace = true }infi-clickhouse-orm = { git = "https://github.com/PostHog/infi.clickhouse_orm", rev = "4e3996becf66bf5c26580aff12a80425d9d56fe5" }# pytest-split: pinned to PostHog's fork (immutable tag) for the order-preserving# optimal_chunks split. Fork: PostHog/pytest-split (of jerry-git/pytest-split).diff --git a/pytest.ini b/pytest.iniindex f9406b623130..ce310a8d6329 100644--- a/pytest.ini+++ b/pytest.ini@@ -1,5 +1,5 @@[pytest]-pythonpath = . common tools/hogli-commands tools/query-performance-ai+pythonpath = . common tools/hogli-commands tools/owners tools/query-performance-aienv =DEBUG=1TEST=1@@ -18,7 +18,7 @@ junit_family = xunit1# nothing in this repo uses the `faker` fixture or the library (faker is a transitive dep)# -p pytest_boot_gc opens the boot GC window (gc.disable) before pytest-django runs# django.setup(), which happens before conftest files load; the root conftest closes it-addopts = -p no:warnings -p no:tach -p no:langsmith_plugin -p no:faker -p pytest_boot_gc --reuse-db --pytest-durations=0 --ignore=posthog/user_scripts --ignore=services/llm-gateway --ignore=services/stripe-mock --ignore=common/ingestion/acceptance_tests --ignore=tools/hogli --ignore=tools/hogli-commands --ignore=tools/traffic-sim --ignore=tools/query-performance-ai+addopts = -p no:warnings -p no:tach -p no:langsmith_plugin -p no:faker -p pytest_boot_gc --reuse-db --pytest-durations=0 --ignore=posthog/user_scripts --ignore=services/llm-gateway --ignore=services/stripe-mock --ignore=common/ingestion/acceptance_tests --ignore=tools/hogli --ignore=tools/hogli-commands --ignore=tools/owners --ignore=tools/traffic-sim --ignore=tools/query-performance-aimarkers =eediff --git a/rust/owners.yaml b/rust/owners.yamlnew file mode 100644index 000000000000..e4421d2ee5ef--- /dev/null+++ b/rust/owners.yaml@@ -0,0 +1,30 @@+version: 1+owners: []+rules:+ - match: ['/behavioral_cohorts_migrations/', '/capture/']+ owners: team-ingestion+ - match: '/common/cookieless/'+ owners: team-web-analytics+ - match: ['/common/symbol_data/', '/cymbal-proto/', '/cymbal/']+ owners: team-error-tracking+ - match: ['/feature-flags/', '/flags-consumer/', '/flags_read_store_migrations/']+ owners: team-feature-flags+ - match: '/hogql/'+ owners: team-data-tools+ - match:+ - '/ingestion-consumer/'+ - '/kafka-assigner-proto/'+ - '/kafka-assigner/'+ - '/kafka-deduplicator/'+ - '/personhog-common/'+ - '/personhog-coordination/'+ - '/personhog-leader/'+ - '/personhog-proto/'+ - '/personhog-replica/'+ - '/personhog-router/'+ - '/personhog-writer/'+ - '/property-defs-rs/'+ - '/property-vals-rs/'+ owners: team-ingestion+ - match: '/replay-anonymizer-node/'+ owners: team-ai-researchdiff --git a/services/mcp/src/owners.yaml b/services/mcp/src/owners.yamlnew file mode 100644index 000000000000..41d048e81165--- /dev/null+++ b/services/mcp/src/owners.yaml@@ -0,0 +1,9 @@+version: 1+owners: []+rules:+ - match:+ - '/generated/ai_observability/'+ - '/tools/aiObservability/'+ - '/tools/generated/ai_observability.ts'+ - '/ui-apps/apps/generated/llm-costs.tsx'+ owners: team-ai-observabilitydiff --git a/tools/hogli-commands/hogli_commands/build.py b/tools/hogli-commands/hogli_commands/build.pyindex 508620f59369..078227a9d6ec 100644--- a/tools/hogli-commands/hogli_commands/build.py+++ b/tools/hogli-commands/hogli_commands/build.py@@ -16,13 +16,16 @@ TRIGGERS: dict[str, tuple[str, ...]] = {"frontend/src/queries/schema/*","posthog/schema_migrations/*",),+ # Python-only globs on the api/presentation trees: OpenAPI is generated from+ # code, so metadata files that live alongside it (owners.yaml) must not+ # trigger a regen."build:openapi": (- "posthog/api/*",+ "posthog/api/*.py","posthog/scopes.py",- "ee/api/*",- "products/*/backend/api/*",- "products/*/backend/presentation/*",- "products/*/backend/widget_specs/*",+ "ee/api/*.py",+ "products/*/backend/api/*.py",+ "products/*/backend/presentation/*.py",+ "products/*/backend/widget_specs/*.py","products/*/mcp/*.yaml","products/*/mcp/prompts/*","services/mcp/definitions/*",diff --git a/tools/owners/README.md b/tools/owners/README.mdnew file mode 100644index 000000000000..4194ffc9f202--- /dev/null+++ b/tools/owners/README.md@@ -0,0 +1,15 @@+# posthog-owners++Resolver, linter, and formatter for PostHog's distributed `owners.yaml` ownership model.+It walks the `owners.yaml` / `product.yaml` files a repo carries, merges them nearest-file-wins, and answers "who owns this path" as a library or CLI, plus a lint that catches schema errors, dead globs, conflicts, and coverage gaps.+The ownership format and resolution semantics are documented in [`docs/internal/ownership-model-proposal.md`](../../docs/internal/ownership-model-proposal.md) and the `establishing-code-ownership` skill.++## Use it from another repo++The package is self-contained (stdlib + pyyaml + click), so any repo carrying `owners.yaml` files can run it without vendoring anything:++```bash+uvx --from "git+https://github.com/PostHog/posthog#subdirectory=tools/owners" owners lint+```++Pin to a commit for CI so the resolver semantics can't shift under you: append `@<sha>` to the URL (`...posthog@<sha>#subdirectory=tools/owners`).diff --git a/tools/owners/posthog_owners/__init__.py b/tools/owners/posthog_owners/__init__.pynew file mode 100644index 000000000000..1b3c8fcaf392--- /dev/null+++ b/tools/owners/posthog_owners/__init__.py@@ -0,0 +1,11 @@+"""Distributed ownership: owners.yaml matcher, schema, resolver, and CLI."""++from .matcher import compile_pattern, path_matches_pattern+from .resolver import OwnersResolver, Resolution++__all__ = [+ "OwnersResolver",+ "Resolution",+ "compile_pattern",+ "path_matches_pattern",+]diff --git a/tools/owners/posthog_owners/__main__.py b/tools/owners/posthog_owners/__main__.pynew file mode 100644index 000000000000..728877400aa5--- /dev/null+++ b/tools/owners/posthog_owners/__main__.py@@ -0,0 +1,33 @@+"""Dependency-light JSON resolver entrypoint for non-Python consumers.++Reads newline-delimited repo-relative paths from stdin (or as argv) and writes a+JSON object keyed by normalized path to stdout::++ {"<path>": {"owners": [...], "status": "...", "slack": "...|null", "source": "...|null"}}++Kept off click on purpose (stdlib + pyyaml only) so a workflow can run it with+``python -m posthog_owners`` after installing just pyyaml — no hogli, no+project sync. The click CLI (``hogli owners:resolve --json``) emits the identical+shape for dev use; both build it via ``resolution_to_wire`` so there is one format.+"""++from __future__ import annotations++import sys+import json++from .matcher import normalize_path+from .resolver import OwnersResolver, read_stdin_paths, resolution_to_wire+++def main() -> None:+ args = sys.argv[1:]+ paths = args if args else read_stdin_paths()++ resolver = OwnersResolver()+ result = {normalize_path(path): resolution_to_wire(resolver.resolve(path)) for path in paths}+ json.dump(result, sys.stdout)+++if __name__ == "__main__":+ main()diff --git a/tools/owners/posthog_owners/cli.py b/tools/owners/posthog_owners/cli.pynew file mode 100644index 000000000000..b9a976b30e67--- /dev/null+++ b/tools/owners/posthog_owners/cli.py@@ -0,0 +1,302 @@+"""hogli owners:* commands — resolve, who, unowned, lint, fmt."""++from __future__ import annotations++import sys+import json+import subprocess++import click++from .matcher import compile_pattern, normalize_path+from .resolver import OWNERS_FILENAME, PRODUCT_FILENAME, OwnersResolver, read_stdin_paths, resolution_to_wire+from .schema import is_simple_owners_file, normalize_product_owners+++def _read_paths(paths: tuple[str, ...]) -> list[str]:+ """CLI paths, falling back to newline-delimited stdin when none are given."""+ if paths:+ return list(paths)+ if sys.stdin.isatty():+ return []+ return read_stdin_paths()++[email protected](name="owners:resolve", help="Resolve ownership for paths (args or newline-delimited stdin)")[email protected]("--json", "as_json", is_flag=True, help="Emit JSON keyed by path")[email protected]("paths", nargs=-1)+def cmd_resolve(as_json: bool, paths: tuple[str, ...]) -> None:+ resolver = OwnersResolver()+ targets = _read_paths(paths)+ result = {normalize_path(path): resolution_to_wire(resolver.resolve(path)) for path in targets}+ if as_json:+ click.echo(json.dumps(result, indent=2, sort_keys=True))+ return+ for path, info in result.items():+ owners = ", ".join(info["owners"]) or "(unowned)"+ click.echo(f"{path}\t{owners}\t{info['status']}\t{info['slack'] or ''}")++[email protected](name="owners:who", help="Show who owns a single path")[email protected]("path")+def cmd_who(path: str) -> None:+ r = OwnersResolver().resolve(path)+ click.echo(f"path: {r.path}")+ if r.owners:+ click.echo(f"owners: {', '.join(r.owners)}")+ elif r.unowned_by_design:+ click.echo("owners: (unowned by design — explicit owners: null)")+ else:+ click.echo("owners: (unowned)")+ click.echo(f"status: {r.status}")+ click.echo(f"slack: {r.slack or '(none)'}")+ click.echo(f"source: {r.source or '(none)'}")++[email protected](name="owners:unowned", help="List unowned tracked files (respecting owners: null exemptions)")[email protected]("prefix", required=False)+def cmd_unowned(prefix: str | None) -> None:+ resolver = OwnersResolver()+ files = resolver.tracked_files(prefix)+ unowned = resolver.unowned(files)+ for path in unowned:+ click.echo(path)+ click.echo(f"\n{len(unowned)} unowned of {len(files)} tracked file(s)", err=True)+++def _validate_owners_live(all_owners: set[str]) -> list[str]:+ """Validate team slugs and @handles against the GitHub org. Returns error strings."""+ # --live reaches back into the hogli-commands extension for the cached team-slug+ # fetch. It is a dev/CI convenience gated behind the flag, so a standalone uvx+ # install (no hogli-commands on the path) simply can't run --live; plain lint works.+ from hogli_commands.product.gh import get_team_slugs # noqa: PLC0415 — optional org-validation dep, only on --live++ errors: list[str] = []+ teams = {o for o in all_owners if not o.startswith("@")}+ handles = {o[1:] for o in all_owners if o.startswith("@")}++ valid_slugs, slug_err = get_team_slugs()+ if valid_slugs is None:+ errors.append(f"could not validate team slugs: {slug_err}")+ else:+ for slug in sorted(teams - valid_slugs):+ errors.append(f"unknown team slug: {slug}")++ for handle in sorted(handles):+ # Org membership, not mere account existence: the assigner can only+ # request reviews from members, so a non-member handle would pass a+ # users/{handle} check yet silently drop at assignment time via the+ # 422 fallback. (Repo-collaborator status would be tighter still, but+ # the app token lacks that scope — same trade-off as get_team_slugs.)+ result = subprocess.run(+ ["gh", "api", f"orgs/PostHog/members/{handle}"],+ capture_output=True,+ text=True,+ )+ if result.returncode != 0:+ errors.append(f"not a PostHog org member (unassignable): @{handle}")+ return errors+++def _reserved_location_error(rel: str) -> str | None:+ """Reject owners.yaml where other tooling globs every YAML in the directory:+ Actions/actionlint treat all of .github/workflows/ as workflows, and+ services/mcp generate-tools globs YAML in products/*/mcp/. Hoist ownership+ into the parent's rules instead."""+ if rel.startswith(".github/workflows/"):+ return f"{rel}: owners.yaml is not allowed under .github/workflows/ (Actions parses every YAML there as a workflow); move it to .github/owners.yaml rules"+ parts = rel.split("/")+ if parts[0] == "products" and "mcp" in parts[:-1]:+ return f"{rel}: owners.yaml is not allowed inside a products/*/mcp/ directory (mcp tooling globs every YAML there); move it to the product's product.yaml or a parent owners.yaml"+ return None+++def _consolidation_suggestions(owners_dirs: dict[str, bool], threshold: int = 3) -> list[tuple[str, int]]:+ """Advisory: directories that could fold a cluster of single-purpose owners.yaml+ files into one anchored ``rules:`` block.++ ``owners_dirs`` maps each owners.yaml's directory ("" = repo root) to whether it+ is simple (see ``is_simple_owners_file``). A directory D is suggested when at least+ ``threshold`` simple files sit strictly below it with no non-simple file on the+ path between (a non-simple file keeps nearest-wins correct, so its subtree stays+ put), and those files span ≥2 of D's immediate children — so D is their genuine+ branch point, not a passthrough ancestor. Only the deepest branch point per+ cluster is reported, so nested/ancestor dirs don't double-report."""++ def is_ancestor(ancestor: str, descendant: str) -> bool:+ if ancestor == descendant:+ return False+ return descendant.startswith(ancestor + "/") if ancestor else True++ non_simple = [d for d, simple in owners_dirs.items() if not simple]+ simple = [d for d, is_simple in owners_dirs.items() if is_simple]++ candidate_dirs: set[str] = {""}+ for f in simple:+ parts = f.split("/")+ for i in range(1, len(parts)):+ candidate_dirs.add("/".join(parts[:i]))++ counts: dict[str, int] = {}+ for directory in candidate_dirs:+ counted = [+ f+ for f in simple+ if is_ancestor(directory, f)+ and not any(is_ancestor(directory, ns) and is_ancestor(ns, f) for ns in non_simple)+ ]+ if len(counted) < threshold:+ continue+ children = {(f[len(directory) + 1 :] if directory else f).split("/", 1)[0] for f in counted}+ if len(children) < 2:+ continue+ counts[directory] = len(counted)++ return sorted(+ (directory, count)+ for directory, count in counts.items()+ if not any(is_ancestor(directory, other) for other in counts if other != directory)+ )++[email protected](name="owners:lint", help="Validate owners.yaml files, conflicts, dead globs, and coverage")[email protected]("--live", is_flag=True, help="Also validate team slugs and @handles against the GitHub org")+def cmd_lint(live: bool) -> None:+ resolver = OwnersResolver()+ repo_root = resolver.repo_root+ errors: list[str] = []+ warnings: list[str] = []+ all_owners: set[str] = set()+ owners_dirs: dict[str, bool] = {}++ tracked = resolver.tracked_files()+ tracked_by_dir: dict[str, list[str]] = {}+ for path in tracked:+ directory = path.rsplit("/", 1)[0] if "/" in path else ""+ tracked_by_dir.setdefault(directory, []).append(path)++ entries = resolver.parsed_ownership_files() # the single parse pass+ owners_yaml_dirs = {e.rel_dir for e in entries if e.name == OWNERS_FILENAME}++ for entry in entries:+ rel = entry.path.relative_to(repo_root).as_posix()+ directory = entry.rel_dir+ parsed = entry.parsed++ if entry.name == OWNERS_FILENAME:+ reserved_error = _reserved_location_error(rel)+ if reserved_error is not None:+ errors.append(reserved_error)++ if entry.name == PRODUCT_FILENAME:+ # Only flags a conflict; product.yaml owners are validated by product:lint:owners.+ if directory in owners_yaml_dirs:+ errors.append(f"{directory or '<root>'}: has both product.yaml (with owners) and owners.yaml")+ if parsed and parsed.owners:+ all_owners.update(normalize_product_owners(parsed.owners))+ continue++ for err in entry.errors:+ errors.append(f"{rel}: {err}")+ owners_dirs[directory] = is_simple_owners_file(parsed)+ if parsed is None:+ continue+ if parsed.owners:+ all_owners.update(parsed.owners)++ if not parsed.rules:+ continue++ # Dead rule globs: a rule matching zero tracked files under its directory.+ under_dir = (+ [p for d, files in tracked_by_dir.items() if d == directory or d.startswith(directory + "/") for p in files]+ if directory+ else tracked+ )+ # Slice paths relative to the file's directory once, not per rule.+ rel_paths = [p[len(directory) + 1 :] for p in under_dir] if directory else under_dir+ for rule in parsed.rules:+ all_owners.update(o for o in (rule.owners if isinstance(rule.owners, list) else []))+ matcher = compile_pattern(rule.match)+ if not any(matcher.test(rp) for rp in rel_paths):+ warnings.append(f"{rel}: rule '{rule.match}' matches zero tracked files (dead glob)")++ if live:+ errors.extend(_validate_owners_live(all_owners))++ unowned = resolver.unowned(tracked)+ warnings.append(f"coverage: {len(unowned)} of {len(tracked)} tracked file(s) resolve to unowned")++ for warning in warnings:+ click.echo(f"⚠ {warning}")++ # Advisory only — never affects the exit code. Points out dirs where a cluster+ # of single-purpose owners.yaml files could fold into one anchored rules block.+ for directory, count in _consolidation_suggestions(owners_dirs):+ target = f"{directory}/{OWNERS_FILENAME}" if directory else OWNERS_FILENAME+ where = directory or "<repo root>"+ click.echo(+ f"suggestion: {where} has {count} single-purpose owners.yaml files below it"+ f" — consider folding them into {target} rules"+ )++ for err in errors:+ click.echo(f"✗ {err}", err=True)++ if errors:+ click.echo(f"\n✗ {len(errors)} owners.yaml error(s)", err=True)+ raise SystemExit(1)+ click.echo(f"\n✓ owners.yaml lint passed ({len(warnings)} warning(s))")+++ name="owners:fmt",+ help="Dry-run oracle: show how the current owners.yaml layout differs from the canonical placement",+)+def cmd_fmt() -> None:+ from .fmt import ALPHA, GAMMA, MAX_RULES, CanonicalPlacer # noqa: PLC0415 — keeps the DP off the CLI import path++ placer = CanonicalPlacer(OwnersResolver())+ plan = placer.build()++ if plan.is_canonical:+ click.echo(f"✓ layout is canonical (cost {plan.canonical_cost})")+ click.echo("✓ canonical layout resolves identically")+ return++ if plan.creations:+ click.echo(f"Create ({len(plan.creations)}):")+ for path in plan.creations:+ click.echo(f" + {path}")+ if plan.deletions:+ click.echo(f"Delete ({len(plan.deletions)}) — statements fold into an ancestor:")+ for path in plan.deletions:+ click.echo(f" - {path}")+ if plan.additions:+ click.echo("Add rules:")+ for path in sorted(plan.additions):+ for line in plan.additions[path]:+ click.echo(f" {path}: {line}")++ click.echo(f"\ncost: current {plan.current_cost} → canonical {plan.canonical_cost}")+ click.echo(f"(constants: ALPHA={ALPHA}, GAMMA={GAMMA}, MAX_RULES={MAX_RULES})")+ click.echo("✓ canonical layout resolves identically")+ click.echo("\nnote: owners:fmt is a read-only oracle — it never writes. Reflows are deliberate human decisions.")+++def main() -> None:+ """Distributed owners.yaml resolver, linter, and formatter.++ The console-script entry point (``owners <subcommand>``). hogli registers the+ same ``cmd_*`` functions directly under their ``owners:*`` names, so this group+ only exists for the standalone install; the subcommands are named without the+ ``owners:`` prefix here since the script itself already carries it.+ """+++main.add_command(cmd_resolve, name="resolve")+main.add_command(cmd_who, name="who")+main.add_command(cmd_unowned, name="unowned")+main.add_command(cmd_lint, name="lint")+main.add_command(cmd_fmt, name="fmt")diff --git a/tools/owners/posthog_owners/fmt.py b/tools/owners/posthog_owners/fmt.pynew file mode 100644index 000000000000..bc672ad6c0ea--- /dev/null+++ b/tools/owners/posthog_owners/fmt.py@@ -0,0 +1,599 @@+"""``owners:fmt`` — a dry-run canonical file-placement oracle.++Ownership is a piecewise-constant function on the directory tree: most of the+tree shares its parent's owners, and a handful of *change points* (boundaries)+flip to a new owner set. A ``match``/``owners`` statement encodes exactly one+such boundary. Which physical ``owners.yaml`` file carries a given statement is+pure presentation — a parent rule ``- match: '/hogql/'`` resolves identically to+a child ``owners.yaml`` under nearest-wins.++``fmt`` computes the *canonical* layout — the placement of statements onto files+that minimizes a facility-location cost — and reports how the current layout+differs. It is an oracle: it NEVER writes. There is no ``--write`` flag. Fold and+split suggestions from ``owners:lint`` are the everyday incremental mechanism+(with hysteresis); ``fmt`` is the drift oracle you consult deliberately.++The cost model (module constants, tunable — "optimal" is relative to them):++* ``ALPHA`` — the price of a dedicated simple ``owners.yaml`` existing at all.+ Pinned carriers (``product.yaml`` manifests, non-simple ``owners.yaml``,+ glob-bearing files, the repo root) cost nothing: they exist anyway.+* ``GAMMA`` — the per-level price of carrying a statement as a rule in an+ ancestor instead of at its own directory (tree distance).+* ``MAX_RULES`` — a file may hold at most this many statements; a denser cluster+ forces a dedicated child file (the split case).++Placement is a bottom-up capacitated facility-location DP over the directory+tree. The result is proven: the proposed layout is simulated in memory and every+tracked path re-resolved; it must match the current resolution exactly.+"""++from __future__ import annotations++from dataclasses import dataclass, field, replace+from pathlib import Path++from .matcher import compile_pattern+from .resolver import OWNERS_FILENAME, PRODUCT_FILENAME, OwnersFile, OwnersResolver, ParsedOwnershipFile+from .schema import OwnersRule, _Unset, is_simple_owners_file, match_is_glob++# Cost model. "Canonical" is optimal only relative to these; tune to taste.+ALPHA = 8 # cost of a dedicated simple owners.yaml existing+GAMMA = 1 # per-level cost of carrying a statement as an ancestor rule+# Soft cap on statements per file before a split is attempted. Sized to the largest+# hand-accepted rules block in the repo (frontend/src/scenes carries ~60); a split+# only happens when a whole subtree of rules can move together — singleton rules are+# never exiled to per-dir files, so overflow past the cap is tolerated.+MAX_RULES = 100++# Sentinel carry distance meaning "no usable ancestor" — large enough that opening a+# dedicated file (ALPHA) always beats carrying even a single statement this far.+_BLOCKED = 10**6+++# An owner set is an ordered tuple of slugs, or None for unowned/no-contribution.+OwnerSet = tuple[str, ...] | None++# Explicit `owners: null` (unowned-by-design, coverage-exempt) is a distinct+# resolution outcome from plain unowned. It flows through labeling, placement,+# and the proof as this sentinel owner set, so a plan can never trade the+# exemption away for bare unownedness without the proof noticing.+UNOWNED_BY_DESIGN: tuple[str, ...] = ("<unowned-by-design>",)+++def _resolution_owner_set(owners: list[str] | None, unowned_by_design: bool) -> OwnerSet:+ if unowned_by_design:+ return UNOWNED_BY_DESIGN+ return tuple(owners) if owners else None+++def _statement_owners_value(owners: OwnerSet) -> list[str] | None:+ """The `owners:` value a statement writes into a file or rule — the sentinel+ materializes as an explicit `owners: null`."""+ return None if owners is None or owners == UNOWNED_BY_DESIGN else list(owners)+++def _is_simple_file(f: OwnersFile | None) -> bool:+ """A file fmt may rewrite/relocate — the shared predicate, admitting anchored+ rules since fmt reasons about statements."""+ return is_simple_owners_file(f, allow_anchored_rules=True)+++@dataclass+class _Node:+ """One directory in the tree fmt reasons over."""++ path: str # repo-relative posix dir ("" = root)+ depth: int+ children: dict[str, _Node] = field(default_factory=dict)+ label: OwnerSet = None # canonical owner set for files directly in this dir+ # Statements that originate at this directory (dir-context flip + file flips).+ statements: list[_Statement] = field(default_factory=list)+ pinned: bool = False # a product.yaml / non-simple owners.yaml carrier lives here (absorbs rules)+ pinned_label: OwnerSet = None # owners the pinned file already provides here+ frozen: bool = False # a glob-bearing file lives here: untouched, never a carrier+ alias: bool = False # the pin is a product.yaml manifest: only its owners list is read,+ # so it can never physically carry rules — placements must land elsewhere+++@dataclass+class _Statement:+ """One boundary to encode: give ``target`` the owner set ``owners``."""++ target: str # repo-relative dir or file path the statement applies to+ is_dir: bool+ owners: OwnerSet+ node: str # the directory node this statement is anchored at+++@dataclass+class _Placement:+ """Where a statement ends up in the canonical layout."""++ statement: _Statement+ carrier_dir: str # directory whose file carries it+ distance: int+++@dataclass+class CanonicalPlan:+ """The result of a fmt run: the canonical placement plus a diff vs. current.+ A plan only exists once the equivalence proof has passed — ``build`` raises+ otherwise — so holding a plan means the layout is proven sound."""++ current_cost: int+ canonical_cost: int+ creations: list[str]+ deletions: list[str]+ additions: dict[str, list[str]] # file -> human-readable rule lines added++ @property+ def is_canonical(self) -> bool:+ return not self.creations and not self.deletions and not self.additions+++class CanonicalPlacer:+ """Builds the canonical layout for a repo and diffs it against the current one."""++ def __init__(self, resolver: OwnersResolver) -> None:+ self.resolver = resolver+ self.repo_root = resolver.repo_root++ # --- tree + labeling -------------------------------------------------++ def _build_tree(self, file_owners: dict[str, OwnerSet]) -> _Node:+ root = _Node(path="", depth=0)+ for path in file_owners:+ parts = path.split("/")+ node = root+ acc: list[str] = []+ for part in parts[:-1]:+ acc.append(part)+ key = part+ if key not in node.children:+ node.children[key] = _Node(path="/".join(acc), depth=node.depth + 1)+ node = node.children[key]+ return root++ def _dir_files(self, file_owners: dict[str, OwnerSet]) -> dict[str, list[tuple[str, OwnerSet]]]:+ by_dir: dict[str, list[tuple[str, OwnerSet]]] = {}+ for path, owners in file_owners.items():+ d = path.rsplit("/", 1)[0] if "/" in path else ""+ by_dir.setdefault(d, []).append((path, owners))+ return by_dir++ def _label_tree(self, node: _Node, by_dir: dict[str, list[tuple[str, OwnerSet]]]) -> None:+ """Bottom-up labeling that minimizes boundaries. Each dir takes the owner set+ held by the most of its *immediate* children and direct files — each becomes a+ boundary only if it disagrees, so this is the local min-boundary choice.++ Pinned and frozen dirs isolate: they carry their own owners (a ``product.yaml``+ manifest, a glob file) and do not vote in their parent, so a manifest at+ ``products/foo`` keeps ownership there instead of floating a rule up the tree."""+ for child in node.children.values():+ self._label_tree(child, by_dir)++ # A frozen dir labels itself from its own file too: its direct files are+ # glob-served and excluded from voting, so deriving the label from children+ # would float a bogus dir-statement above the frozen file, where the+ # nearer file shadows it and the proof fails.+ if node.pinned or node.frozen:+ node.label = node.pinned_label+ return++ votes: dict[OwnerSet, int] = {}+ for child in node.children.values():+ if child.pinned or child.frozen:+ continue # isolated subtree — does not sway the parent+ votes[child.label] = votes.get(child.label, 0) + 1+ for _path, owners in by_dir.get(node.path, []):+ votes[owners] = votes.get(owners, 0) + 1++ # Deterministic plurality: max votes, tie-break None first then lexicographic.+ def sort_key(item: tuple[OwnerSet, int]) -> tuple[int, int, tuple[str, ...]]:+ owners, n = item+ return (-n, 0 if owners is None else 1, owners or ())++ node.label = min(votes.items(), key=sort_key)[0] if votes else None++ # --- boundaries → statements ----------------------------------------++ def _collect_statements(+ self, node: _Node, parent_label: OwnerSet, by_dir: dict[str, list[tuple[str, OwnerSet]]]+ ) -> None:+ if node.label != parent_label:+ node.statements.append(_Statement(target=node.path, is_dir=True, owners=node.label, node=node.path))+ for path, owners in sorted(by_dir.get(node.path, [])):+ if owners != node.label:+ node.statements.append(_Statement(target=path, is_dir=False, owners=owners, node=node.path))+ for child in sorted(node.children.values(), key=lambda c: c.path):+ self._collect_statements(child, node.label, by_dir)++ # --- classification: pinned carriers vs frozen glob files ------------++ def _classify(+ self, entries: list[ParsedOwnershipFile]+ ) -> tuple[dict[str, OwnerSet], dict[str, OwnerSet], set[str]]:+ """Classify the parsed ownership files. Returns (pinned_carriers, frozen_dirs+ mapped to their file's own top-level owner set, alias_dirs).++ Pinned carriers (``product.yaml`` with owners, or a non-simple owners.yaml+ with status/inherit) absorb statements for free. Frozen dirs host a+ glob-bearing file — crosscutting, untouched, never a carrier. Alias dirs are+ the product.yaml subset of pinned: the manifest provides its dir's owners but+ physically cannot hold rules (only its ``owners:`` list is read), so+ placements must land elsewhere."""+ pinned: dict[str, OwnerSet] = {}+ frozen: dict[str, OwnerSet] = {}+ alias: set[str] = set()+ for entry in entries:+ parsed = entry.parsed+ if entry.name == PRODUCT_FILENAME:+ if parsed and parsed.owners:+ pinned[entry.rel_dir] = tuple(parsed.owners)+ alias.add(entry.rel_dir)+ continue+ if parsed is None:+ continue+ if any(match_is_glob(r.match) for r in parsed.rules):+ frozen[entry.rel_dir] = _resolution_owner_set(parsed.owners, parsed.owners is None)+ elif not _is_simple_file(parsed):+ pinned[entry.rel_dir] = _resolution_owner_set(parsed.owners, parsed.owners is None)+ return pinned, frozen, alias++ def _apply_classification(+ self, node_index: dict[str, _Node], pinned: dict[str, OwnerSet], frozen: dict[str, OwnerSet], alias: set[str]+ ) -> None:+ for d, owners in pinned.items():+ node = node_index.get(d)+ if node is not None:+ node.pinned = True+ node.pinned_label = owners+ node.alias = d in alias+ for d, owners in frozen.items():+ node = node_index.get(d)+ if node is not None:+ node.frozen = True+ node.pinned_label = owners++ # --- facility-location DP -------------------------------------------++ def _facility_cost(self, node: _Node) -> int:+ """Price of a file existing at this directory. Free for pinned carriers and+ the repo root (they exist anyway); ALPHA for a dedicated simple file."""+ return 0 if (node.pinned or node.path == "") else ALPHA++ def _plan_placements(self, root: _Node) -> tuple[list[_Placement], set[str]]:+ """Bottom-up capacitated facility location. Returns statement placements and+ the set of directories whose file is open in the canonical layout."""+ open_dirs: set[str] = set()+ placements: list[_Placement] = []++ # memo[(path, d)] = (min cost, opens) — reconstruct is a pure lookup of the+ # decision cost() already made, so the two can never disagree.+ memo: dict[tuple[str, int], tuple[int, bool]] = {}++ def cost(node: _Node, d: int) -> tuple[int, bool]:+ """Min cost to serve node's subtree given the nearest open facility sits+ ``d`` levels above node (``d`` unused when node opens), plus whether the+ node opens its own facility. A ``d`` of ``_BLOCKED`` or more means no+ usable ancestor exists (an alias manifest or frozen glob file shadows+ everything above by nearest-file-wins), which prices carry-up out so+ the subtree opens its own facility."""+ key = (node.path, d)+ if key in memo:+ return memo[key]+ n_here = sum(1 for s in node.statements if not self._served_by_pin(node, s))++ forced_open = (node.pinned and not node.alias) or node.path == ""+ # Statements below an alias or a frozen file can never live above it:+ # the nearer file's own fields (or its untouchable globs) would shadow+ # any ancestor rule under nearest-file-wins.+ child_d = _BLOCKED if node.alias or node.frozen else d + 1+ # Option A: do not open here; carry own statements up ``d`` levels.+ carry_up = GAMMA * d * n_here + sum(cost(c, child_d)[0] for c in node.children.values())+ if (node.frozen or node.alias) and not forced_open:+ # A glob file or product.yaml manifest lives here — it can never carry+ # new rules; statements pass through.+ memo[key] = (carry_up, False)+ return memo[key]+ # Option B: open here; own statements are free, children are one level down.+ open_here = self._facility_cost(node) + sum(cost(c, 1)[0] for c in node.children.values())+ opens = forced_open or open_here <= carry_up+ memo[key] = (open_here if opens else carry_up, opens)+ return memo[key]++ def reconstruct(node: _Node, d: int, nearest_open: str) -> None:+ _best, opens = cost(node, d)+ movable = [s for s in node.statements if not self._served_by_pin(node, s)]+ if opens:+ open_dirs.add(node.path)+ for s in movable:+ placements.append(_Placement(statement=s, carrier_dir=node.path, distance=0))+ for c in node.children.values():+ reconstruct(c, 1, node.path)+ else:+ child_d = _BLOCKED if node.alias or node.frozen else d + 1+ for s in movable:+ placements.append(_Placement(statement=s, carrier_dir=nearest_open, distance=d))+ for c in node.children.values():+ reconstruct(c, child_d, nearest_open)++ cost(root, 0)+ reconstruct(root, 0, "")+ self._enforce_capacity(root, placements, open_dirs)+ return placements, open_dirs++ def _served_by_pin(self, node: _Node, s: _Statement) -> bool:+ """A dir-context statement whose owners already match the pinned carrier at+ that very directory needs no rule — the manifest/non-simple file provides it."""+ return s.is_dir and (node.pinned or node.frozen) and node.pinned_label == s.owners++ def _enforce_capacity(self, root: _Node, placements: list[_Placement], open_dirs: set[str]) -> None:+ """If a carrier exceeds MAX_RULES, open the child prefix with the most overflow+ as a dedicated facility and reassign its statements there. Repeat to a fixpoint."""+ node_index: dict[str, _Node] = {}+ _index(root, node_index)++ def can_host(d: str) -> bool:+ node = node_index.get(d)+ return node is None or not (node.frozen or node.alias)++ changed = True+ while changed:+ changed = False+ by_carrier: dict[str, list[_Placement]] = {}+ for p in placements:+ by_carrier.setdefault(p.carrier_dir, []).append(p)+ for carrier, ps in by_carrier.items():+ if len(ps) <= MAX_RULES:+ continue+ # Group overflow by the immediate child-of-carrier prefix. Only+ # statements that live under a real subdirectory can move to a child+ # facility — a direct file (``/x.tsx``) has no subdir to hold it, the+ # carrier's own top-level statement (empty head) stays put, and a dir+ # hosting a glob file or product.yaml manifest cannot take new rules.+ # The cap is soft: a group of one is never exiled to a per-dir file+ # (that recreates the single-purpose sprawl fmt exists to remove), so+ # if no group has at least two statements the overflow is tolerated.+ groups: dict[str, list[_Placement]] = {}+ for p in ps:+ rel = p.statement.target[len(carrier) + 1 :] if carrier else p.statement.target+ head = rel.split("/", 1)[0]+ if head and (p.statement.is_dir or "/" in rel):+ groups.setdefault(head, []).append(p)+ hostable = [h for h in groups if len(groups[h]) >= 2 and can_host(f"{carrier}/{h}" if carrier else h)]+ best_head = max(hostable, key=lambda h: len(groups[h]), default=None)+ if best_head is None:+ continue+ new_dir = f"{carrier}/{best_head}" if carrier else best_head+ open_dirs.add(new_dir)+ for p in groups[best_head]:+ p.carrier_dir = new_dir+ p.distance = _depth(p.statement.target) - _depth(new_dir) - (0 if p.statement.is_dir else 1)+ if p.distance < 0:+ p.distance = 0+ changed = True++ # --- current layout cost + diff -------------------------------------++ def build(self) -> CanonicalPlan:+ entries = self.resolver.parsed_ownership_files() # the single parse pass+ pinned, frozen, alias = self._classify(entries)+ # One definition of "a carrier file already exists here": the _classify one.+ pinned_dirs = set(pinned) | set(frozen)++ tracked = self.resolver.tracked_files()+ code_files = [p for p in tracked if p.rsplit("/", 1)[-1] not in (OWNERS_FILENAME, PRODUCT_FILENAME)]+ # Every file's (owners, status) — the proof compares both: placement only+ # models owners, so a fold that reorders past a status rule must fail the+ # proof rather than silently drop generated/vendored from a subtree.+ all_owners: dict[str, tuple[OwnerSet, str]] = {}+ label_owners: dict[str, OwnerSet] = {} # excludes glob-painted files, which stay frozen+ for p in code_files:+ r = self.resolver.resolve(p)+ owners = _resolution_owner_set(r.owners, r.unowned_by_design)+ all_owners[p] = (owners, r.status)+ # A file whose owners come from a glob in a frozen file stays frozen — keep+ # it out of labeling. Unowned files (no source) are never glob-served.+ glob_served = False+ if r.source is not None:+ source_dir = r.source.rsplit("/", 1)[0] if "/" in r.source else ""+ glob_served = source_dir in frozen+ if not glob_served:+ label_owners[p] = owners++ root = self._build_tree(label_owners)+ node_index: dict[str, _Node] = {}+ _index(root, node_index)+ by_dir = self._dir_files(label_owners)+ self._apply_classification(node_index, pinned, frozen, alias)+ self._label_tree(root, by_dir)+ self._collect_statements(root, None, by_dir)++ placements, open_dirs = self._plan_placements(root)+ proposed = self._proposed_files(entries, placements, open_dirs)+ self._prove(proposed, all_owners) # raises on any resolution mismatch++ creations, deletions, additions = self._diff(entries, proposed, open_dirs, pinned_dirs, code_files)+ return CanonicalPlan(+ current_cost=self._current_cost(entries),+ canonical_cost=self._layout_cost(open_dirs, placements, pinned_dirs),+ creations=creations,+ deletions=deletions,+ additions=additions,+ )++ def _layout_cost(self, open_dirs: set[str], placements: list[_Placement], pinned_dirs: set[str]) -> int:+ # A dedicated file costs ALPHA; the root and pinned carriers are free.+ total = sum(ALPHA for d in open_dirs if d != "" and d not in pinned_dirs)+ total += sum(GAMMA * p.distance for p in placements)+ return total++ def _current_cost(self, entries: list[ParsedOwnershipFile]) -> int:+ """Cost of the layout as it stands: ALPHA per dedicated simple file, plus the+ carry distance of every statement each file currently holds as a rule."""+ total = 0+ for entry in entries:+ if entry.name == PRODUCT_FILENAME or entry.parsed is None:+ continue+ parsed = entry.parsed+ if _is_simple_file(parsed) and entry.rel_dir != "":+ total += ALPHA+ for rule in parsed.rules:+ if match_is_glob(rule.match):+ continue+ target = rule.match.strip("/")+ total += GAMMA * max(0, len(target.split("/")) - (0 if rule.match.endswith("/") else 1))+ return total++ def _proposed_files(+ self, entries: list[ParsedOwnershipFile], placements: list[_Placement], open_dirs: set[str]+ ) -> dict[str, OwnersFile]:+ """Materialize the proposed layout as in-memory OwnersFile objects, keyed by+ directory. Pinned files are carried over verbatim (as copies, since rules are+ appended) and augmented with their placements."""+ files: dict[str, OwnersFile] = {}+ for entry in entries:+ parsed = entry.parsed+ if parsed is None:+ continue+ if entry.name == PRODUCT_FILENAME:+ files[entry.rel_dir] = parsed # aliases never receive placements+ elif not _is_simple_file(parsed):+ # Copy: placements are appended, and the parsed entries are cached.+ files[entry.rel_dir] = replace(parsed, rules=list(parsed.rules))++ for carrier in open_dirs:+ if carrier not in files:+ files[carrier] = OwnersFile(+ path=self.repo_root / carrier / OWNERS_FILENAME, directory=carrier, owners=[]+ )+ for p in placements:+ carrier = p.carrier_dir+ f = files[carrier]+ rel = p.statement.target[len(carrier) + 1 :] if carrier else p.statement.target+ match = f"/{rel}/" if p.statement.is_dir and rel else ("/" if not rel else f"/{rel}")+ if p.statement.is_dir and not rel:+ f.owners = _statement_owners_value(p.statement.owners)+ continue+ f.rules.append(OwnersRule(match=match, owners=_statement_owners_value(p.statement.owners)))+ return files++ def _diff(+ self,+ entries: list[ParsedOwnershipFile],+ proposed: dict[str, OwnersFile],+ open_dirs: set[str],+ pinned_dirs: set[str],+ code_files: list[str],+ ) -> tuple[list[str], list[str], dict[str, list[str]]]:+ current_simple_dirs: set[str] = set() # dirs whose file fmt may delete+ # dir -> {match: owners as written} — last occurrence wins, mirroring the+ # resolver's last-match-wins so the diff compares against what decides.+ current_rules: dict[str, dict[str, list[str] | None | _Unset]] = {}+ current_owners: dict[str, list[str] | None] = {} # dir -> top-level owners as written+ for entry in entries:+ if entry.name != OWNERS_FILENAME or entry.parsed is None:+ continue+ current_rules[entry.rel_dir] = {r.match: r.owners for r in entry.parsed.rules}+ current_owners[entry.rel_dir] = entry.parsed.owners+ if _is_simple_file(entry.parsed):+ current_simple_dirs.add(entry.rel_dir)++ creations, deletions = [], []+ additions: dict[str, list[str]] = {}++ for carrier in sorted(open_dirs):+ proposed_file = proposed[carrier]+ proposed_rules = {r.match: r.owners for r in proposed_file.rules}+ cur_rules = current_rules.get(carrier, {})+ path = f"{carrier}/{OWNERS_FILENAME}" if carrier else OWNERS_FILENAME+ file_exists = carrier in current_rules or carrier in pinned_dirs+ # A new file matters if it carries rules OR contributes owners itself+ # (a non-empty list, or explicit null); owners: [] with no rules is a no-op.+ has_content = bool(proposed_file.rules) or bool(proposed_file.owners) or proposed_file.owners is None+ if not file_exists and has_content:+ creations.append(path)+ edits: list[str] = []+ # Changed top-level `owners:` and reused-match rules with different+ # owners are as much a part of the plan as new rules — omitting either+ # would print a plan that, applied literally, resolves differently+ # from the proved proposal.+ if carrier in current_owners and proposed_file.owners != current_owners[carrier]:+ edits.append(f"owners: {_fmt_owners(current_owners[carrier])} -> {_fmt_owners(proposed_file.owners)}")+ changed: list[str] = []+ added: list[str] = []+ for m, o in proposed_rules.items():+ if m not in cur_rules:+ added.append(f"{m} -> {_fmt_owners(o)}")+ elif o != cur_rules[m]:+ changed.append(f"{m}: {_fmt_owners(cur_rules[m])} -> {_fmt_owners(o)}")+ removed: list[str] = []+ # Rebuilt simple carriers can shed rules the canonical layout proved+ # redundant; those drops are part of the plan too. Rules that match no+ # code file under the carrier stay silent — they act outside fmt's+ # domain (e.g. the root rule routing owners.yaml edits) and the proof+ # never reasons about them, so fmt must not propose touching them.+ if carrier not in pinned_dirs:+ for m in cur_rules.keys() - proposed_rules.keys():+ matcher = compile_pattern(m)+ prefix = f"{carrier}/" if carrier else ""+ in_domain = any(+ matcher.test(p[len(prefix) :]) for p in code_files if not prefix or p.startswith(prefix)+ )+ if in_domain:+ removed.append(f"drop {m} (was {_fmt_owners(cur_rules[m])})")+ edits += sorted(changed) + sorted(added) + sorted(removed)+ if edits:+ additions[path] = edits++ for carrier in current_simple_dirs:+ if carrier not in open_dirs:+ deletions.append(f"{carrier}/{OWNERS_FILENAME}" if carrier else OWNERS_FILENAME)++ return sorted(creations), sorted(deletions), additions++ # --- equivalence proof ----------------------------------------------++ def _prove(self, proposed: dict[str, OwnersFile], file_owners: dict[str, tuple[OwnerSet, str]]) -> None:+ """Re-resolve every tracked path against the proposed layout; raises on any+ owners or status mismatch with the current resolution."""+ sim = _InMemoryResolver(self.repo_root, proposed)+ for path, expected in file_owners.items():+ got = sim.resolve(path)+ got_pair = (_resolution_owner_set(got.owners, got.unowned_by_design), got.status)+ if got_pair != expected:+ raise AssertionError(f"fmt bug: canonical layout resolves {path} to {got_pair}, expected {expected}")+++class _InMemoryResolver(OwnersResolver):+ """An OwnersResolver that reads ownership files from an in-memory map instead of+ disk — used to prove the proposed layout resolves identically."""++ def __init__(self, repo_root: Path, files: dict[str, OwnersFile]) -> None:+ self.repo_root = repo_root+ self._dir_cache = {}+ self._teams_cache = None+ self._files = files++ def _load_dir_file(self, directory: str) -> OwnersFile | None: # type: ignore[override]+ return self._files.get(directory)+++def _depth(path: str) -> int:+ return 0 if path == "" else len(path.split("/"))+++def _index(node: _Node, out: dict[str, _Node]) -> None:+ out[node.path] = node+ for c in node.children.values():+ _index(c, out)+++def _fmt_owners(owners: list[str] | None | _Unset) -> str:+ if isinstance(owners, _Unset):+ return "(inherit)"+ if owners is None:+ return "(unowned)"+ return "[" + ", ".join(owners) + "]"diff --git a/tools/owners/posthog_owners/matcher.py b/tools/owners/posthog_owners/matcher.pynew file mode 100644index 000000000000..27c32534311e--- /dev/null+++ b/tools/owners/posthog_owners/matcher.py@@ -0,0 +1,185 @@+"""GitHub-faithful CODEOWNERS pattern matcher.++Python port of ``.github/scripts/codeowners.js`` (itself a port of+hmarr/codeowners), reproducing GitHub's segment semantics: leading-slash root+anchoring, slash-free names behaving as ``**/`` prefixed, trailing-slash meaning+"this directory and everything under it", ``*`` never crossing ``/``, and a+literal final segment owning its whole subtree.++Used both for ``owners.yaml`` ``rules:`` globs and by the legacy differ to+replicate the assigner's ``CODEOWNERS-soft`` behavior, so it must stay faithful.+"""++from __future__ import annotations++import re+from collections.abc import Callable+from functools import lru_cache+from typing import Literal++SEP = "/"+++def normalize_path(file_path: str) -> str:+ """Repo-relative, forward-slash path with any leading ``./`` or ``/`` stripped."""+ p = file_path.replace("\\", SEP)+ while p.startswith("./"):+ p = p[2:]+ while p.startswith(SEP):+ p = p[1:]+ return p+++def pattern_to_segments(pattern: str) -> list[str]:+ """Normalize a pattern into GitHub-semantics path segments.++ Applies the leading-slash (root-anchor), slash-free (``**`` prefix), and+ trailing-slash (``**`` suffix) rules, then collapses consecutive ``**``.+ Raises ``ValueError`` on the patterns GitHub rejects. ``/`` is handled by+ callers and never passed here.+ """+ if "***" in pattern:+ raise ValueError("pattern cannot contain three consecutive asterisks")+ if pattern == "":+ raise ValueError("empty pattern")++ segs = pattern.split(SEP)++ if segs[0] == "":+ # Leading slash anchors to the repo root: drop the empty first segment.+ segs = segs[1:]+ elif len(segs) == 1 or (len(segs) == 2 and segs[1] == ""):+ # A slash-free name (`foo`, `foo/`, `*.js`) matches at any depth, so it+ # behaves as if prefixed with `**/`.+ if segs[0] != "**":+ segs = ["**", *segs]++ if len(segs) > 1 and segs[-1] == "":+ # A trailing slash means "this directory and everything under it".+ segs[-1] = "**"++ # Collapse runs of consecutive `**` into one — semantically identical, and two+ # adjacent `**` would otherwise compile to a degenerate, never-matching form.+ collapsed: list[str] = []+ for seg in segs:+ if seg == "**" and collapsed and collapsed[-1] == "**":+ continue+ collapsed.append(seg)+ return collapsed+++def _seg_to_regex(seg: str) -> re.Pattern[str]:+ """Compile one literal segment (may contain ``*``, ``?``, ``\\`` escapes) into+ an anchored regex matching exactly one path segment (never crossing ``/``)."""+ out = ["^"]+ escape = False+ for ch in seg:+ if escape:+ escape = False+ out.append(re.escape(ch))+ elif ch == "\\":+ escape = True+ elif ch == "*":+ out.append("[^/]*")+ elif ch == "?":+ out.append("[^/]")+ else:+ out.append(re.escape(ch))+ out.append("$")+ return re.compile("".join(out))+++class _Token:+ """One compiled pattern token: ``**`` (star), ``*`` (one), or a literal."""++ __slots__ = ("type", "test")++ def __init__(self, type_: Literal["star", "one", "lit"], test: Callable[[str], bool]) -> None:+ self.type = type_+ self.test = test+++def _glob_match(tokens: list[_Token], path_segs: list[str]) -> bool:+ """Match tokenized pattern against path segments with no cross-segment+ backtracking: a bottom-up ``dp[ti][pi]`` scan, O(tokens x segments).++ Encodes the same rules as the JS reference: ``**`` matches zero or more whole+ segments (a trailing ``**`` needs at least one), ``*`` and literals each match+ exactly one segment, and a literal final segment also owns its subtree.+ """+ m = len(tokens)+ n = len(path_segs)+ # nxt holds dp[ti + 1][*]; seed with dp[m][pi] = (no tokens left → path exhausted).+ nxt = [pi == n for pi in range(n + 1)]+ for ti in range(m - 1, -1, -1):+ tok = tokens[ti]+ is_last = ti == m - 1+ cur = [False] * (n + 1)+ if tok.type == "star":+ if is_last:+ # A trailing `**` consumes every remaining segment but needs one.+ for pi in range(n + 1):+ cur[pi] = (n - pi) >= 1+ else:+ cur[n] = nxt[n]+ for pi in range(n - 1, -1, -1):+ cur[pi] = nxt[pi] or cur[pi + 1]+ else:+ for pi in range(n):+ if not tok.test(path_segs[pi]):+ continue+ cur[pi] = True if (is_last and tok.type == "lit") else nxt[pi + 1]+ nxt = cur+ return nxt[0]+++class PatternMatcher:+ """A single compiled CODEOWNERS pattern. ``test(path)`` returns whether a+ normalized repo-relative path is matched."""++ def __init__(self, pattern: str) -> None:+ self.pattern = pattern+ self._literal_prefix: str | None = None+ self._tokens: list[_Token] | None = None++ # Fast path for left-anchored patterns with no wildcards (the common case).+ if not re.search(r"[*?\\]", pattern) and pattern.startswith(SEP):+ self._literal_prefix = pattern[1:]+ return++ self._tokens = []+ for seg in pattern_to_segments(pattern):+ if seg == "**":+ self._tokens.append(_Token("star", lambda _s: False))+ elif seg == "*":+ self._tokens.append(_Token("one", lambda s: len(s) >= 1))+ else:+ regex = _seg_to_regex(seg)+ self._tokens.append(_Token("lit", lambda s, r=regex: bool(r.match(s))))++ def test(self, path: str) -> bool:+ prefix = self._literal_prefix+ if prefix is not None:+ if prefix == "":+ return False+ if prefix.endswith(SEP):+ return path.startswith(prefix)+ if len(path) == len(prefix):+ return path == prefix+ if len(path) > len(prefix) and path[len(prefix)] == SEP:+ return path[: len(prefix)] == prefix+ return False++ assert self._tokens is not None+ return _glob_match(self._tokens, path.split(SEP) if path else [])+++@lru_cache(maxsize=4096)+def compile_pattern(pattern: str) -> PatternMatcher:+ """Compile a pattern (cached), raising ``ValueError`` on the invalid ones GitHub rejects."""+ return PatternMatcher(pattern)+++def path_matches_pattern(pattern: str, file_path: str) -> bool:+ """Whether a single CODEOWNERS pattern matches a repo-relative path."""+ return compile_pattern(pattern).test(normalize_path(file_path))diff --git a/tools/owners/posthog_owners/resolver.py b/tools/owners/posthog_owners/resolver.pynew file mode 100644index 000000000000..7e55a9985bd3--- /dev/null+++ b/tools/owners/posthog_owners/resolver.py@@ -0,0 +1,295 @@+"""Ownership resolution for a repo-relative path.++Walks from the repo root toward the path, collecting ``owners.yaml`` (or aliased+``product.yaml``) contributions, honoring ``inherit: false`` as a hard cut, and+merges them nearest-file-wins per field. See ``docs/internal/ownership-model-proposal.md``.+"""++from __future__ import annotations++import sys+import subprocess+from dataclasses import dataclass, field+from pathlib import Path+from typing import TypedDict++from .matcher import compile_pattern, normalize_path+from .schema import UNSET, OwnersFile, _Unset, parse_owners_file, parse_product_yaml_as_owners++OWNERS_FILENAME = "owners.yaml"+PRODUCT_FILENAME = "product.yaml"+++@dataclass+class Resolution:+ """The resolved ownership of a single path."""++ path: str+ owners: list[str] | None # None for both explicit-null and no-contribution+ status: str+ slack: str | None+ source: str | None # repo-relative path of the file that decided owners+ unowned_by_design: bool # explicit `owners: null` exemption++ @property+ def is_owned(self) -> bool:+ return bool(self.owners)++ @property+ def is_unowned(self) -> bool:+ """Unowned and NOT exempt — what the coverage check fails on."""+ return not self.owners and not self.unowned_by_design+++class WireResolution(TypedDict):+ """The JSON wire shape shared by ``hogli owners:resolve --json`` and the+ dependency-light ``python -m posthog_owners`` entrypoint. Both emit+ exactly this dict per path so consumers see one format."""++ owners: list[str]+ status: str+ slack: str | None+ source: str | None+++def resolution_to_wire(r: Resolution) -> WireResolution:+ return {"owners": r.owners or [], "status": r.status, "slack": r.slack, "source": r.source}+++def read_stdin_paths() -> list[str]:+ """Newline-delimited repo-relative paths from stdin, blanks dropped."""+ return [line.strip() for line in sys.stdin.read().splitlines() if line.strip()]+++@dataclass+class ParsedOwnershipFile:+ """One tracked ownership file, parsed once."""++ path: Path # absolute+ rel_dir: str # repo-relative posix dir ("" = root)+ name: str # OWNERS_FILENAME or PRODUCT_FILENAME+ parsed: OwnersFile | None+ errors: list[str] = field(default_factory=list)+++@dataclass+class _Merged:+ owners: list[str] | None | _Unset = UNSET+ status: str | _Unset = UNSET+ source: str | None = None+++def _git_repo_root() -> Path:+ result = subprocess.run(+ ["git", "rev-parse", "--show-toplevel"],+ capture_output=True,+ text=True,+ check=True,+ )+ return Path(result.stdout.strip())+++class OwnersResolver:+ """Resolves ownership by reading ``owners.yaml`` / ``product.yaml`` from disk.++ Works from any CWD by locating the repo root via ``git rev-parse`` (override+ with ``repo_root`` for testing). Parsed files are cached per directory.+ """++ def __init__(self, repo_root: Path | None = None) -> None:+ self.repo_root = (repo_root or _git_repo_root()).resolve()+ self._dir_cache: dict[str, OwnersFile | None] = {}+ # The worktree is treated as immutable for the resolver's lifetime.+ self._tracked_cache: dict[str | None, list[str]] = {}+ self._parsed_ownership: list[ParsedOwnershipFile] | None = None+ self._teams_cache: dict[str, str | bool] | None = None++ def _load_dir_file(self, directory: str) -> OwnersFile | None:+ """Ownership file for a repo-relative directory ("" = root), or None."""+ if directory in self._dir_cache:+ return self._dir_cache[directory]++ base = self.repo_root if directory == "" else self.repo_root / directory+ result: OwnersFile | None = None++ owners_path = base / OWNERS_FILENAME+ if owners_path.is_file():+ parsed, _errors = parse_owners_file(owners_path.read_text(), path=owners_path, directory=directory)+ result = parsed++ # A product.yaml alias only applies when there is no owners.yaml (a+ # directory with both is a lint error; resolve prefers owners.yaml).+ if result is None:+ product_path = base / PRODUCT_FILENAME+ if product_path.is_file():+ result = parse_product_yaml_as_owners(product_path.read_text(), path=product_path, directory=directory)++ self._dir_cache[directory] = result+ return result++ def _ancestor_dirs(self, path: str) -> list[str]:+ """Repo-relative dirs from root ("") down to the path's parent, outermost first."""+ dirs = [""]+ parts = path.split("/")[:-1] # drop the filename+ acc: list[str] = []+ for part in parts:+ acc.append(part)+ dirs.append("/".join(acc))+ return dirs++ def _collect_files(self, path: str) -> list[OwnersFile]:+ """Ownership files on the walk to ``path``, outermost first. ``inherit``+ cuts are NOT applied here: a matched rule may override the file-level+ flag either way, so the cut must happen per contribution in ``resolve``,+ after rule overrides are folded in."""+ collected: list[OwnersFile] = []+ for directory in self._ancestor_dirs(path):+ f = self._load_dir_file(directory)+ if f is not None:+ collected.append(f)+ return collected++ def _file_contribution(self, f: OwnersFile, path: str) -> OwnersFile | None:+ """A shallow copy of the file's fields with its own last-matching rule+ applied. Returns an OwnersFile whose top-level fields hold the effective+ contribution (rules already merged in). Returns the file itself if no rule."""+ rel = path[len(f.directory) + 1 :] if f.directory else path+ matched = None+ for rule in f.rules: # last-match-wins within the file+ if compile_pattern(rule.match).test(rel):+ matched = rule+ if matched is None:+ return f++ contrib = OwnersFile(+ path=f.path,+ directory=f.directory,+ owners=f.owners,+ status=f.status,+ inherit=f.inherit,+ is_alias=f.is_alias,+ )+ if not isinstance(matched.owners, _Unset):+ contrib.owners = matched.owners+ if not isinstance(matched.status, _Unset):+ contrib.status = matched.status+ if not isinstance(matched.inherit, _Unset):+ contrib.inherit = matched.inherit+ return contrib++ def resolve(self, path: str) -> Resolution:+ norm = normalize_path(path)+ merged = _Merged()++ for f in self._collect_files(norm):+ contrib = self._file_contribution(f, norm)+ assert contrib is not None++ # The single `set noparent` site: contrib.inherit is the file-level+ # flag with any matched rule's override folded in, so a file-level+ # `inherit: false` cuts here, and a rule-level `inherit: true` can+ # restore ancestors for its paths.+ if not contrib.inherit:+ merged = _Merged()++ # Owners: an explicit list (non-empty) or explicit null overrides; an+ # empty list is "no contribution here" and falls through.+ if contrib.owners is None:+ merged.owners = None+ merged.source = self._rel(contrib.path)+ elif contrib.owners:+ merged.owners = list(contrib.owners)+ merged.source = self._rel(contrib.path)++ if not isinstance(contrib.status, _Unset):+ merged.status = contrib.status++ return self._build_resolution(norm, merged)++ def _teams_registry(self) -> dict[str, str | bool]:+ """The root file's ``teams:`` Slack registry (team slug -> channel or False),+ loaded once. Empty when there is no root file or it declares none."""+ if self._teams_cache is None:+ root = self._load_dir_file("")+ self._teams_cache = dict(root.teams) if root is not None else {}+ return self._teams_cache++ def _effective_slack(self, owners: list[str] | None) -> str | None:+ """The Slack channel for a path: the registry entry for the primary owner+ (team slugs only), then the derived ``#<slug>``, else None. Only a team slug+ (not an ``@handle``) carries a channel."""+ if owners and not owners[0].startswith("@"):+ primary = owners[0]+ registry = self._teams_registry()+ if primary in registry:+ entry = registry[primary]+ # Schema only admits `slack: false`; any bool means "no channel".+ return entry if isinstance(entry, str) else None+ return f"#{primary}"+ return None++ def _build_resolution(self, path: str, merged: _Merged) -> Resolution:+ unowned_by_design = merged.owners is None+ owners: list[str] | None = None if isinstance(merged.owners, _Unset) else merged.owners++ status = "active" if isinstance(merged.status, _Unset) else merged.status++ slack = self._effective_slack(owners)++ return Resolution(+ path=path,+ owners=owners,+ status=status,+ slack=slack,+ source=merged.source,+ unowned_by_design=unowned_by_design,+ )++ def _rel(self, path: Path) -> str:+ return path.relative_to(self.repo_root).as_posix()++ def map(self, paths: list[str]) -> dict[str, Resolution]:+ return {p: self.resolve(p) for p in paths}++ def unowned(self, paths: list[str]) -> list[str]:+ """The subset of ``paths`` that resolve to unowned (and not exempt)."""+ return [p for p in paths if self.resolve(p).is_unowned]++ def tracked_files(self, prefix: str | None = None) -> list[str]:+ """Repo-relative paths from ``git ls-files``, optionally under ``prefix``.+ Cached per prefix — the worktree is treated as immutable per run."""+ if prefix in self._tracked_cache:+ return self._tracked_cache[prefix]+ args = ["git", "-C", str(self.repo_root), "ls-files", "-z"]+ if prefix:+ args.append(prefix)+ result = subprocess.run(args, capture_output=True, text=True, check=True)+ paths = [p for p in result.stdout.split("\0") if p]+ self._tracked_cache[prefix] = paths+ return paths++ def ownership_files(self) -> list[Path]:+ """Absolute paths of every tracked ownership file (owners.yaml + product.yaml)."""+ return [entry.path for entry in self.parsed_ownership_files()]++ def parsed_ownership_files(self) -> list[ParsedOwnershipFile]:+ """Every tracked ownership file, parsed exactly once (cached). This is the+ single parse pass consumers (lint, fmt) should thread through instead of+ re-reading and re-parsing the same YAML per concern."""+ if self._parsed_ownership is not None:+ return self._parsed_ownership+ entries: list[ParsedOwnershipFile] = []+ for rel in self.tracked_files():+ name = rel.rsplit("/", 1)[-1]+ if name not in (OWNERS_FILENAME, PRODUCT_FILENAME):+ continue+ abs_path = self.repo_root / rel+ rel_dir = rel.rsplit("/", 1)[0] if "/" in rel else ""+ if name == PRODUCT_FILENAME:+ parsed = parse_product_yaml_as_owners(abs_path.read_text(), path=abs_path, directory=rel_dir)+ errors: list[str] = []+ else:+ parsed, errors = parse_owners_file(abs_path.read_text(), path=abs_path, directory=rel_dir)+ entries.append(ParsedOwnershipFile(path=abs_path, rel_dir=rel_dir, name=name, parsed=parsed, errors=errors))+ self._parsed_ownership = entries+ return entriesdiff --git a/tools/owners/posthog_owners/schema.py b/tools/owners/posthog_owners/schema.pynew file mode 100644index 000000000000..ce8c1ee5c546--- /dev/null+++ b/tools/owners/posthog_owners/schema.py@@ -0,0 +1,296 @@+"""Dataclass model, parser, and validator for ``owners.yaml``.++Also loads ``products/<name>/product.yaml`` as an *aliased* ownership file: only+its ``owners:`` list is read (``@handles`` kept, a ``team-CHANGEME``-only list+treated as empty), every other field ignored.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from pathlib import Path+from typing import TypeGuard++import yaml++from .matcher import compile_pattern++VALID_STATUSES = ("active", "deprecated", "generated", "vendored")+CHANGEME_SLUG = "team-CHANGEME"++# Top-level keys allowed in owners.yaml. Rules allow the same set minus `version`+# and `rules`, plus the required `match`. `teams` is root-only (see parse).+_TOP_LEVEL_KEYS = {"version", "owners", "status", "inherit", "rules", "teams"}+_RULE_KEYS = {"match", "owners", "status", "inherit"}+_TEAMS_ENTRY_KEYS = {"slack"}+++class _Unset:+ """Sentinel marking a field the file did not set (so it falls through to an+ ancestor). Distinct from ``owners: null`` (explicit unowned-by-design)."""++ _instance: _Unset | None = None++ def __new__(cls) -> _Unset:+ if cls._instance is None:+ cls._instance = super().__new__(cls)+ return cls._instance++ def __repr__(self) -> str:+ return "UNSET"+++UNSET = _Unset()+++@dataclass+class OwnersRule:+ """A per-path override inside a file, evaluated last-match-wins within the file."""++ match: str+ owners: list[str] | None | _Unset = UNSET+ status: str | _Unset = UNSET+ inherit: bool | _Unset = UNSET+++@dataclass+class OwnersFile:+ """A parsed ownership file (real ``owners.yaml`` or an aliased ``product.yaml``)."""++ path: Path+ directory: str # repo-relative posix dir containing the file ("" for repo root)+ owners: list[str] | None # required; None = explicit unowned-by-design; [] = no contribution+ version: int = 1+ status: str | _Unset = UNSET+ inherit: bool = True+ rules: list[OwnersRule] = field(default_factory=list)+ is_alias: bool = False+ # Root-only Slack registry: team slug -> slack (string or False). Empty everywhere+ # but the repo-root file; lets a team declare its channel once instead of per file.+ teams: dict[str, str | bool] = field(default_factory=dict)+++def normalize_product_owners(owners: list[str]) -> list[str]:+ """Drop the ``team-CHANGEME`` scaffold placeholder: it never carries ownership+ signal, so a list consisting only of it is empty. Applied to both ``product.yaml``+ aliases and ``owners.yaml`` owners lists — one CHANGEME semantics everywhere."""+ return [o for o in owners if o != CHANGEME_SLUG]+++def _validate_owners_value(value: object, where: str, errors: list[str]) -> list[str] | None | _Unset:+ if value is None:+ return None+ if isinstance(value, str) and value:+ value = [value]+ # Empty-string entries are rejected, not filtered: `owners: ['']` would count+ # as covered while the assigner drops the falsy owner and requests nobody.+ if not isinstance(value, list) or not all(isinstance(x, str) and x for x in value):+ errors.append(f"{where}: 'owners' must be a non-empty string, a list of non-empty strings, or null")+ return UNSET+ return normalize_product_owners([str(x) for x in value])+++def _is_valid_slack(raw: object) -> TypeGuard[str | bool]:+ """A Slack channel value is a string starting with '#', or ``false`` for "no+ channel". Shared by the ``teams:`` registry — the only place a channel is set."""+ return raw is False or (isinstance(raw, str) and raw.startswith("#"))+++def _validate_teams(value: object, errors: list[str]) -> dict[str, str | bool]:+ """Validate the root-only ``teams:`` registry — a mapping of team slug to a+ single ``slack`` value."""+ registry: dict[str, str | bool] = {}+ if not isinstance(value, dict):+ errors.append("'teams' must be a mapping of team slug to {slack: ...}")+ return registry+ for slug, entry in value.items():+ where = f"teams['{slug}']"+ if not isinstance(slug, str):+ errors.append(f"teams: slug must be a string, got {slug!r}")+ continue+ if slug.startswith("@"):+ errors.append(f"{where}: registry keys are team slugs, not @handles")+ continue+ if not isinstance(entry, dict):+ errors.append(f"{where}: entry must be a mapping with a 'slack' key")+ continue+ for key in entry:+ if key not in _TEAMS_ENTRY_KEYS:+ errors.append(f"{where}: unknown field '{key}'")+ if "slack" in entry:+ raw = entry["slack"]+ if _is_valid_slack(raw):+ registry[slug] = raw+ else:+ errors.append(f"{where}: 'slack' must be a string starting with '#' or false")+ return registry+++def _validate_status(value: object, where: str, errors: list[str]) -> str | _Unset:+ if isinstance(value, str) and value in VALID_STATUSES:+ return value+ errors.append(f"{where}: 'status' must be one of {', '.join(VALID_STATUSES)}")+ return UNSET+++def _validate_inherit(value: object, where: str, errors: list[str]) -> bool | _Unset:+ if isinstance(value, bool):+ return value+ errors.append(f"{where}: 'inherit' must be a boolean")+ return UNSET+++def _rule_match_patterns(raw_match: object, where: str, errors: list[str]) -> list[str]:+ """A rule's ``match`` may be one non-empty string or a non-empty list of them.+ Returns every compiling pattern in order; on any malformed or uncompilable entry+ it appends a schema error and returns ``[]`` so the whole rule is dropped (lint+ reports a normal error and the resolver never sees a rule that would crash)."""+ if isinstance(raw_match, str):+ candidates: list[object] = [raw_match]+ elif isinstance(raw_match, list) and raw_match:+ candidates = list(raw_match)+ else:+ errors.append(f"{where}: 'match' is required and must be a non-empty string or a non-empty list of strings")+ return []++ patterns: list[str] = []+ ok = True+ for candidate in candidates:+ if not isinstance(candidate, str) or not candidate:+ errors.append(f"{where}: each 'match' pattern must be a non-empty string")+ ok = False+ continue+ try:+ compile_pattern(candidate)+ except ValueError as exc:+ errors.append(f"{where}: invalid match pattern '{candidate}': {exc}")+ ok = False+ continue+ patterns.append(candidate)+ return patterns if ok else []+++def _parse_rule(raw: object, index: int, errors: list[str]) -> list[OwnersRule]:+ """Parse one physical rule entry into one ``OwnersRule`` per ``match`` pattern+ (a list ``match`` explodes here so resolver/fmt/lint keep seeing single-pattern+ rules). Returns ``[]`` on a schema error."""+ where = f"rules[{index}]"+ if not isinstance(raw, dict):+ errors.append(f"{where}: each rule must be a mapping")+ return []+ for key in raw:+ if key not in _RULE_KEYS:+ errors.append(f"{where}: unknown field '{key}'")+ patterns = _rule_match_patterns(raw.get("match"), where, errors)+ if not patterns:+ return []++ owners = _validate_owners_value(raw["owners"], where, errors) if "owners" in raw else UNSET+ status = _validate_status(raw["status"], where, errors) if "status" in raw else UNSET+ inherit = _validate_inherit(raw["inherit"], where, errors) if "inherit" in raw else UNSET+ return [OwnersRule(match=pattern, owners=owners, status=status, inherit=inherit) for pattern in patterns]+++def parse_owners_file(text: str, *, path: Path, directory: str) -> tuple[OwnersFile | None, list[str]]:+ """Parse and validate ``owners.yaml`` contents.++ Returns ``(file, errors)``. ``file`` is None only when the document itself is+ unusable (bad YAML, not a mapping, missing required fields).+ """+ errors: list[str] = []+ try:+ data = yaml.safe_load(text)+ except yaml.YAMLError as exc:+ return None, [f"invalid YAML: {exc}"]+ if not isinstance(data, dict):+ return None, ["owners.yaml must be a YAML mapping"]++ for key in data:+ if key not in _TOP_LEVEL_KEYS:+ errors.append(f"unknown top-level field '{key}'")++ if data.get("version") != 1:+ errors.append("'version: 1' is required")++ if "owners" not in data:+ errors.append("'owners' is required (a string, a list of strings, or null for unowned-by-design)")+ owners: list[str] | None = []+ else:+ validated = _validate_owners_value(data["owners"], "owners", errors)+ owners = [] if isinstance(validated, _Unset) else validated++ file = OwnersFile(path=path, directory=directory, owners=owners)++ if "status" in data:+ file.status = _validate_status(data["status"], "status", errors)+ if "inherit" in data:+ inherit = _validate_inherit(data["inherit"], "inherit", errors)+ file.inherit = True if isinstance(inherit, _Unset) else inherit++ if "teams" in data:+ # The registry is a single repo-wide lookup, so it only makes sense at the+ # root; a nested file carrying it would silently do nothing.+ if directory != "":+ errors.append("'teams' is only allowed in the repo-root owners.yaml")+ else:+ file.teams = _validate_teams(data["teams"], errors)++ if "rules" in data:+ raw_rules = data["rules"]+ if not isinstance(raw_rules, list):+ errors.append("'rules' must be a list")+ else:+ for i, raw_rule in enumerate(raw_rules):+ file.rules.extend(_parse_rule(raw_rule, i, errors))++ # A missing version or owners makes the file unusable for resolution.+ if data.get("version") != 1 or "owners" not in data:+ return None, errors+ return file, errors+++def parse_product_yaml_as_owners(text: str, *, path: Path, directory: str) -> OwnersFile | None:+ """Load ``product.yaml`` as an aliased ownership file, or None if it has no+ usable ``owners:`` list."""+ try:+ data = yaml.safe_load(text)+ except yaml.YAMLError:+ return None+ if not isinstance(data, dict) or "owners" not in data:+ return None+ raw = data["owners"]+ if not isinstance(raw, list) or not all(isinstance(x, str) and x for x in raw):+ return None+ owners = normalize_product_owners(raw)+ return OwnersFile(path=path, directory=directory, owners=owners, is_alias=True)+++def match_is_glob(match: str) -> bool:+ """A rule match is a crosscutting glob (not a tree boundary) when it carries a+ wildcard character."""+ return any(ch in match for ch in "*?[")+++def is_simple_owners_file(parsed: OwnersFile | None, *, allow_anchored_rules: bool = False) -> bool:+ """Whether a file is "simple" — mechanically relocatable, nothing but ownership.++ Both callers agree that status/``inherit: false`` (and being a+ ``product.yaml`` alias) disqualify a file. So does a ``teams:`` registry:+ it is root-only content relocation would strand. So does any rule carrying+ more than match+owners: relocation only preserves owners, so rule-level+ ``status``/``inherit`` must pin the file. They differ on rules:++ - lint's consolidation suggestions (``allow_anchored_rules=False``) only fold+ files whose entire content is one non-empty ``owners:`` list;+ - fmt (``allow_anchored_rules=True``) reasons about statements, so files whose+ rules are all anchored (no globs) are fair game too.+ """+ if parsed is None or parsed.is_alias:+ return False+ if parsed.inherit is False or parsed.status is not UNSET or parsed.teams:+ return False+ if any(r.status is not UNSET or r.inherit is not UNSET for r in parsed.rules):+ return False+ if allow_anchored_rules:+ return not any(match_is_glob(r.match) for r in parsed.rules)+ return bool(parsed.owners) and not parsed.rulesdiff --git a/tools/owners/pyproject.toml b/tools/owners/pyproject.tomlnew file mode 100644index 000000000000..739cf6ce41ae--- /dev/null+++ b/tools/owners/pyproject.toml@@ -0,0 +1,53 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[project]+name = "posthog-owners"+version = "0.1.0"+description = "Distributed owners.yaml ownership resolver, linter, and formatter"+readme = "README.md"+license = "MIT"+requires-python = ">=3.10"+authors = [+ { name = "PostHog", email = "[email protected]" }+]+keywords = ["ownership", "codeowners", "devex", "yaml"]+classifiers = [+ "Development Status :: 4 - Beta",+ "Environment :: Console",+ "Intended Audience :: Developers",+ "License :: OSI Approved :: MIT License",+ "Operating System :: OS Independent",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.10",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+ "Programming Language :: Python :: 3.13",+ "Topic :: Software Development :: Build Tools",+ "Topic :: Utilities",+]+dependencies = [+ "pyyaml>=6.0",+ "click>=8.0",+]++[project.optional-dependencies]+dev = [+ "pytest>=7.0",+]++[project.scripts]+owners = "posthog_owners.cli:main"++[project.urls]+Homepage = "https://github.com/PostHog/posthog"+Documentation = "https://github.com/PostHog/posthog/tree/master/tools/owners"+Repository = "https://github.com/PostHog/posthog"++[tool.hatch.build.targets.wheel]+packages = ["posthog_owners"]++[tool.pytest.ini_options]+testpaths = ["tests"]+addopts = "-p no:warnings -p no:django"diff --git a/tools/owners/tests/test_owners.py b/tools/owners/tests/test_owners.pynew file mode 100644index 000000000000..3a8b4858e2bb--- /dev/null+++ b/tools/owners/tests/test_owners.py@@ -0,0 +1,614 @@+from __future__ import annotations++import subprocess+from pathlib import Path++import pytest++from posthog_owners import fmt as fmt_module+from posthog_owners.cli import _consolidation_suggestions, _reserved_location_error+from posthog_owners.fmt import CanonicalPlacer, CanonicalPlan+from posthog_owners.matcher import path_matches_pattern+from posthog_owners.resolver import OwnersResolver+from posthog_owners.schema import is_simple_owners_file, parse_owners_file+++ "pattern,path,expected",+ [+ ("/foo/bar", "foo/bar", True),+ ("/foo/bar", "foo/bar/baz.py", True),+ ("/foo/bar", "x/foo/bar", False),+ ("foo", "a/b/foo", True),+ ("foo", "a/b/foo/c", True),+ ("*.js", "a/b/c.js", True),+ ("*.js", "a/b/c.ts", False),+ ("/docs/*", "docs/x.md", True),+ ("/docs/*", "docs/a/b.md", False),+ ("a/**/b", "a/b", True),+ ("a/**/b", "a/x/y/b", True),+ ("a/**/b", "a/b/c", True),+ ("**/foo", "a/foo", True),+ ("**", "anything/x", True),+ ("docs/", "docs/x/y", True),+ ("docker-compose*.yml", "a/b/docker-compose.dev.yml", True),+ ],+)+def test_matcher_vectors(pattern: str, path: str, expected: bool) -> None:+ assert path_matches_pattern(pattern, path) is expected+++def _write(root: Path, rel: str, text: str) -> None:+ p = root / rel+ p.parent.mkdir(parents=True, exist_ok=True)+ p.write_text(text)+++def resolver_repo(tmp_path: Path) -> Path:+ _write(+ tmp_path,+ "owners.yaml",+ "version: 1\nowners: null\nrules:\n - match: Dockerfile\n owners: [team-devex]\n",+ )+ _write(+ tmp_path,+ "posthog/owners.yaml",+ "version: 1\nowners: [team-a]\n"+ "rules:\n - match: '/vendor/**'\n owners: null\n - match: legacy.py\n owners: [team-legacy]\n",+ )+ _write(tmp_path, "posthog/sub/owners.yaml", "version: 1\nowners: [team-b]\n")+ _write(tmp_path, "posthog/noinherit/owners.yaml", "version: 1\ninherit: false\nowners: [team-c]\n")+ _write(tmp_path, "products/foo/product.yaml", "name: Foo\nowners:\n - team-foo\n")+ _write(tmp_path, "products/bar/product.yaml", "name: Bar\nowners:\n - team-CHANGEME\n")+ return tmp_path+++ "path,owners,unowned_by_design",+ [+ ("Dockerfile", ["team-devex"], False),+ ("README.md", None, True),+ ("posthog/x.py", ["team-a"], False),+ ("posthog/legacy.py", ["team-legacy"], False),+ ("posthog/vendor/lib.py", None, True),+ ("posthog/sub/y.py", ["team-b"], False),+ ("posthog/sub/legacy.py", ["team-b"], False),+ ("posthog/noinherit/z.py", ["team-c"], False),+ ("products/foo/thing.py", ["team-foo"], False),+ ("products/bar/thing.py", None, True),+ ("other/legacy.py", None, True),+ ],+)+def test_resolver_precedence(resolver_repo: Path, path: str, owners: list[str] | None, unowned_by_design: bool) -> None:+ r = OwnersResolver(repo_root=resolver_repo).resolve(path)+ assert r.owners == owners+ assert r.unowned_by_design is unowned_by_design+++def test_rule_level_inherit_false_cuts_ancestors_for_matching_paths_only(tmp_path: Path) -> None:+ _write(tmp_path, "a/owners.yaml", "version: 1\nowners: [team-a]\n")+ _write(+ tmp_path,+ "a/b/owners.yaml",+ "version: 1\nowners: []\nrules:\n - match: '/cut/'\n owners: [team-b]\n inherit: false\n",+ )+ resolver = OwnersResolver(repo_root=tmp_path)+ cut = resolver.resolve("a/b/cut/x.py")+ assert cut.owners == ["team-b"] # rule-level inherit:false + own owners win+ other = resolver.resolve("a/b/other.py")+ assert other.owners == ["team-a"] # non-matching path still inherits the ancestor+++def test_rule_level_inherit_true_restores_ancestors_under_file_level_cut(tmp_path: Path) -> None:+ # The inverse direction: the file cuts inheritance, a rule opts its paths+ # back in. The cut must apply after rule overrides — applying it while+ # collecting files made this documented override a silent no-op.+ _write(tmp_path, "owners.yaml", "version: 1\nowners: [team-root]\n")+ _write(+ tmp_path,+ "a/owners.yaml",+ "version: 1\nowners: []\ninherit: false\nrules:\n - match: '/keep/'\n inherit: true\n",+ )+ resolver = OwnersResolver(repo_root=tmp_path)+ assert resolver.resolve("a/x.py").owners is None # file-level cut holds+ assert resolver.resolve("a/keep/x.py").owners == ["team-root"] # rule restores+++def test_invalid_rule_glob_is_a_schema_error_not_a_crash(tmp_path: Path) -> None:+ _write(+ tmp_path,+ "a/owners.yaml",+ "version: 1\nowners: [team-a]\nrules:\n - match: 'a***b'\n owners: [team-b]\n",+ )+ parsed, errors = parse_owners_file(+ (tmp_path / "a/owners.yaml").read_text(), path=tmp_path / "a/owners.yaml", directory="a"+ )+ assert any("invalid match pattern" in e for e in errors)+ assert parsed is not None and parsed.rules == [] # rule dropped, file still usable+ # The resolver never sees the uncompilable rule, so resolution doesn't raise.+ assert OwnersResolver(repo_root=tmp_path).resolve("a/x.py").owners == ["team-a"]+++ "owners_yaml,expected",+ [+ ("owners: team-a", ["team-a"]),+ ("owners: '@someone'", ["@someone"]),+ ("owners: ''", None), # empty string is a schema error, not a bogus [''] owner+ ("owners: ['']", None), # a [''] list would count as covered while the assigner pings nobody+ ("owners: [team-a, '']", None),+ ],+)+def test_bare_string_owners_normalizes_to_single_element_list(+ tmp_path: Path, owners_yaml: str, expected: list[str] | None+) -> None:+ text = f"version: 1\n{owners_yaml}\nrules:\n - match: 'sub/'\n {owners_yaml}\n"+ parsed, errors = parse_owners_file(text, path=tmp_path / "owners.yaml", directory="")+ if expected is None:+ assert any("'owners' must be" in e for e in errors)+ else:+ assert errors == []+ assert parsed is not None+ assert parsed.owners == expected+ assert parsed.rules[0].owners == expected+++def test_multi_match_explodes_to_one_rule_per_pattern(tmp_path: Path) -> None:+ # A list `match:` becomes one OwnersRule per pattern, in order, each carrying the+ # rule's shared owners/status — so resolver/fmt/lint keep seeing single-pattern rules.+ text = (+ "version: 1\nowners: [team-a]\n"+ "rules:\n - match: [Dockerfile, 'docker-compose*.yml']\n owners: [team-infra]\n status: generated\n"+ )+ parsed, errors = parse_owners_file(text, path=tmp_path / "owners.yaml", directory="")+ assert errors == []+ assert parsed is not None+ assert [r.match for r in parsed.rules] == ["Dockerfile", "docker-compose*.yml"]+ assert all(r.owners == ["team-infra"] and r.status == "generated" for r in parsed.rules)+++ "rules_yaml,needle",+ [+ ("rules:\n - match: []\n owners: [team-b]\n", "non-empty list of strings"),+ ("rules:\n - match: ['ok', '']\n owners: [team-b]\n", "each 'match' pattern must be a non-empty string"),+ ("rules:\n - match: ['ok', 123]\n owners: [team-b]\n", "each 'match' pattern must be a non-empty string"),+ ("rules:\n - match: ['ok', 'a***b']\n owners: [team-b]\n", "invalid match pattern 'a***b'"),+ ],+)+def test_multi_match_validation_errors_drop_the_rule(tmp_path: Path, rules_yaml: str, needle: str) -> None:+ # A malformed element anywhere in a list `match:` is a schema error that drops the+ # whole rule, leaving the file usable (never a rule the resolver could crash on).+ text = "version: 1\nowners: [team-a]\n" + rules_yaml+ parsed, errors = parse_owners_file(text, path=tmp_path / "owners.yaml", directory="")+ assert any(needle in e for e in errors)+ assert parsed is not None and parsed.rules == []+++def test_multi_match_rule_wins_and_loses_under_last_match(tmp_path: Path) -> None:+ # The exploded patterns take part in last-match-wins like any rule: the later+ # multi-match rule overrides the earlier `*.yml` for its patterns only.+ _write(+ tmp_path,+ "owners.yaml",+ "version: 1\nowners: [team-a]\n"+ "rules:\n - match: '*.yml'\n owners: [team-yaml]\n"+ " - match: [Dockerfile, 'docker-compose*.yml']\n owners: [team-infra]\n",+ )+ resolver = OwnersResolver(repo_root=tmp_path)+ assert resolver.resolve("Dockerfile").owners == ["team-infra"]+ assert resolver.resolve("docker-compose.dev.yml").owners == ["team-infra"] # beats earlier *.yml+ assert resolver.resolve("other.yml").owners == ["team-yaml"] # only *.yml matches+ assert resolver.resolve("main.py").owners == ["team-a"] # no rule matches+++def test_resolver_no_contribution_is_unowned_not_exempt(tmp_path: Path) -> None:+ _write(tmp_path, "posthog/owners.yaml", "version: 1\nowners: [team-a]\n")+ resolver = OwnersResolver(repo_root=tmp_path)+ r = resolver.resolve("other/file.py")+ assert r.owners is None+ assert r.unowned_by_design is False+ assert resolver.unowned(["other/file.py", "posthog/x.py"]) == ["other/file.py"]+++ "path,slack",+ [+ ("posthog/x.py", "#team-a"),+ ("posthog/sub/y.py", "#team-b"),+ ("posthog/noinherit/z.py", "#team-c"),+ ("products/foo/thing.py", "#team-foo"),+ ],+)+def test_resolver_slack_derivation_and_fallthrough(resolver_repo: Path, path: str, slack: str) -> None:+ assert OwnersResolver(repo_root=resolver_repo).resolve(path).slack == slack+++def registry_repo(tmp_path: Path) -> Path:+ _write(+ tmp_path,+ "owners.yaml",+ "version: 1\nowners: []\nteams:\n"+ " team-registry:\n slack: '#registry-chan'\n"+ " team-silent:\n slack: false\n",+ )+ _write(tmp_path, "reg/owners.yaml", "version: 1\nowners: [team-registry]\n")+ _write(tmp_path, "silent/owners.yaml", "version: 1\nowners: [team-silent]\n")+ _write(tmp_path, "derive/owners.yaml", "version: 1\nowners: [team-nonreg]\n")+ _write(tmp_path, "indiv/owners.yaml", "version: 1\nowners: ['@alice', team-registry]\n")+ return tmp_path+++ "path,slack",+ [+ ("reg/x.py", "#registry-chan"), # registry hit for the primary owner beats derived+ ("silent/x.py", None), # registry false suppresses derivation+ ("derive/x.py", "#team-nonreg"), # no registry entry: derive #<primary owner>+ ("indiv/x.py", None), # primary owner is an @handle: registry ignored, no derive+ ],+)+def test_slack_registry_precedence(registry_repo: Path, path: str, slack: str | None) -> None:+ assert OwnersResolver(repo_root=registry_repo).resolve(path).slack == slack+++def test_teams_registry_is_root_only(tmp_path: Path) -> None:+ text = "version: 1\nowners: [team-a]\nteams:\n team-a:\n slack: '#a'\n"+ _, sub_errors = parse_owners_file(text, path=tmp_path / "sub/owners.yaml", directory="sub")+ assert any("only allowed in the repo-root" in e for e in sub_errors)+ root, root_errors = parse_owners_file(text, path=tmp_path / "owners.yaml", directory="")+ assert root_errors == []+ assert root is not None and root.teams == {"team-a": "#a"}+++ "teams_yaml,needle",+ [+ ("teams: [team-a]\n", "'teams' must be a mapping"),+ ("teams:\n team-a:\n slack: 'no-hash'\n", "must be a string starting with '#' or false"),+ ("teams:\n team-a:\n channel: '#a'\n", "unknown field 'channel'"),+ ("teams:\n team-a: '#a'\n", "entry must be a mapping"),+ ("teams:\n '@alice':\n slack: '#a'\n", "not @handles"),+ ("teams:\n 123:\n slack: '#a'\n", "slug must be a string"),+ ],+)+def test_teams_registry_invalid_shapes(tmp_path: Path, teams_yaml: str, needle: str) -> None:+ text = "version: 1\nowners: []\n" + teams_yaml+ file, errors = parse_owners_file(text, path=tmp_path / "owners.yaml", directory="")+ assert any(needle in e for e in errors)+ assert file is not None # a bad registry entry doesn't make the file unusable+++def test_teams_registry_pins_file_as_non_simple(tmp_path: Path) -> None:+ text = "version: 1\nowners: [team-a]\nteams:\n team-a:\n slack: '#a'\n"+ file, _ = parse_owners_file(text, path=tmp_path / "owners.yaml", directory="")+ assert file is not None+ assert is_simple_owners_file(file) is False+ assert is_simple_owners_file(file, allow_anchored_rules=True) is False+++ "rel,reserved",+ [+ (".github/workflows/owners.yaml", True),+ (".github/workflows/sub/owners.yaml", True),+ ("products/error_tracking/mcp/owners.yaml", True),+ ("products/foo/mcp/sub/owners.yaml", True),+ (".github/owners.yaml", False),+ ("products/foo/backend/owners.yaml", False),+ ("mcp/owners.yaml", False),+ ],+)+def test_reserved_location_error(rel: str, reserved: bool) -> None:+ assert (_reserved_location_error(rel) is not None) is reserved+++ "owners_dirs,expected",+ [+ # Branch point with enough simple files spread across children fires.+ ({"a/b": True, "a/c": True, "a/d": True, "a/e": True, "a/f": True}, [("a", 5)]),+ # Exactly at threshold (3) across ≥2 children fires.+ ({"a/b": True, "a/c": True, "a/d": True}, [("a", 3)]),+ # Below threshold stays quiet.+ ({"a/b": True, "a/c": True}, []),+ # A passthrough ancestor (all files under one child) yields the deeper branch point only.+ (+ {"a/b/1": True, "a/b/2": True, "a/b/3": True, "a/b/4": True, "a/b/5": True},+ [("a/b", 5)],+ ),+ # A non-simple file between parent and files keeps that subtree out of the count.+ (+ {+ "a/b": True,+ "a/c": True,+ "a/mid": False,+ "a/mid/f": True,+ "a/mid/g": True,+ },+ [],+ ),+ # Nested branch points report only the deepest.+ (+ {"a/b/1": True, "a/b/2": True, "a/b/3": True, "a/b/4": True, "a/b/5": True, "a/c": True, "a/d": True},+ [("a/b", 5)],+ ),+ ],+)+def test_consolidation_suggestions(owners_dirs: dict[str, bool], expected: list[tuple[str, int]]) -> None:+ assert _consolidation_suggestions(owners_dirs) == expected+++def _fmt_plan(tmp_path: Path, files: dict[str, str]) -> CanonicalPlan:+ for rel, text in files.items():+ _write(tmp_path, rel, text)+ subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)+ subprocess.run(["git", "add", "-A"], cwd=tmp_path, check=True)+ return CanonicalPlacer(OwnersResolver(repo_root=tmp_path)).build()+++def test_fmt_folds_dedicated_child_into_pinned_parent(tmp_path: Path) -> None:+ # `a` is a pinned carrier (non-simple, carries a status); `a/b` is a dedicated+ # single-statement file. Canonical folds b's statement into a and drops the file.+ plan = _fmt_plan(+ tmp_path,+ {+ "a/owners.yaml": "version: 1\nowners: [team-a]\nstatus: deprecated\n",+ "a/f.py": "x",+ "a/b/owners.yaml": "version: 1\nowners: [team-b]\n",+ "a/b/g.py": "x",+ "r1.py": "x",+ "r2.py": "x",+ },+ )+ assert plan.deletions == ["a/b/owners.yaml"]+ assert plan.additions == {"a/owners.yaml": ["/b/ -> [team-b]"]}+ assert plan.creations == []+++def test_fmt_splits_when_carrier_exceeds_capacity(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ # A pinned parent above enough owned sibling dirs to blow past MAX_RULES opens a+ # dedicated child facility under the shared prefix to absorb the overflow.+ monkeypatch.setattr(fmt_module, "MAX_RULES", 3)+ files = {+ "P/owners.yaml": "version: 1\nowners: [team-p]\nstatus: deprecated\n",+ "P/f.py": "x",+ "r1.py": "x",+ "r2.py": "x",+ }+ for i in range(4):+ files[f"P/c/s{i}/owners.yaml"] = f"version: 1\nowners: [team-{i}]\n"+ files[f"P/c/s{i}/g.py"] = "x"+ plan = _fmt_plan(tmp_path, files)+ assert "P/c/owners.yaml" in plan.creations+++def test_fmt_never_exiles_singleton_rules_on_overflow(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ # When every overflow group is a single statement, splitting would recreate the+ # per-dir single-purpose files fmt exists to remove — the cap is soft instead.+ monkeypatch.setattr(fmt_module, "MAX_RULES", 3)+ files = {+ "P/owners.yaml": "version: 1\nowners: [team-p]\nstatus: deprecated\n",+ "P/f.py": "x",+ "r1.py": "x",+ "r2.py": "x",+ }+ for i in range(4):+ files[f"P/d{i}/owners.yaml"] = f"version: 1\nowners: [team-{i}]\n"+ files[f"P/d{i}/g.py"] = "x"+ plan = _fmt_plan(tmp_path, files)+ assert plan.creations == []+++def test_fmt_product_yaml_is_a_free_carrier(tmp_path: Path) -> None:+ # The product manifest already declares ownership, so no dedicated owners.yaml is+ # proposed and nothing is added — a single-statement product is not flagged.+ plan = _fmt_plan(+ tmp_path,+ {+ "products/foo/product.yaml": "name: Foo\nowners:\n - team-foo\n",+ "products/foo/x.py": "x",+ "r1.py": "x",+ "r2.py": "x",+ },+ )+ assert plan.is_canonical+++def test_fmt_never_places_rules_on_a_product_yaml_dir(tmp_path: Path) -> None:+ # A product.yaml manifest only exposes its owners list — it cannot physically hold+ # rules, and an owners.yaml next to it is a lint error. A differently-owned subtree+ # below a product must keep its own file or fold to an ancestor, never produce+ # additions keyed on the product dir.+ plan = _fmt_plan(+ tmp_path,+ {+ "products/foo/product.yaml": "name: Foo\nowners:\n - team-foo\n",+ "products/foo/x.py": "x",+ "products/foo/sub/owners.yaml": "version: 1\nowners: [team-bar]\n",+ "products/foo/sub/y.py": "x",+ "r1.py": "x",+ "r2.py": "x",+ },+ )+ assert "products/foo/owners.yaml" not in plan.additions+ assert "products/foo/owners.yaml" not in plan.creations+++def test_fmt_leaves_glob_files_untouched(tmp_path: Path) -> None:+ # A glob rule is crosscutting, not a tree boundary — fmt must not rewrite it.+ plan = _fmt_plan(+ tmp_path,+ {+ "d/owners.yaml": "version: 1\nowners: []\nrules:\n - match: '*.py'\n owners: [team-a]\n",+ "d/x.py": "x",+ "d/y.py": "x",+ },+ )+ assert plan.is_canonical+++def test_fmt_reports_top_level_owner_edits(tmp_path: Path) -> None:+ # Canonical placement here rewrites the root file's `owners:` ([] -> [team-a])+ # while deleting both children. A plan that only printed the deletions would+ # under-apply: following it literally leaves every file unowned even though+ # the proof passed against the full in-memory proposal.+ plan = _fmt_plan(+ tmp_path,+ {+ "owners.yaml": "version: 1\nowners: []\n",+ "a/owners.yaml": "version: 1\nowners: [team-a]\n",+ "b/owners.yaml": "version: 1\nowners: [team-a]\n",+ "a/f.py": "x",+ "b/g.py": "x",+ },+ )+ assert not plan.is_canonical+ assert sorted(plan.deletions) == ["a/owners.yaml", "b/owners.yaml"]+ assert any("owners: [] -> [team-a]" in line for line in plan.additions.get("owners.yaml", []))+++def test_fmt_reports_rule_owner_changes(tmp_path: Path) -> None:+ # The carrier already holds a `/a/` rule with stale owners; canonical placement+ # keeps the match but flips the owners. A diff that only checks for new match+ # strings would print nothing but the deletion, and applying that literally+ # would route a/** to the stale team.+ plan = _fmt_plan(+ tmp_path,+ {+ "owners.yaml": "version: 1\nowners: []\nrules:\n - match: '/a/'\n owners: [team-old]\n",+ "a/owners.yaml": "version: 1\nowners: [team-new]\n",+ "a/f.py": "x",+ "r1.py": "x",+ },+ )+ assert "a/owners.yaml" in plan.deletions+ assert "/a/: [team-old] -> [team-new]" in plan.additions.get("owners.yaml", [])+++def test_fmt_preserves_unowned_by_design_exemptions(tmp_path: Path) -> None:+ # An `owners: null` child under a no-contribution parent must survive as an+ # explicit statement — collapsing it into plain unowned would delete the file+ # with no replacement and silently drop the coverage exemption.+ plan = _fmt_plan(+ tmp_path,+ {+ "owners.yaml": "version: 1\nowners: []\n",+ "a/owners.yaml": "version: 1\nowners: null\n",+ "a/f.py": "x",+ "r1.py": "x",+ },+ )+ if "a/owners.yaml" in plan.deletions:+ assert "/a/ -> (unowned)" in plan.additions.get("owners.yaml", [])+++def test_fmt_reports_stale_rule_removals(tmp_path: Path) -> None:+ # `/b/` restates what the file's own owners already provide; canonical layout+ # drops it. The product.yaml alias above blocks carry-up, so the backend file+ # must stay open — a plan that stayed silent about the shed rule would report+ # is_canonical while the stale rule (and the cost difference) persists.+ plan = _fmt_plan(+ tmp_path,+ {+ "owners.yaml": "version: 1\nowners: []\n",+ "products/foo/product.yaml": "name: Foo\nowners:\n - team-p\n",+ "products/foo/x.py": "x",+ "products/foo/backend/owners.yaml": (+ "version: 1\nowners: [team-a]\nrules:\n - match: '/b/'\n owners: [team-a]\n"+ ),+ "products/foo/backend/b/f.py": "x",+ "products/foo/backend/g.py": "x",+ "r1.py": "x",+ },+ )+ assert not plan.is_canonical+ assert "drop /b/ (was [team-a])" in plan.additions.get("products/foo/backend/owners.yaml", [])+ assert "products/foo/backend/owners.yaml" not in plan.deletions+++def test_fmt_frozen_file_blocks_carry_up(tmp_path: Path) -> None:+ # d's glob file is frozen; d/sub's boundary must not be carried above d, or+ # the untouched nearer file would shadow the ancestor rule and the proof+ # would fail — this layout used to crash build() with a proof AssertionError.+ plan = _fmt_plan(+ tmp_path,+ {+ "owners.yaml": "version: 1\nowners: []\n",+ "d/owners.yaml": "version: 1\nowners: [team-d]\nrules:\n - match: '*.py'\n owners: [team-d]\n",+ "d/sub/owners.yaml": "version: 1\nowners: [team-s]\n",+ "d/sub/f.py": "x",+ "d/g.py": "x",+ "r1.py": "x",+ },+ )+ assert "d/sub/owners.yaml" not in plan.deletions+++def test_fmt_proof_rejects_plans_that_drop_status(tmp_path: Path) -> None:+ # Folding the child appends an owner-only '/gen/' rule after the parent's+ # status-only '/gen/' rule; last-match-wins then loses `generated` while+ # owners stay identical. The proof must refuse such a plan, not print it.+ with pytest.raises(AssertionError, match="fmt bug"):+ _fmt_plan(+ tmp_path,+ {+ "owners.yaml": "version: 1\nowners: []\n",+ "a/owners.yaml": ("version: 1\nowners: [team-a]\nrules:\n - match: '/gen/'\n status: generated\n"),+ "a/gen/owners.yaml": "version: 1\nowners: [team-g]\n",+ "a/gen/f.py": "x",+ "a/f.py": "x",+ "r1.py": "x",+ },+ )+++def test_fmt_pins_files_with_rule_level_metadata(tmp_path: Path) -> None:+ # Relocation only preserves match+owners, so a rule carrying status/inherit+ # must pin its file exactly like a glob does — otherwise folding this child+ # into the parent would silently drop the generated status.+ plan = _fmt_plan(+ tmp_path,+ {+ "a/owners.yaml": "version: 1\nowners: [team-a]\nstatus: deprecated\n",+ "a/f.py": "x",+ "a/b/owners.yaml": (+ "version: 1\nowners: [team-b]\nrules:\n - match: '/gen/'\n owners: [team-b]\n status: generated\n"+ ),+ "a/b/gen/g.py": "x",+ "r1.py": "x",+ "r2.py": "x",+ },+ )+ assert plan.is_canonical+++def test_fmt_is_idempotent_on_canonical_layout(tmp_path: Path) -> None:+ # A layout already in canonical form (child folded into the pinned parent) yields+ # no proposed moves.+ plan = _fmt_plan(+ tmp_path,+ {+ "a/owners.yaml": "version: 1\nowners: [team-a]\nstatus: deprecated\n"+ "rules:\n - match: '/b/'\n owners: [team-b]\n",+ "a/f.py": "x",+ "a/b/g.py": "x",+ "r1.py": "x",+ "r2.py": "x",+ },+ )+ assert plan.is_canonical+++def test_fmt_equivalence_proof_catches_a_wrong_layout(tmp_path: Path) -> None:+ # The built-in proof must hard-fail if the proposed layout ever resolves a path+ # differently from the current one — corrupt the expected map and confirm it raises.+ for rel, text in {"a/owners.yaml": "version: 1\nowners: [team-a]\n", "a/f.py": "x"}.items():+ _write(tmp_path, rel, text)+ subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)+ subprocess.run(["git", "add", "-A"], cwd=tmp_path, check=True)+ placer = CanonicalPlacer(OwnersResolver(repo_root=tmp_path))+ with pytest.raises(AssertionError):+ placer._prove({}, {"a/f.py": ("team-wrong",)})diff --git a/tools/pr-approval-agent/README.md b/tools/pr-approval-agent/README.mdindex 7995815dfb1a..884eccf7117d 100644--- a/tools/pr-approval-agent/README.md+++ b/tools/pr-approval-agent/README.md@@ -5,6 +5,8 @@ Deterministic safety gates first, then Claude reviews for showstoppers.> [!NOTE]> This directory (together with `.stamphog/`) is vendored into other repos — e.g. [MLHog](https://github.com/PostHog/MLHog/tree/master/tools/pr-approval-agent) — each documenting its intentional local changes in its own copy of this README. When you change the engine or policy format here, those copies stay stale until someone re-syncs them, so give the owning teams a heads-up (or re-sync yourself: diff, re-copy, re-apply their documented local changes).+> A policy that declares a `hogli-resolver` ownership source additionally needs the sibling `tools/owners` package vendored.+> The legacy `gh-codeowners` / `ph-product` ownership formats were removed together with the `CODEOWNERS-soft` migration, so a vendored copy whose policy still declares them must migrate to `hogli-resolver` (adopting `owners.yaml` + `tools/owners`) as part of the re-sync — or skip the re-sync and keep its previous engine until it's ready. The policy loader rejects unknown formats loudly at startup, so a missed migration fails closed rather than silently skipping the ownership source.## Usage@@ -208,12 +210,13 @@ If the check hasn't completed yet when stamphog runs, stamphog refuses with a meOwnership context for the LLM (not a hard gate). The sources are declared in`.stamphog/policy.yml` under `ownership:` and read from the master checkout: a-`gh-codeowners` source (`.github/CODEOWNERS-soft`, last-match-wins) plus a-`ph-product` source (`products/*/product.yaml` owners). A file's owning teams-are the union across all sources, so stamphog sees the same merged view the-reviewer auto-assigner builds. Cross-team typo/test/comment fixes are fine, as-are small well-tested behavioral fixes (T1a/T1b) with no outstanding reviewer-concerns; API contract, data model, and larger behavioral changes get escalated.+`hogli-resolver` source that resolves ownership through the shared hogli+resolver over the distributed `owners.yaml` / `product.yaml` files. A file's+owning teams are the union across all sources, so stamphog sees the same merged+view the reviewer auto-assigner builds. Cross-team typo/test/comment fixes are+fine, as are small well-tested behavioral fixes (T1a/T1b) with no outstanding+reviewer concerns; API contract, data model, and larger behavioral changes get+escalated.## Versioningdiff --git a/tools/pr-approval-agent/gates.py b/tools/pr-approval-agent/gates.pyindex e54c5ae9b770..34f842016d57 100644--- a/tools/pr-approval-agent/gates.py+++ b/tools/pr-approval-agent/gates.py@@ -4,20 +4,33 @@ Handles deny-lists, allow-lists, multi-source ownership (declared in`.stamphog/policy.yml`), tier assignment, and file classification. Policy dataloads from .stamphog/policy.yml at import via policy.py, which needs PyYAML:any uv-run script that imports this module must declare pyyaml in its PEP 723-dependencies block.+dependencies block. Ownership goes through the shared hogli resolver rather+than a private parser — one semantics, many consumers."""import re+import sysfrom collections import Counterfrom collections.abc import Callablefrom dataclasses import dataclassfrom fnmatch import fnmatchfrom pathlib import Path-from typing import Protocol+from typing import TYPE_CHECKING, Protocol-import yamlfrom policy import OwnershipSource, load_policy+if TYPE_CHECKING:+ from posthog_owners.resolver import OwnersResolver++# The resolver lives in the posthog-owners package, a sibling under tools/. It is+# not installed in this script's uv env, so it is put on the path and imported as+# a library (it needs only pyyaml, which review_pr.py declares). The import is+# deferred to _build_hogli_resolver: downstream repos vendor this directory+# (plus .stamphog/) without tools/owners, and a module-level import would+# disable their stamphog copy before any gate runs — the package is only+# required once a policy actually declares a hogli-resolver ownership source.+_OWNERS_PKG = Path(__file__).resolve().parents[1] / "owners"+# ── Dependency ecosystems ────────────────────────────────────────## Source of truth for how each package ecosystem pairs manifests with@@ -141,10 +154,10 @@ def _ecosystem_for_manifest(name: str) -> str | None:# Ownership is advisory reviewer context, not a hard gate. The sources are# declared in `.stamphog/policy.yml` (`ownership:`) and compiled here into# resolvers; each resolver answers "which teams own this file?" and the-# per-file result is the union across sources. Two formats ship today:-# `gh-codeowners` (a CODEOWNERS-soft file, last-match-wins) and `ph-product`-# (products/*/product.yaml owners). OWNERSHIP_FORMATS is the single place a new-# format registers.+# per-file result is the union across sources. One format ships today:+# `hogli-resolver`, which delegates to the shared hogli `OwnersResolver` over+# the distributed `owners.yaml` / `product.yaml` files. OWNERSHIP_FORMATS is the+# single place a new format registers.class OwnershipResolver(Protocol):@@ -153,119 +166,53 @@ class OwnershipResolver(Protocol):def owners(self, filepath: str) -> set[str]: ...-class CodeownersRule:- def __init__(self, pattern: str, teams: list[str]):- self.raw_pattern = pattern- self.teams = set(teams)- self._pattern = pattern.lstrip("/").replace("\\*\\*", "**").replace("\\*", "*")-- def matches(self, filepath: str) -> bool:- pat = self._pattern- if not any(c in pat for c in ("*", "?")):- if filepath == pat or filepath == pat.rstrip("/"):- return True- prefix = pat if pat.endswith("/") else pat + "/"- if filepath.startswith(prefix):- return True- return False- if fnmatch(filepath, pat):- return True- if "**" in pat and fnmatch(filepath, pat.rstrip("/") + "/**"):- return True- return False---def parse_codeowners_soft(path: Path) -> list[CodeownersRule]:- rules = []- if not path.exists():- return rules- with open(path) as f:- for line in f:- line = line.strip()- if not line or line.startswith("#"):- continue- parts = line.split()- if len(parts) < 2:- continue- pattern = parts[0]- teams = [t for t in parts[1:] if t.startswith("@")]- if teams:- rules.append(CodeownersRule(pattern, teams))- return rules---def resolve_owners(filepath: str, rules: list[CodeownersRule]) -> set[str]:- matched_teams: set[str] = set()- for rule in rules:- if rule.matches(filepath):- matched_teams = rule.teams- return matched_teams---class _CodeownersResolver:- """gh-codeowners: last-match-wins CODEOWNERS-soft semantics over one file."""-- def __init__(self, rules: list[CodeownersRule]) -> None:- self._rules = rules+def _owner_to_team_handle(owner: str) -> str | None:+ """Map a resolver owner to the handle shape the advisory context uses.- def owners(self, filepath: str) -> set[str]:- return set(resolve_owners(filepath, self._rules))---def _normalize_product_owner(slug: object) -> str | None:- """Normalize a product.yaml owner slug exactly like assign-reviewers.js.-- Skip empty / `team-CHANGEME` / already-`@`-prefixed slugs (an existing- prefix would build `@PostHog/@PostHog/...`); otherwise prefix `@PostHog/`.+ Resolver owners are bare team slugs (`team-foo`) plus `@handle` individuals.+ Team slugs become `@PostHog/<slug>` (the shape the reviewer prompt expects);+ individuals pass through unchanged so individually-owned paths count as+ owned instead of reporting no ownership-source match. The `team-CHANGEME`+ placeholder is already filtered by the resolver's parsers."""- if not isinstance(slug, str):- return None- slug = slug.strip()- if not slug or slug == "team-CHANGEME" or slug.startswith("@"):+ if not owner:return None- return f"@PostHog/{slug}"-+ if owner.startswith("@"):+ return owner+ return f"@PostHog/{owner}"-def _read_product_owners(path: Path) -> frozenset[str]:- """Normalized owners from a product.yaml, or empty on any parse/shape problem."""- try:- data = yaml.safe_load(path.read_text())- except (OSError, yaml.YAMLError):- return frozenset()- if not isinstance(data, dict) or not isinstance(data.get("owners"), list):- return frozenset()- teams = {norm for slug in data["owners"] if (norm := _normalize_product_owner(slug)) is not None}- return frozenset(teams)+class _HogliResolver:+ """hogli-resolver: the shared hogli resolver over distributed ownership files.-class _ProductYamlResolver:- """ph-product: each product.yaml owns its parent directory subtree."""+ `OwnersResolver` walks `owners.yaml` / `product.yaml` from the repo root and+ merges nearest-file-wins, so it subsumes the old CODEOWNERS-soft parser and+ the separate product.yaml reader — one ownership semantics, many consumers.+ """- def __init__(self, owned_dirs: dict[str, frozenset[str]]) -> None:- # Maps a repo-relative directory (posix, no trailing slash) to its owners.- self._owned_dirs = owned_dirs+ def __init__(self, resolver: "OwnersResolver") -> None:+ self._resolver = resolverdef owners(self, filepath: str) -> set[str]:- result: set[str] = set()- for directory, teams in self._owned_dirs.items():- if filepath.startswith(directory + "/"):- result |= teams- return result-+ resolved = self._resolver.resolve(filepath).owners or []+ return {handle for owner in resolved if (handle := _owner_to_team_handle(owner))}-def _build_codeowners_resolver(repo_root: Path, source: OwnershipSource) -> _CodeownersResolver:- assert source.path is not None # validated by the loader (gh-codeowners uses `path`)- return _CodeownersResolver(parse_codeowners_soft(repo_root / source.path))--def _build_product_yaml_resolver(repo_root: Path, source: OwnershipSource) -> _ProductYamlResolver:- assert source.glob is not None # validated by the loader (ph-product uses `glob`)- owned_dirs: dict[str, frozenset[str]] = {}- for yaml_path in sorted(repo_root.glob(source.glob)):- teams = _read_product_owners(yaml_path)- if teams:- owned_dirs[yaml_path.parent.relative_to(repo_root).as_posix()] = teams- return _ProductYamlResolver(owned_dirs)+def _build_hogli_resolver(repo_root: Path, source: OwnershipSource) -> _HogliResolver:+ if str(_OWNERS_PKG) not in sys.path:+ sys.path.insert(0, str(_OWNERS_PKG))+ try:+ from posthog_owners.resolver import (+ OwnersResolver, # noqa: PLC0415 — absent in vendored copies; needed only for this format+ )+ except ImportError as exc:+ raise RuntimeError(+ "ownership format 'hogli-resolver' requires the posthog-owners package: "+ "vendor tools/owners alongside tools/pr-approval-agent, or drop the "+ "hogli-resolver source from .stamphog/policy.yml"+ ) from exc+ assert source.path is not None # validated by the loader (hogli-resolver uses `path`)+ return _HogliResolver(OwnersResolver(repo_root=repo_root / source.path))@dataclass(frozen=True)@@ -280,8 +227,7 @@ class OwnershipFormat:# entry here plus its resolver above; the loader validates each declared# source's format name and locator pairing against this table.OWNERSHIP_FORMATS: dict[str, OwnershipFormat] = {- "gh-codeowners": OwnershipFormat("path", _build_codeowners_resolver),- "ph-product": OwnershipFormat("glob", _build_product_yaml_resolver),+ "hogli-resolver": OwnershipFormat("path", _build_hogli_resolver),}OWNERSHIP_FORMAT_LOCATORS: dict[str, str] = {name: fmt.locator for name, fmt in OWNERSHIP_FORMATS.items()}@@ -293,19 +239,27 @@ def build_ownership(repo_root: Path, sources: tuple[OwnershipSource, ...]) -> lidef detect_ownership(files: list[str], resolvers: list[OwnershipResolver]) -> dict:- """Aggregate per-file team ownership, unioning each source's owners per file."""+ """Aggregate per-file ownership, unioning each source's owners per file.++ Individuals (`@handle`) count toward owned/unowned but live in their own+ bucket: `teams` feeds team-membership checks and the cross-team calculus+ downstream, and a raw handle there would fail membership lookups and inflate+ the team count."""all_teams: set[str] = set()+ all_individuals: set[str] = set()owned_files = 0unowned_files = 0team_file_counts: Counter = Counter()for f in files:- teams: set[str] = set()+ owners: set[str] = set()for resolver in resolvers:- teams |= resolver.owners(f)- if teams:+ owners |= resolver.owners(f)+ teams = {o for o in owners if o.startswith("@PostHog/")}+ if owners:owned_files += 1all_teams.update(teams)+ all_individuals.update(owners - teams)for t in teams:team_file_counts[t] += 1else:@@ -313,6 +267,7 @@ def detect_ownership(files: list[str], resolvers: list[OwnershipResolver]) -> direturn {"teams": sorted(all_teams),+ "individuals": sorted(all_individuals),"team_count": len(all_teams),"owned_files": owned_files,"unowned_files": unowned_files,diff --git a/tools/pr-approval-agent/review_pr.py b/tools/pr-approval-agent/review_pr.pyindex af9c793310c8..9c58449b33de 100644--- a/tools/pr-approval-agent/review_pr.py+++ b/tools/pr-approval-agent/review_pr.py@@ -576,7 +576,8 @@ class Pipeline:def _summarize_ownership(self) -> str:"""Build ownership context for the LLM (not a hard gate)."""ownership = self.classification["ownership"]- if ownership["team_count"] == 0:+ individuals = ownership.get("individuals", [])+ if ownership["team_count"] == 0 and not individuals:self.classification["ownership_summary"] = "no owned paths touched"return self.classification["ownership_summary"]@@ -588,10 +589,17 @@ class Pipeline:if check_team_membership(author, team_slug):author_teams.append(team_raw)- parts = [f"touches {', '.join(teams)}"]+ parts = []+ if teams:+ parts.append(f"touches {', '.join(teams)}")+ if individuals:+ # Individuals never enter the membership check — the author simply+ # is or isn't one of them.+ suffix = f" (author {author} is one of them)" if f"@{author}" in individuals else ""+ parts.append(f"individually owned by {', '.join(individuals)}{suffix}")if author_teams:parts.append(f"author {author} is on {', '.join(author_teams)}")- else:+ elif teams:parts.append(f"author {author} is not on any owning team")if ownership["cross_team"]:parts.append("cross-team change")diff --git a/tools/pr-approval-agent/reviewer.py b/tools/pr-approval-agent/reviewer.pyindex 6fe531041ec3..2043599a0c2f 100644--- a/tools/pr-approval-agent/reviewer.py+++ b/tools/pr-approval-agent/reviewer.py@@ -651,7 +651,8 @@ class Reviewer:def _format_ownership(self, cl: dict) -> str:ownership = cl.get("ownership", {})teams = ownership.get("teams", [])- if not teams:+ individuals = ownership.get("individuals", [])+ if not teams and not individuals:return "Ownership: no ownership-source match"summary = cl.get("ownership_summary", "")on_team = cl.get("author_on_owning_team", True)@@ -659,7 +660,9 @@ class Reviewer:lines = [f"Ownership: {summary}"]if per_team:lines.append(f" Files per team: {json.dumps(per_team)}")- if not on_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:lines.append(" NOTE: Author is NOT on the owning team")if ownership.get("cross_team"):lines.append(" NOTE: Cross-team change")diff --git a/tools/pr-approval-agent/test_gates.py b/tools/pr-approval-agent/test_gates.pyindex 22e161f611f8..22574784668d 100644--- a/tools/pr-approval-agent/test_gates.py+++ b/tools/pr-approval-agent/test_gates.py@@ -506,53 +506,50 @@ def test_dismiss_time_trust_is_opt_in_per_ecosystem() -> None:# ── Ownership sources ────────────────────────────────────────────-_PH_PRODUCT = (OwnershipSource(format="ph-product", glob="products/*/product.yaml"),)+_HOGLI_RESOLVER = (OwnershipSource(format="hogli-resolver", path="."),)@pytest.mark.parametrize(- "owners_yaml, expected_teams",+ "owners_yaml, expected_teams, expected_individuals, expected_owned",[- pytest.param("owners:\n - team-devex\n", ["@PostHog/team-devex"], id="plain-slug-prefixed"),- pytest.param("owners:\n - '@PostHog/team-x'\n", [], id="already-prefixed-skipped"),- pytest.param("owners:\n - team-CHANGEME\n", [], id="changeme-skipped"),- pytest.param("name: foo\n", [], id="ownerless"),- pytest.param("owners: value: bad\n", [], id="unparseable"),+ pytest.param("owners:\n - team-devex\n", ["@PostHog/team-devex"], [], 1, id="plain-slug-prefixed"),+ # Individuals count as owned but stay out of `teams`, which feeds+ # team-membership checks and the cross-team calculus downstream.+ pytest.param("owners:\n - '@handle'\n", [], ["@handle"], 1, id="individual-own-bucket"),+ pytest.param("name: foo\n", [], [], 0, id="ownerless"),],)-def test_product_yaml_owner_normalization(tmp_path: Path, owners_yaml: str, expected_teams: list[str]) -> None:+def test_resolver_owner_normalization(+ tmp_path: Path,+ owners_yaml: str,+ expected_teams: list[str],+ expected_individuals: list[str],+ expected_owned: int,+) -> None:product_dir = tmp_path / "products" / "foo"product_dir.mkdir(parents=True)(product_dir / "product.yaml").write_text(owners_yaml)- resolvers = build_ownership(tmp_path, _PH_PRODUCT)+ resolvers = build_ownership(tmp_path, _HOGLI_RESOLVER)ownership = detect_ownership(["products/foo/backend/models.py"], resolvers)assert ownership["teams"] == expected_teams+ assert ownership["individuals"] == expected_individuals+ assert ownership["owned_files"] == expected_owned+ assert ownership["cross_team"] is False-def test_ownership_unions_codeowners_and_product_yaml(tmp_path: Path) -> None:- codeowners = tmp_path / ".github" / "CODEOWNERS-soft"- codeowners.parent.mkdir(parents=True)- codeowners.write_text("products/foo/sub/ @PostHog/team-a\nposthog/ @PostHog/team-c\n")+def test_ownership_cross_team_and_unowned(tmp_path: Path) -> None:product_dir = tmp_path / "products" / "foo"product_dir.mkdir(parents=True)- (product_dir / "product.yaml").write_text("owners:\n - team-b\n")+ (product_dir / "product.yaml").write_text("owners:\n - team-a\n - team-b\n")- resolvers = build_ownership(- tmp_path,- (- OwnershipSource(format="gh-codeowners", path=".github/CODEOWNERS-soft"),- OwnershipSource(format="ph-product", glob="products/*/product.yaml"),- ),- )-- both = detect_ownership(["products/foo/sub/x.py"], resolvers)- assert both["teams"] == ["@PostHog/team-a", "@PostHog/team-b"]- assert both["cross_team"] is True+ resolvers = build_ownership(tmp_path, _HOGLI_RESOLVER)- product_only = detect_ownership(["products/foo/y.py"], resolvers)- assert product_only["teams"] == ["@PostHog/team-b"]- assert product_only["cross_team"] is False+ owned = detect_ownership(["products/foo/sub/x.py"], resolvers)+ assert owned["teams"] == ["@PostHog/team-a", "@PostHog/team-b"]+ assert owned["cross_team"] is Trueoutside = detect_ownership(["posthog/models/x.py"], resolvers)- assert outside["teams"] == ["@PostHog/team-c"]+ assert outside["teams"] == []+ assert outside["unowned_files"] == 1diff --git a/tools/pr-approval-agent/test_policy.py b/tools/pr-approval-agent/test_policy.pyindex 18886e0f2884..2ad19ea49f5e 100644--- a/tools/pr-approval-agent/test_policy.py+++ b/tools/pr-approval-agent/test_policy.py@@ -239,7 +239,7 @@ def _ownership_path_escapes_repo(d: dict) -> None:def _ownership_wrong_locator_for_format(d: dict) -> None:- d["ownership"]["sources"][1] = {"format": "ph-product", "path": "products/foo/product.yaml"}+ d["ownership"]["sources"][0] = {"format": "hogli-resolver", "glob": "products/*/product.yaml"}@pytest.mark.parametrize(diff --git a/tools/pr-approval-agent/test_reviewer.py b/tools/pr-approval-agent/test_reviewer.pyindex c7fd2bb5e401..b3d8e286d95f 100644--- a/tools/pr-approval-agent/test_reviewer.py+++ b/tools/pr-approval-agent/test_reviewer.py@@ -183,3 +183,24 @@ def test_inline_truncation_keeps_unresolved_drops_resolved(assert {c["body"] for c in shown} == kept_idsassert all(c["body"] != dropped_id for c in shown)assert line == omission+++ "ownership, summary, expected_head",+ [+ # Individual-only ownership must reach the prompt, not collapse to+ # "no ownership-source match", and the team-membership note (computed+ # against teams the author can't be "on") must stay out.+ (+ {"teams": [], "individuals": ["@handle"]},+ "individually owned by @handle",+ "Ownership: individually owned by @handle",+ ),+ ({"teams": [], "individuals": []}, "", "Ownership: no ownership-source match"),+ ],+)+def test_format_ownership_individual_only(ownership: dict, summary: str, expected_head: str) -> None:+ cl = {"ownership": ownership, "ownership_summary": summary, "author_on_owning_team": False}+ out = Reviewer(Path("."))._format_ownership(cl)+ assert out.splitlines()[0] == expected_head+ assert "NOT on the owning team" not in outdiff --git a/uv.lock b/uv.lockindex fc8aaa5e3b31..4ed58cbcf17d 100644--- a/uv.lock+++ b/uv.lock@@ -27,6 +27,7 @@ modal = falsemembers = ["hogli","posthog",+ "posthog-owners",][[package]]@@ -5743,6 +5744,7 @@ dev = [{ name = "orjson" },{ name = "packaging" },{ name = "parameterized" },+ { name = "posthog-owners" },{ name = "prance" },{ name = "protoletariat" },{ name = "pyarrow" },@@ -6018,6 +6020,7 @@ dev = [{ name = "orjson", specifier = "==3.11.9" },{ name = "packaging", specifier = "==24.1" },{ name = "parameterized", specifier = "==0.9.0" },+ { name = "posthog-owners", editable = "tools/owners" },{ name = "prance", specifier = "==23.6.21.0" },{ name = "protoletariat", specifier = "~=3.3.10" },{ name = "pyarrow", specifier = "==23.0.1" },@@ -6067,6 +6070,28 @@ sentiment = [{ name = "torch", specifier = "~=2.8.0" },]+[[package]]+name = "posthog-owners"+version = "0.1.0"+source = { editable = "tools/owners" }+dependencies = [+ { name = "click" },+ { name = "pyyaml" },+]++[package.optional-dependencies]+dev = [+ { name = "pytest" },+]++[package.metadata]+requires-dist = [+ { name = "click", specifier = ">=8.0" },+ { name = "pytest", marker = "extra == 'dev'", specifier = ">=7.0" },+ { name = "pyyaml", specifier = ">=6.0" },+]+provides-extras = ["dev"]+[[package]]name = "posthoganalytics"version = "7.20.4"