Skip to content

: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.

feat(devex): make owners-yaml a publishable package in packages/owners (#102210)

Julian Bez31ae481bdc2e
diff --git a/.agents/skills/establishing-code-ownership/SKILL.md b/.agents/skills/establishing-code-ownership/SKILL.md
index 73627e74ebf1..80de31c5b8c4 100644
--- a/.agents/skills/establishing-code-ownership/SKILL.md
+++ b/.agents/skills/establishing-code-ownership/SKILL.md
@@ -21,16 +21,16 @@ hogli owners:unowned # every tracked file with no owner
`owners:who` prints the resolved `owners`, the `status`, the Slack channel, and `source` — the `owners.yaml`/`product.yaml` file that decided the answer.
The channel comes from the root `teams:` registry entry for the primary owner, else a derived `#<slug>`; a path whose primary owner is an `@handle` has no channel.
`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).
+No hogli/flox available? The dependency-light fallback needs only pyyaml: `git ls-files posthog/hogql | PYTHONPATH=packages/owners-yaml python -m owners_yaml` (stdin paths → the same JSON).
## Resolution algorithm (what the resolver does)
For a path, it walks from the repo root down to the path collecting ownership files, then merges them **nearest-file-wins**:
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.
+2. **`products/<name>/product.yaml` — an accepted alias.** The root `owners.yaml` enables this with `alias_files: [product.yaml]`. 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.
- A tool that can only read CODEOWNERS gets a generated projection of the map instead, from `hogli owners:codeowners` (see [tools/owners/README.md](../../../tools/owners/README.md)); that projection covers test files and is never `.github/CODEOWNERS`.
+ A tool that can only read CODEOWNERS gets a generated projection of the map instead, from `hogli owners:codeowners` (see [packages/owners-yaml/README.md](../../../packages/owners-yaml/README.md)); that projection covers test files and is never `.github/CODEOWNERS`.
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.
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index 19dc81f0ffd5..145dd1fdde48 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -419,6 +419,15 @@ jobs:
- 'tools/hogli-commands/hogli_commands/hints.py'
- 'tools/hogli-commands/hogli_commands/product/**'
- 'tools/hogli-commands/hogli_commands/product_structure.yaml'
+ # owners_yaml is a runtime dependency of product code (stamphog reads
+ # owners.yaml through it), so a resolver change has to re-run its
+ # dependents; turbo-discover finds the products that import it.
+ # Deliberately not in `legacy`, because a leaf-package change should
+ # run its dependents rather than the whole Django suite.
+ - 'packages/owners-yaml/**'
+ # Transitional: branches that predate the move still carry the
+ # resolver at tools/owners.
+ - 'tools/owners/**'
# product:lint --all checks these generated files against the tree,
# so a baseline-only edit must run it too. The crossings baseline is
# also what product:lint reads to let a wiring location leave a
@@ -562,6 +571,9 @@ jobs:
- 'products/*/product.yaml'
- '**/owners.yaml'
# Resolver changes must re-run the owners.yaml lint too.
+ - 'packages/owners-yaml/**'
+ # Transitional: branches that predate the move still carry the
+ # resolver at tools/owners.
- 'tools/owners/**'
openapi_types:
# Generated OpenAPI types - validate they match schema
diff --git a/.dockerignore b/.dockerignore
index 3bff2f7a3ea0..6623185cc3d1 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -14,6 +14,7 @@
!common/tailwind
!packages/quill
!packages/llm-normalizer
+!packages/owners-yaml
!dags
!docs/onboarding
!ee
@@ -75,7 +76,6 @@ services/agent-*/.next
!tailwind.config.js
!tools/hogli
!tools/openapi-codegen
-!tools/owners
!tsconfig.json
common/*/*/node_modules
common/*/node_modules
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 688d0c7f3ffe..d69f2f58bd54 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -36,13 +36,13 @@ posthog/hogql/database/test/__snapshots__/test_database.ambr
# 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
+# pull_request_target event (via `python -m owners_yaml`), with packages/owners-yaml
# 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.
# DevEx maintains the resolver and reviews it with that risk in mind.
-tools/owners/** @PostHog/team-devex
+packages/owners-yaml/** @PostHog/team-devex
# And of course modifying this file can bring us problems so let's have the security team own it.
# This does not affect the distributed owners.yaml files, which drive non-required reviewer
diff --git a/.github/scripts/assign-reviewers.js b/.github/scripts/assign-reviewers.js
index 9962de088079..4e814338b340 100644
--- a/.github/scripts/assign-reviewers.js
+++ b/.github/scripts/assign-reviewers.js
@@ -54,13 +54,13 @@ function resolveOwners(filenames) {
// 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)
+ // are blocked by the CODEOWNERS entry on packages/owners-yaml. -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__')"
+ "import sys, runpy; sys.path.insert(0, 'packages/owners-yaml'); runpy.run_module('owners_yaml', run_name='__main__')"
const result = spawnSync(python, ['-I', '-c', launcher], {
input: filenames.join('\n'),
encoding: 'utf8',
diff --git a/.github/scripts/report_test_timings.py b/.github/scripts/report_test_timings.py
index 315cd2eaf69b..18fa1382ca4a 100644
--- a/.github/scripts/report_test_timings.py
+++ b/.github/scripts/report_test_timings.py
@@ -6,11 +6,11 @@
# "opentelemetry-api~=1.27",
# "opentelemetry-sdk~=1.27",
# "opentelemetry-exporter-otlp-proto-http~=1.27",
-# "posthog-owners",
+# "owners-yaml",
# ]
#
# [tool.uv.sources]
-# posthog-owners = { path = "../../tools/owners" }
+# owners-yaml = { path = "../../packages/owners-yaml" }
# ///
"""Emit OTLP traces from CI JUnit XML artifacts.
@@ -65,7 +65,7 @@ from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.trace.id_generator import IdGenerator
from opentelemetry.trace import Status, StatusCode
-from posthog_owners import OwnersResolver, first_team_owner
+from owners_yaml import OwnersResolver, first_team_owner
logger = logging.getLogger("report_test_timings")
@@ -804,7 +804,7 @@ def owner_team_lookup() -> Callable[[str], str]:
Resolution is capture-time on purpose: a test is attributed to whoever owned it when it
ran. Ownership is best-effort next to the timings themselves, so every failure — a resolver
- that can't load (a base checkout predating `tools/owners`) or one file that won't resolve —
+ that can't load (a base checkout predating `packages/owners-yaml`) or one file that won't resolve —
degrades to no stamp, leaving those spans in the reader's `unowned` bucket rather than
losing the emit.
"""
diff --git a/.github/scripts/trunk-codeowners.sh b/.github/scripts/trunk-codeowners.sh
index d16d0d0c3b77..1c479721be7d 100755
--- a/.github/scripts/trunk-codeowners.sh
+++ b/.github/scripts/trunk-codeowners.sh
@@ -42,10 +42,10 @@ generate() {
# uv first, because CI images carry uv more often than a python with pyyaml, and --no-project
# keeps it off this repo's own dependency sync. The entrypoint needs stdlib plus pyyaml only.
if command -v uv >/dev/null 2>&1; then
- uv run --no-project --with pyyaml python -m posthog_owners --codeowners "$target" && return 0
+ uv run --no-project --with pyyaml python -m owners_yaml --codeowners "$target" && return 0
fi
if command -v python3 >/dev/null 2>&1; then
- python3 -m posthog_owners --codeowners "$target" && return 0
+ python3 -m owners_yaml --codeowners "$target" && return 0
fi
return 1
}
@@ -62,7 +62,7 @@ fi
mkdir -p "$output_dir" || fall_back "Could not create $output_dir"
-if ! PYTHONPATH="$repo_root/tools/owners" generate >/dev/null 2>&1; then
+if ! PYTHONPATH="$repo_root/packages/owners-yaml" generate >/dev/null 2>&1; then
fall_back "Could not generate the Trunk ownership map"
fi
diff --git a/.github/scripts/trunk-codeowners.test.sh b/.github/scripts/trunk-codeowners.test.sh
index 3b8b81754199..4eb17d629a29 100755
--- a/.github/scripts/trunk-codeowners.test.sh
+++ b/.github/scripts/trunk-codeowners.test.sh
@@ -5,7 +5,7 @@ script="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/trunk-codeowners.sh"
workdir="$(mktemp -d)"
trap 'rm -rf "$workdir"' EXIT
-# The generator itself is covered by tools/owners/tests/test_owners.py. These cases stub the
+# The generator itself is covered by packages/owners-yaml/tests/test_owners.py. These cases stub the
# interpreter so the script's own contract is deterministic on a runner with no Python.
stub_interpreter() {
local name="$1" exit_code="$2" body="$3"
diff --git a/.github/scripts/trunk-impacted-targets.js b/.github/scripts/trunk-impacted-targets.js
index f486dc0606f4..901231b4d17e 100644
--- a/.github/scripts/trunk-impacted-targets.js
+++ b/.github/scripts/trunk-impacted-targets.js
@@ -648,6 +648,9 @@ const TRIPWIRE_RULES = [
// owners.yaml is the fallback every path resolves through when no nearer
// file claims it. A product's own owners.yaml is not here: it keeps its
// product lane.
+ ['packages/owners-yaml/**', OWNERSHIP],
+ // Transitional: branches that predate the move still carry the resolver at tools/owners,
+ // where the tools/ fallback rule would give it the Python lanes only.
['tools/owners/**', OWNERSHIP],
['owners.yaml', OWNERSHIP],
// The quarantine list covers the pytest, jest, and playwright suites at
diff --git a/.github/scripts/trunk-impacted-targets.test.js b/.github/scripts/trunk-impacted-targets.test.js
index 01c44910e82c..03d3602e03d2 100644
--- a/.github/scripts/trunk-impacted-targets.test.js
+++ b/.github/scripts/trunk-impacted-targets.test.js
@@ -466,7 +466,8 @@ test('stack and image configuration at the root stays universal', () => {
test('ownership data shares one lane instead of every lane', () => {
for (const file of [
'owners.yaml',
- 'tools/owners/posthog_owners/matcher.py',
+ 'packages/owners-yaml/owners_yaml/matcher.py',
+ 'tools/owners/owners_yaml/matcher.py',
'.github/CODEOWNERS',
'.github/owners.yaml',
]) {
@@ -1828,7 +1829,8 @@ test('cross-domain tools are tripwires rather than backend-only', () => {
computeTargets(['tools/openapi-codegen/config.ts'], CONTEXT),
computeTargets(['frontend/src/products.json'], CONTEXT)
)
- assert.deepEqual(computeTargets(['tools/owners/posthog_owners/__init__.py'], CONTEXT), ['ownership'])
+ assert.deepEqual(computeTargets(['packages/owners-yaml/owners_yaml/__init__.py'], CONTEXT), ['ownership'])
+ assert.deepEqual(computeTargets(['tools/owners/owners_yaml/__init__.py'], CONTEXT), ['ownership'])
})
// Prose overlaps only other prose, and has to reach that lane through the
diff --git a/.github/scripts/turbo-discover-cascade.test.js b/.github/scripts/turbo-discover-cascade.test.js
index cfc7d9fed6af..f0290734c8ec 100644
--- a/.github/scripts/turbo-discover-cascade.test.js
+++ b/.github/scripts/turbo-discover-cascade.test.js
@@ -1,14 +1,29 @@
// Run with: node --test .github/scripts/turbo-discover-cascade.test.js
//
// Unit tests for the dependent-cascade logic in turbo-discover.js:
-// productGraphFromTachMap, tachDependents, loadTachModuleGraph. Uses a
-// synthetic graph throughout — never asserts against the real tach map, which
-// would turn into a change-detector test that breaks on every unrelated import.
+// productGraphFromTachMap, tachDependents, loadTachModuleGraph, and the lib
+// package import scan (libImportName, productsImportingModule,
+// coreFilesImportingModule, getAffectedLibPackages). Uses a synthetic graph and
+// a temp-dir tree throughout — never asserts against the real tach map or the
+// real products/, which would turn into change-detector tests that break on
+// every unrelated import.
const test = require('node:test')
const assert = require('node:assert/strict')
-const { productGraphFromTachMap, tachDependents, loadTachModuleGraph } = require('./turbo-discover')
+const fs = require('node:fs')
+const os = require('node:os')
+const path = require('node:path')
+
+const {
+ productGraphFromTachMap,
+ tachDependents,
+ loadTachModuleGraph,
+ getAffectedLibPackages,
+ libImportName,
+ productsImportingModule,
+ coreFilesImportingModule,
+} = require('./turbo-discover')
// Graph literals use the shape productGraphFromTachMap emits: product directory
// name -> sorted product directory names it imports.
@@ -87,3 +102,104 @@ test('changed products are excluded from their own dependent set', () => {
test('fail closed: a run that cannot start yields null instead of throwing', () => {
assert.equal(loadTachModuleGraph('/nonexistent/repo-root'), null)
})
+
+// --- Lib packages as cascade sources ---
+//
+// A lib package is a uv distribution, so tach reports imports of it as
+// third-party and no consumer declares an edge to it. Its consumers are found by
+// scanning for import statements instead.
+
+function writeTree(files) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'turbo-discover-scan-'))
+ for (const [relative, contents] of Object.entries(files)) {
+ const full = path.join(root, relative)
+ fs.mkdirSync(path.dirname(full), { recursive: true })
+ fs.writeFileSync(full, contents)
+ }
+ return root
+}
+
+test('the import scan finds a product that imports the lib and ignores mentions that are not imports', () => {
+ const root = writeTree({
+ 'foo/backend/x.py': 'from owners_yaml.resolver import OwnersResolver\n',
+ 'bar/backend/y.py': '# owners_yaml is mentioned here\nMESSAGE = "import owners_yaml"\n',
+ 'baz/backend/z.py': 'from owners_yaml_extra import y\n',
+ 'multi_word/backend/w.py': 'import owners_yaml\n',
+ })
+ try {
+ assert.deepEqual(productsImportingModule('owners_yaml', root), ['foo', 'multi-word'])
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('the import scan reports the core files importing a lib, which is what forces Django to run', () => {
+ const root = writeTree({
+ 'posthog/models/thing.py': 'import os\n',
+ 'ee/billing/thing.py': 'from owners_yaml.resolver import OwnersResolver\n',
+ 'common/util/thing.py': 'x = "owners_yaml"\n',
+ })
+ try {
+ const dirs = ['posthog', 'ee', 'common'].map((d) => path.join(root, d))
+ assert.deepEqual(coreFilesImportingModule('owners_yaml', dirs), [path.join(root, 'ee/billing/thing.py')])
+ assert.deepEqual(coreFilesImportingModule('missing_module', dirs), [])
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('a lib change reaches both its importers and the products that depend on those importers', () => {
+ const root = writeTree({ 'stamphog/backend/logic.py': 'from owners_yaml.resolver import OwnersResolver\n' })
+ try {
+ const direct = productsImportingModule('owners_yaml', root)
+ assert.deepEqual(direct, ['stamphog'])
+ const products = graph({ stamphog: [], downstream: ['stamphog'] })
+ assert.deepEqual([...new Set([...direct, ...tachDependents(direct, products)])].sort(), [
+ 'downstream',
+ 'stamphog',
+ ])
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+// The import name and the package name are independent (@posthog/owners-yaml ships
+// owners_yaml), so the manifest declares it. A guess that nothing imports would
+// scan clean and read as "no consumer to test", which is why a missing or
+// malformed declaration throws instead.
+test('the lib import name is read from the package manifest, and a manifest that does not declare one throws', () => {
+ const root = writeTree({
+ 'owners/package.json': '{ "name": "@posthog/owners-yaml", "pythonImportName": "owners_yaml" }',
+ 'silent/package.json': '{ "name": "@posthog/silent" }',
+ 'bad/package.json': '{ "name": "@posthog/bad", "pythonImportName": "Not A Module" }',
+ })
+ try {
+ assert.equal(libImportName(path.join(root, 'owners')), 'owners_yaml')
+ assert.throws(() => libImportName(path.join(root, 'silent')), /pythonImportName/)
+ assert.throws(() => libImportName(path.join(root, 'bad')), /pythonImportName/)
+ assert.throws(() => libImportName(path.join(root, 'absent')), /could not read/)
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+test('affected lib packages carry the directory from the dry-run list, and products are not lib packages', () => {
+ const testTasks = [
+ { package: '@posthog/owners-yaml', directory: 'packages/owners-yaml' },
+ { package: '@posthog/products-stamphog', directory: 'products/stamphog' },
+ ]
+ const affected = [{ package: { name: '@posthog/owners-yaml' } }, { package: { name: '@posthog/products-stamphog' } }]
+
+ assert.deepEqual(getAffectedLibPackages(testTasks, affected), [
+ { name: '@posthog/owners-yaml', directory: 'packages/owners-yaml' },
+ ])
+})
+
+// The two turbo runs must agree on the package set: a source with no directory
+// cannot be scanned, so dropping it silently would skip its consumers.
+test('fail closed: an affected package missing from the dry-run list throws rather than being skipped', () => {
+ assert.throws(
+ () => getAffectedLibPackages([], [{ package: { name: '@posthog/owners-yaml' } }]),
+ /has no directory/
+ )
+})
diff --git a/.github/scripts/turbo-discover.js b/.github/scripts/turbo-discover.js
index a2579a6a6f04..afc206b7e3dc 100644
--- a/.github/scripts/turbo-discover.js
+++ b/.github/scripts/turbo-discover.js
@@ -9,6 +9,17 @@
// Products without contract-check are non-isolated: any change in them
// triggers the full test suite (all products + Django).
//
+// Lib packages are the other kind of workspace package with a backend:test task:
+// the Python distributions under packages/ (@posthog/owners-yaml and the like). They
+// never become matrix entries, because their own tests run in ci-python.yml.
+// They matter here as cascade sources. Each one is a uv distribution, so tach
+// resolves an import of it as third-party and records no edge to it, which means
+// nothing declares who its consumers are. A changed lib's direct consumers come
+// from scanning products/ for its import statements, and the tach map then
+// supplies the product-to-product closure over those consumers. The same scan
+// covers posthog/, ee/ and common/, where an importer has no product id to
+// select, so the only sound answer there is the full suite.
+//
// Products under SMALL_THRESHOLD duration get grouped into one matrix entry
// to avoid spinning up a full Docker stack for a handful of tests.
// Durations come from .test_durations (maintained by pytest-split).
@@ -177,8 +188,14 @@ function parseAffectedTasks(raw) {
return JSON.parse(raw).data.affectedTasks.items
}
+const PRODUCT_PACKAGE_PREFIX = '@posthog/products-'
+
+function isProductPackage(pkg) {
+ return pkg.startsWith(PRODUCT_PACKAGE_PREFIX)
+}
+
function packageToProduct(pkg) {
- return pkg.replace('@posthog/products-', '')
+ return pkg.replace(PRODUCT_PACKAGE_PREFIX, '')
}
// A product that ships the contract-check script but no turbo.json of its own
@@ -197,11 +214,37 @@ function getIsolatedProducts(contractTasks, repoRoot = process.cwd()) {
}
function getAffectedTaskProducts(tasks) {
- return [...new Set(tasks.map((t) => packageToProduct(t.package.name)))].sort()
+ return [
+ ...new Set(
+ tasks
+ .map((t) => t.package.name)
+ .filter(isProductPackage)
+ .map(packageToProduct)
+ ),
+ ].sort()
+}
+
+// The lib packages a diff touched, as { name, directory }. The affected query
+// reports package names only, so the directory comes from the dry-run task list,
+// which carries both. A package present in one list and not the other would mean
+// the two turbo runs disagree, so it throws rather than dropping a cascade source.
+function getAffectedLibPackages(testTasks, affectedTasks) {
+ const directories = new Map(
+ testTasks.filter((t) => !isProductPackage(t.package)).map((t) => [t.package, t.directory])
+ )
+ return [...new Set(affectedTasks.map((t) => t.package.name).filter((name) => !isProductPackage(name)))]
+ .sort()
+ .map((name) => {
+ const directory = directories.get(name)
+ if (!directory) {
+ throw new Error(`affected package '${name}' has no directory in the backend:test task list`)
+ }
+ return { name, directory }
+ })
}
function getAllProducts(testTasks) {
- return [...new Set(testTasks.map((t) => packageToProduct(t.package)))].sort()
+ return [...new Set(testTasks.map((t) => t.package).filter(isProductPackage).map(packageToProduct))].sort()
}
function affectedArgs(taskName) {
@@ -682,6 +725,107 @@ function productPrefix(product) {
return `products/${productToModule(product)}/`
}
+// --- Lib package consumers (import scan) ---
+// The tach map cannot answer who uses a lib package: the package is a uv
+// distribution, so tach resolves `import owners_yaml` as third-party and records
+// no edge to it. The import statements themselves are the only record, and unlike
+// a declared edge they cannot drift from what the code does.
+//
+// Roots that hold no product, so an importer there can only be answered with the
+// full suite.
+const CORE_SCAN_DIRS = ['posthog', 'ee', 'common']
+// Enough core importers to name in the log; the decision needs only the first.
+const CORE_IMPORTER_SAMPLE = 3
+const SKIPPED_SCAN_DIRS = new Set(['__pycache__', 'node_modules', '.venv'])
+
+// The Python module a lib package ships, declared in its package.json rather than
+// derived from the package name: the two names are independent (@posthog/owners-yaml
+// ships owners_yaml). A missing or malformed declaration throws rather than
+// returning a guess, because a module name nothing imports scans clean, which
+// reads as "no consumer to test" and skips exactly the products the cascade
+// exists to select. The character check also keeps the name safe to interpolate
+// into the import-scan regex.
+function libImportName(directory) {
+ const manifest = path.join(directory, 'package.json')
+ let declared
+ try {
+ declared = JSON.parse(fs.readFileSync(manifest, 'utf-8')).pythonImportName
+ } catch (e) {
+ throw new Error(`could not read ${manifest} (${e.message})`)
+ }
+ if (typeof declared !== 'string' || !/^[a-z_][a-z0-9_]*$/.test(declared)) {
+ throw new Error(
+ `${manifest} must declare "pythonImportName" as the Python module the package ships, so a change to it can select the products that import it`
+ )
+ }
+ return declared
+}
+
+function collectPythonFiles(dir) {
+ const files = []
+ let entries
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true })
+ } catch {
+ return files
+ }
+ for (const entry of entries) {
+ if (SKIPPED_SCAN_DIRS.has(entry.name)) {continue}
+ const full = path.join(dir, entry.name)
+ if (entry.isDirectory()) {
+ files.push(...collectPythonFiles(full))
+ } else if (entry.isFile() && entry.name.endsWith('.py')) {
+ files.push(full)
+ }
+ }
+ return files
+}
+
+// Matches `import <module>` and `from <module> ...`. The anchor at the start of a
+// line keeps mentions in comments, docstrings and other prose out, and the
+// required `.` or whitespace after the name stops owners_yaml from matching
+// owners_yaml_extra. An import under `if TYPE_CHECKING:` still matches, which
+// over-tests rather than missing a consumer.
+function importPatternFor(module) {
+ return new RegExp(`^[ \\t]*(from|import)[ \\t]+${module}([. \\t]|$)`, 'm')
+}
+
+// Products with at least one file importing the module, as product ids.
+function productsImportingModule(module, productsDir = PRODUCTS_DIR) {
+ const importPattern = importPatternFor(module)
+ let entries
+ try {
+ entries = fs.readdirSync(productsDir, { withFileTypes: true })
+ } catch {
+ return []
+ }
+ const consumers = []
+ for (const entry of entries) {
+ if (!entry.isDirectory() || SKIPPED_SCAN_DIRS.has(entry.name)) {continue}
+ const files = collectPythonFiles(path.join(productsDir, entry.name))
+ if (files.some((file) => importPattern.test(fs.readFileSync(file, 'utf-8')))) {
+ consumers.push(moduleToProduct(entry.name))
+ }
+ }
+ return consumers.sort()
+}
+
+// Core importers of a lib, as file paths. Core carries no product id, so the only
+// sound response to one is the full suite, and running this scan is what keeps the
+// "a lib change can skip Django" path honest without a separate lint.
+function coreFilesImportingModule(module, dirs = CORE_SCAN_DIRS) {
+ const importPattern = importPatternFor(module)
+ const found = []
+ for (const dir of dirs) {
+ for (const file of collectPythonFiles(dir)) {
+ if (!importPattern.test(fs.readFileSync(file, 'utf-8'))) {continue}
+ found.push(file)
+ if (found.length >= CORE_IMPORTER_SAMPLE) {return found}
+ }
+ }
+ return found
+}
+
// Check if .test_durations is stale for a product by comparing on-disk test
// file coverage vs recorded entries. Returns { stale, fileCount, coveredCount, coverage }.
function checkProductStaleness(product, durations) {
@@ -1241,6 +1385,10 @@ module.exports = {
productGraphFromTachMap,
loadTachModuleGraph,
tachDependents,
+ getAffectedLibPackages,
+ libImportName,
+ productsImportingModule,
+ coreFilesImportingModule,
}
// --- Main ---
@@ -1352,6 +1500,54 @@ if (legacyChanged) {
runLegacy = false
}
+ // The scan only ever yields product directory names, so a lib package can never
+ // reach the matrix, whose filters resolve @posthog/products-* packages.
+ const affectedLibs = getAffectedLibPackages(allTestTasks, affectedTestTasks)
+ if (affectedLibs.length > 0) {
+ const directConsumers = new Set()
+ for (const lib of affectedLibs) {
+ const libModule = libImportName(lib.directory)
+ const importers = productsImportingModule(libModule).filter((p) => allProductSet.has(p))
+ console.error(`Lib package changed: ${lib.name} (${libModule}) — imported by ${JSON.stringify(importers)}`)
+ for (const importer of importers) {
+ directConsumers.add(importer)
+ }
+ const coreImporters = coreFilesImportingModule(libModule)
+ if (coreImporters.length > 0) {
+ console.error(`${libModule} is imported by core (${coreImporters.join(', ')}) — Django will run`)
+ runLegacy = true
+ runLegacyReason = runLegacyReason || 'lib_cascade'
+ }
+ }
+ if (directConsumers.size === 0) {
+ console.error('No product imports the changed lib packages — nothing cascaded in')
+ } else {
+ const cascaded = tachDependentProducts([...directConsumers], allProductSet)
+ if (cascaded === null) {
+ // Fail toward over-testing, like the contract cascade above: without the
+ // graph we cannot know which products depend on the changed package.
+ console.error('Lib dependent cascade unavailable — testing all products rather than risk skipping a dependent')
+ products = allProducts
+ runLegacy = true
+ runLegacyReason = runLegacyReason || 'lib_cascade'
+ } else {
+ if (cascaded.length > 0) {
+ console.error(`Products depending on those importers via the tach map: ${JSON.stringify(cascaded)}`)
+ }
+ const reached = [...new Set([...directConsumers, ...cascaded])].sort()
+ products = [...new Set([...products, ...reached])].sort()
+ const nonIsolatedReached = reached.filter((p) => !isolatedProducts.has(p))
+ if (nonIsolatedReached.length > 0) {
+ console.error(
+ `Non-isolated products cascaded in from a lib change: ${JSON.stringify(nonIsolatedReached)} — Django will run, since core can import their internals`
+ )
+ runLegacy = true
+ runLegacyReason = runLegacyReason || 'lib_cascade'
+ }
+ }
+ }
+ }
+
if (schemaChanged) {
const schemaProducts = schemaAffectedProducts()
if (schemaProducts === null) {
diff --git a/.github/scripts/weekly-report-common.mjs b/.github/scripts/weekly-report-common.mjs
index b48ad0bb851a..cf3efd8a0ab0 100644
--- a/.github/scripts/weekly-report-common.mjs
+++ b/.github/scripts/weekly-report-common.mjs
@@ -118,10 +118,10 @@ export function resolveOwners(items, toRepoPaths = repoPathResolver()) {
let resolved = {}
if (allPaths.length > 0) {
try {
- const out = execFileSync('python3', ['-m', 'posthog_owners', '--purpose', 'notifications'], {
+ const out = execFileSync('python3', ['-m', 'owners_yaml', '--purpose', 'notifications'], {
encoding: 'utf8',
input: allPaths.join('\n'),
- env: { ...process.env, PYTHONPATH: 'tools/owners' },
+ env: { ...process.env, PYTHONPATH: 'packages/owners-yaml' },
})
resolved = JSON.parse(out)
} catch (err) {
diff --git a/.github/scripts/weekly-slow-tests-report.mjs b/.github/scripts/weekly-slow-tests-report.mjs
index eec85a1c54e5..fbea1b26d0e8 100644
--- a/.github/scripts/weekly-slow-tests-report.mjs
+++ b/.github/scripts/weekly-slow-tests-report.mjs
@@ -2,7 +2,7 @@
//
// Sibling of weekly-flaky-report.mjs: one HogQL read of the passing test spans the
// CI timing reporter (.github/scripts/report_test_timings.py) already ships, ranked by
-// median wall time, with owner attribution through tools/owners and recent editors
+// median wall time, with owner attribution through packages/owners-yaml and recent editors
// resolved through the GitHub commits API into Slack mentions. The report nudges the
// people best placed to speed a test up; it does not re-derive any span signal.
//
diff --git a/.github/workflows/auto-assign-reviewers.yml b/.github/workflows/auto-assign-reviewers.yml
index ec2ad4369e58..1b6205fcc828 100644
--- a/.github/workflows/auto-assign-reviewers.yml
+++ b/.github/workflows/auto-assign-reviewers.yml
@@ -49,7 +49,7 @@ jobs:
token: ${{ steps.app-token.outputs.token || github.token }}
# The assigner shells out to the owners resolver
- # (`python -m posthog_owners`) for ownership. That entrypoint
+ # (`python -m owners_yaml`) 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
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index 39c68c3fb217..9b34e299e7bf 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -283,6 +283,15 @@ jobs:
- 'tools/hogli-commands/hogli_commands/hints.py'
- 'tools/hogli-commands/hogli_commands/product/**'
- 'tools/hogli-commands/hogli_commands/product_structure.yaml'
+ # owners_yaml is a runtime dependency of product code (stamphog reads
+ # owners.yaml through it), so a resolver change has to re-run its
+ # dependents; turbo-discover finds the products that import it.
+ # Deliberately not in `legacy`, because a leaf-package change should
+ # run its dependents rather than the whole Django suite.
+ - 'packages/owners-yaml/**'
+ # Transitional: branches that predate the move still carry the
+ # resolver at tools/owners.
+ - 'tools/owners/**'
# product:lint --all checks these generated files against the tree,
# so a baseline-only edit must run it too. The crossings baseline is
# also what product:lint reads to let a wiring location leave a
@@ -429,6 +438,9 @@ jobs:
- 'products/*/product.yaml'
- '**/owners.yaml'
# Resolver changes must re-run the owners.yaml lint too.
+ - 'packages/owners-yaml/**'
+ # Transitional: branches that predate the move still carry the
+ # resolver at tools/owners.
- 'tools/owners/**'
openapi_types:
# Generated OpenAPI types - validate they match schema
@@ -4472,9 +4484,11 @@ jobs:
id: timing-reporter
shell: bash
run: |
- # tools/owners is a path dep of the reporter, so a base ref predating it can't resolve its deps.
+ # The owners resolver is a path dep of the reporter, so a base ref predating it
+ # can't resolve its deps. A base ref from before the move to packages/owners-yaml still
+ # carries it at tools/owners, so both locations count as available.
available=false
- if [[ -f .github/scripts/report_test_timings.py && -d tools/owners ]]; then
+ if [[ -f .github/scripts/report_test_timings.py && ( -d packages/owners-yaml || -d tools/owners ) ]]; then
available=true
fi
# A re-run may emit only through an attempt-aware reporter: an older script would
diff --git a/.github/workflows/ci-frontend.yml b/.github/workflows/ci-frontend.yml
index 44ac7e8cccb5..834fb5a5693e 100644
--- a/.github/workflows/ci-frontend.yml
+++ b/.github/workflows/ci-frontend.yml
@@ -1089,7 +1089,9 @@ jobs:
shell: bash
run: |
available=false
- if [[ -f .github/scripts/report_test_timings.py && -d tools/owners ]] && grep -q -- '"jest"' .github/scripts/report_test_timings.py; then
+ # The owners resolver is a path dep of the reporter. A base ref from before the
+ # move to packages/owners-yaml still carries it at tools/owners, so both count.
+ if [[ -f .github/scripts/report_test_timings.py && ( -d packages/owners-yaml || -d tools/owners ) ]] && grep -q -- '"jest"' .github/scripts/report_test_timings.py; then
available=true
fi
if [[ "$GITHUB_RUN_ATTEMPT" != "1" ]] && ! grep -q "def partition_run_attempt" .github/scripts/report_test_timings.py 2>/dev/null; then
diff --git a/.github/workflows/ci-nodejs.yml b/.github/workflows/ci-nodejs.yml
index 4b347d951b2e..1d922e31541b 100644
--- a/.github/workflows/ci-nodejs.yml
+++ b/.github/workflows/ci-nodejs.yml
@@ -981,7 +981,9 @@ jobs:
shell: bash
run: |
available=false
- if [[ -f .github/scripts/report_test_timings.py && -f bin/report-jest-timings && -d tools/owners ]] && grep -q -- '--timings' .github/scripts/report_test_timings.py; then
+ # The owners resolver is a path dep of the reporter. A head ref from before the
+ # move to packages/owners-yaml still carries it at tools/owners, so both count.
+ if [[ -f .github/scripts/report_test_timings.py && -f bin/report-jest-timings && ( -d packages/owners-yaml || -d tools/owners ) ]] && grep -q -- '--timings' .github/scripts/report_test_timings.py; then
available=true
fi
if [[ "$available" != "true" ]]; then
diff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.yml
index 89dec512b560..2c90d3b4f6fb 100644
--- a/.github/workflows/ci-python.yml
+++ b/.github/workflows/ci-python.yml
@@ -131,6 +131,9 @@ jobs:
# hogli CLI changes need validation
- 'tools/hogli/**'
- 'tools/hogli-commands/hogli_commands/**'
+ - 'packages/owners-yaml/**'
+ # Transitional: branches that predate the move still carry the resolver
+ # at tools/owners.
- 'tools/owners/**'
- 'hogli.yaml'
- 'bin/**'
@@ -159,6 +162,9 @@ jobs:
- 'uv.lock'
- .github/workflows/ci-python.yml
owners:
+ - 'packages/owners-yaml/**'
+ # Transitional: branches that predate the move still carry the resolver
+ # at tools/owners.
- 'tools/owners/**'
- 'pyproject.toml'
- 'uv.lock'
@@ -382,8 +388,29 @@ jobs:
- name: Run owners resolver tests
shell: bash
run: |
- [ "$RUN_OWNERS" = "true" ] || { echo "tools/owners unchanged — skipping"; exit 0; }
- pytest tools/owners/tests -v --junitxml=junit-owners.xml
+ [ "$RUN_OWNERS" = "true" ] || { echo "the owners package is unchanged — skipping"; exit 0; }
+ pytest packages/owners-yaml/tests -v --junitxml=junit-owners.xml
+
+ # A wheel in an empty venv cannot import anything else from the monorepo, so a
+ # new import of host code fails here instead of for users of the published package.
+ - name: Check the owners package runs outside the monorepo
+ shell: bash
+ run: |
+ [ "$RUN_OWNERS" = "true" ] || { echo "the owners package is unchanged — skipping"; exit 0; }
+ scratch=$(mktemp -d)
+ uv build packages/owners-yaml --wheel --out-dir "$scratch/dist"
+ uv venv "$scratch/venv"
+ uv pip install --python "$scratch/venv/bin/python" "$scratch"/dist/*.whl
+ repo="$scratch/repo"
+ mkdir -p "$repo/billing"
+ printf 'version: 1\nowners: team-platform\ngithub_org: example\n' > "$repo/owners.yaml"
+ printf 'version: 1\nowners: team-billing\n' > "$repo/billing/owners.yaml"
+ touch "$repo/billing/invoices.py"
+ "$scratch/venv/bin/owners" lint --repo-root "$repo"
+ # Capture first. `grep -q` on a pipe exits at the first match, the CLI then
+ # writes to a closed pipe and exits 1, and pipefail fails the step.
+ resolved=$("$scratch/venv/bin/owners" who --repo-root "$repo" billing/invoices.py)
+ grep -q 'team-billing' <<<"$resolved"
- name: Run query-performance-ai tests
shell: bash
diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml
index da7fbf594e42..9fc99fadf3ab 100644
--- a/.github/workflows/ci-scripts.yml
+++ b/.github/workflows/ci-scripts.yml
@@ -44,7 +44,7 @@ jobs:
# against drift — trunk-impacted-targets.test.js walks proto/, rust/,
# nodejs/ and every workspace package.json (the unanchored pattern
# pulls each manifest without its source tree), and
- # report_test_timings imports tools/owners and finds the root by
+ # report_test_timings imports the owners resolver and finds the root by
# owners.yaml. A new test that reads another path must add it here.
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
@@ -55,6 +55,7 @@ jobs:
/bin/report-jest-timings
/.depot/
/tools/
+ /packages/owners-yaml/
/proto/
/rust/
/nodejs/
@@ -83,10 +84,10 @@ jobs:
enable-cache: false
# The preinstalled python3 runs these standalone tests, so no
- # setup-python step. defusedxml + opentelemetry + tools/owners are
+ # setup-python step. defusedxml + opentelemetry + the owners resolver are
# report_test_timings.py's script deps.
- name: Install pytest
- run: python3 -m pip install --quiet pytest parameterized defusedxml==0.7.1 opentelemetry-sdk==1.33.1 opentelemetry-exporter-otlp-proto-http==1.33.1 ./tools/owners
+ run: python3 -m pip install --quiet pytest parameterized defusedxml==0.7.1 opentelemetry-sdk==1.33.1 opentelemetry-exporter-otlp-proto-http==1.33.1 ./packages/owners-yaml
# `-c /dev/null` skips the repo pytest.ini (its --reuse-db addopt needs
# pytest-django, which we don't install here). `--noconftest` skips the
diff --git a/.github/workflows/publish-owners-yaml.yml b/.github/workflows/publish-owners-yaml.yml
new file mode 100644
index 000000000000..284c2d86a213
--- /dev/null
+++ b/.github/workflows/publish-owners-yaml.yml
@@ -0,0 +1,106 @@
+name: Publish owners-yaml to PyPI
+
+on:
+ push:
+ tags:
+ - 'owners-yaml-v*'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: publish-owners-yaml-${{ github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ publish:
+ name: Build and publish
+ # Hard guard: only publish from a tag ref. workflow_dispatch is supported
+ # so a failed publish can be re-run against the existing tag (via
+ # `gh workflow run publish-owners-yaml.yml --ref owners-yaml-vX.Y.Z`); dispatching
+ # from a branch is a no-op.
+ if: startsWith(github.ref, 'refs/tags/owners-yaml-v')
+ runs-on: ubuntu-22.04
+ timeout-minutes: 10
+ environment: pypi-owners-yaml
+ permissions:
+ id-token: write
+ contents: write
+ attestations: write
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+
+ - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
+ with:
+ python-version: '3.13.13'
+
+ - uses: ./.github/actions/setup-uv
+ with:
+ enable-cache: false
+
+ - name: Verify tag matches package version
+ shell: bash
+ env:
+ TAG_REF: ${{ github.ref_name }}
+ run: |
+ tag_version="${TAG_REF#owners-yaml-v}"
+ pkg_version=$(python -c "import tomllib; print(tomllib.load(open('packages/owners-yaml/pyproject.toml','rb'))['project']['version'])")
+ if [[ "$tag_version" != "$pkg_version" ]]; then
+ echo "::error::tag version ($tag_version) does not match packages/owners-yaml/pyproject.toml version ($pkg_version)"
+ exit 1
+ fi
+
+ # hogli's script is stdlib-only and reads any Keep a Changelog file.
+ - name: Extract release notes from the changelog
+ shell: bash
+ env:
+ TAG_REF: ${{ github.ref_name }}
+ run: |
+ tag_version="${TAG_REF#owners-yaml-v}"
+ python tools/hogli/scripts/release_notes.py "$tag_version" --changelog packages/owners-yaml/CHANGELOG.md > /tmp/owners-release-notes.md
+
+ - name: Build sdist and wheel
+ run: uv build packages/owners-yaml --out-dir dist
+
+ - name: Validate metadata
+ run: uvx twine check dist/*.whl dist/*.tar.gz
+
+ - name: Smoke-test built wheel
+ shell: bash
+ env:
+ TAG_REF: ${{ github.ref_name }}
+ run: |
+ tag_version="${TAG_REF#owners-yaml-v}"
+ uv venv /tmp/owners-smoke
+ # By path, never by name: the step must test the wheel this run built, not
+ # whatever the public index happens to serve under that name and version.
+ uv pip install --python /tmp/owners-smoke/bin/python dist/*.whl
+ installed=$(/tmp/owners-smoke/bin/owners --version | tr -d '[:space:]')
+ if [[ "$installed" != *"$tag_version" ]]; then
+ echo "::error::installed version ($installed) does not match the tag ($tag_version)"
+ exit 1
+ fi
+ /tmp/owners-smoke/bin/owners-yaml --version
+ /tmp/owners-smoke/bin/owners lint --repo-root .
+
+ - name: Generate build provenance attestation
+ uses: actions/attest-build-provenance@e8998f949152b193b063cb0ec769d69d929409be # v2.4.0
+ with:
+ subject-path: |
+ dist/*.whl
+ dist/*.tar.gz
+
+ - name: Publish to PyPI
+ # --check-url skips a file the index already holds, so a re-dispatch after a failed
+ # release step gets past the publish instead of dying on the immutable duplicate.
+ run: uv publish --check-url https://pypi.org/simple/ dist/*.whl dist/*.tar.gz
+
+ - name: Create GitHub Release
+ uses: softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3.0.0
+ with:
+ files: |
+ dist/*.whl
+ dist/*.tar.gz
+ body_path: /tmp/owners-release-notes.md
+ prerelease: ${{ contains(github.ref, 'alpha') || contains(github.ref, 'beta') || contains(github.ref, 'rc') }}
diff --git a/.github/workflows/weekly-flaky-report.yml b/.github/workflows/weekly-flaky-report.yml
index 6cf6e4d43ba4..803bb7459703 100644
--- a/.github/workflows/weekly-flaky-report.yml
+++ b/.github/workflows/weekly-flaky-report.yml
@@ -5,7 +5,7 @@ name: Weekly flaky test report
# engineering_analytics product's flaky_tests endpoint and relays a channel
# table plus per-team thread slices to Slack via the DevEx bot — it does not
# re-derive the flake signal. Owner
-# attribution runs in the script through the tools/owners resolver, which is why
+# attribution runs in the script through the packages/owners-yaml resolver, which is why
# the sparse checkout includes the ownership files.
#
# Requires (no-ops with a warning until set, so it never spams failures):
@@ -50,7 +50,7 @@ jobs:
.github/scripts/weekly-flaky-report.mjs
.github/scripts/weekly-report-common.mjs
.nvmrc
- tools/owners
+ packages/owners-yaml
owners.yaml
**/owners.yaml
**/product.yaml
diff --git a/.github/workflows/weekly-slow-tests-report.yml b/.github/workflows/weekly-slow-tests-report.yml
index 33330a8115e8..cdca49aa673b 100644
--- a/.github/workflows/weekly-slow-tests-report.yml
+++ b/.github/workflows/weekly-slow-tests-report.yml
@@ -3,7 +3,7 @@ name: Weekly slow test report
# Posts the week's slowest passing tests to #flakey-tests every Monday, tagging the
# people who last edited each test. PULL model, sibling of weekly-flaky-report.yml:
# the script reads the passing test spans CI already ships to PostHog (see
-# .github/scripts/report_test_timings.py), resolves owners through tools/owners and
+# .github/scripts/report_test_timings.py), resolves owners through packages/owners-yaml and
# recent editors through the GitHub commits API, and relays one table to Slack via
# the DevEx bot.
#
@@ -48,7 +48,7 @@ jobs:
.github/scripts/weekly-slow-tests-report.mjs
.github/scripts/weekly-report-common.mjs
.nvmrc
- tools/owners
+ packages/owners-yaml
owners.yaml
**/owners.yaml
**/product.yaml
diff --git a/.semgrep/rules/devex/no-init-reexports.yaml b/.semgrep/rules/devex/no-init-reexports.yaml
index 88155d3d3e6f..5b7b13fca1a4 100644
--- a/.semgrep/rules/devex/no-init-reexports.yaml
+++ b/.semgrep/rules/devex/no-init-reexports.yaml
@@ -103,7 +103,7 @@ rules:
- 'tools/hogli-commands/hogli_commands/devenv/__init__.py'
- 'tools/hogli-commands/hogli_commands/product/__init__.py'
- 'tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py'
- - 'tools/owners/posthog_owners/__init__.py'
+ - 'packages/owners-yaml/owners_yaml/__init__.py'
# Column-0 anchor: only flag eager, top-level re-exports. Indented ones (TYPE_CHECKING,
# try/except ImportError, function-local) are already lazy and intentionally skipped.
pattern-regex: '(?m)^from\s+\.'
diff --git a/.stamphog/README.md b/.stamphog/README.md
index 315c76d82acc..f2b9d86ecacd 100644
--- a/.stamphog/README.md
+++ b/.stamphog/README.md
@@ -12,7 +12,7 @@ It overrides `deny` and `allow`, and the differences are:
- `auth` and `billing` exempt `products/warehouse_sources/backend/temporal/data_imports/sources/`, because connector code does OAuth and talks to the Stripe API without touching PostHog's auth system or its billing.
- `infra_cicd` also matches `.github/pr-deploy`.
-- `stamphog_policy` also matches `products/stamphog/backend/logic/policy_defaults/`, `tools/owners/`, `owners.yaml` and `product.yaml`, because those are gate inputs here.
+- `stamphog_policy` also matches `products/stamphog/backend/logic/policy_defaults/`, `packages/owners-yaml/`, `owners.yaml` and `product.yaml`, because those are gate inputs here.
- `allow` also lists `.github/CODEOWNERS`.
- Every `rationale` records the false positives that shaped the rule in this repository.
diff --git a/.stamphog/policy.yml b/.stamphog/policy.yml
index 33a9d13b2430..209d577c5e44 100644
--- a/.stamphog/policy.yml
+++ b/.stamphog/policy.yml
@@ -128,6 +128,8 @@ deny:
# runs the previous engine needs this exact literal.
- 'tools/pr-approval-agent/'
- 'products/stamphog/backend/logic/policy_defaults/'
+ - 'packages/owners-yaml/'
+ # Transitional: branches that predate the move still carry the resolver here.
- 'tools/owners/'
- 'CODEOWNERS'
- 'owners\.yaml'
diff --git a/Dockerfile b/Dockerfile
index bc52f37c6e7e..4d93948b3ba8 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -200,10 +200,10 @@ RUN --mount=type=cache,id=uv-libxmlsec1.2.37-2,target=/root/.cache/uv \
--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. tools/owners is also a real install source here: posthog-owners
+ # present in the build context. packages/owners-yaml is also a real install source here: owners-yaml
# is a runtime dependency (stamphog's digest reads owners.yaml through it), and --no-editable
# copies it into the venv so the image never depends on this bind mount's path surviving.
- --mount=type=bind,source=tools/owners,target=tools/owners \
+ --mount=type=bind,source=packages/owners-yaml,target=packages/owners-yaml \
uv sync --locked --no-dev --no-editable --no-install-project --no-binary-package lxml --no-binary-package xmlsec
ENV PATH=/python-runtime/bin:$PATH \
@@ -404,11 +404,11 @@ COPY --chown=posthog:posthog common/migration_utils common/migration_utils/
COPY --chown=posthog:posthog products products/
# Stamphog ships the review engine + owners resolver from this checkout into its sandbox at
# runtime (products/stamphog/backend/temporal/activities.py), so both must exist in the image as
-# source. The engine arrives with products/ above, and only tools/owners needs its own COPY. This
-# differs from the installation of posthog-owners into the venv as a library: the sandbox receives
+# source. The engine arrives with products/ above, and only packages/owners-yaml needs its own COPY. This
+# differs from the installation of owners-yaml into the venv as a library: the sandbox receives
# files copied into a checkout, and not an import.
-COPY --chown=posthog:posthog tools/owners tools/owners/
-RUN test -f products/stamphog/packages/pr-approval-agent/review_local.py && test -d tools/owners/posthog_owners
+COPY --chown=posthog:posthog packages/owners-yaml packages/owners-yaml/
+RUN test -f products/stamphog/packages/pr-approval-agent/review_local.py && test -d packages/owners-yaml/owners_yaml
# Generated MCP tool catalog, read at runtime from BASE_DIR by the OAuth consent page
# (posthog/api/oauth/mcp_resource_scopes.py) and the tasks permission broker. The rest of
# services/ is a Node build (Dockerfile.node) and deliberately stays out of this image.
diff --git a/Dockerfile.llm-analytics b/Dockerfile.llm-analytics
index 5f0d5d5a529c..cb95d5253feb 100644
--- a/Dockerfile.llm-analytics
+++ b/Dockerfile.llm-analytics
@@ -44,11 +44,11 @@ RUN --mount=type=cache,id=uv-libxmlsec1.2.37-2,target=/root/.cache/uv \
--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. tools/owners is also a real install
- # source here: posthog-owners is a runtime dependency (stamphog's digest reads owners.yaml
+ # workspace member must be present in the build context. packages/owners-yaml is also a real install
+ # source here: owners-yaml is a runtime dependency (stamphog's digest reads owners.yaml
# through it, and posthog/urls.py imports that chain unconditionally), and --no-editable copies
# it into the venv so the image never depends on this bind mount's path surviving.
- --mount=type=bind,source=tools/owners,target=tools/owners \
+ --mount=type=bind,source=packages/owners-yaml,target=packages/owners-yaml \
uv sync --locked --no-dev --no-editable --no-install-project --group sentiment --no-binary-package lxml --no-binary-package xmlsec
ENV PATH=/python-runtime/bin:$PATH \
@@ -56,12 +56,12 @@ ENV PATH=/python-runtime/bin:$PATH \
POSTHOG_SENTIMENT_MODEL_CACHE=/opt/posthog-sentiment-model \
TIKTOKEN_CACHE_DIR=/code/.tiktoken_cache
-# posthog-owners is installed from a bind mount that does not survive into the image, so a missing
-# --no-editable above leaves an editable install pointing at /code/tools/owners and every Django
-# entrypoint dies on `import posthog_owners` at runtime instead of here. The root Dockerfile asserts
-# the same invariant with `test -d tools/owners/posthog_owners`; this image never copies that source
+# owners-yaml is installed from a bind mount that does not survive into the image, so a missing
+# --no-editable above leaves an editable install pointing at /code/packages/owners-yaml and every Django
+# entrypoint dies on `import owners_yaml` at runtime instead of here. The root Dockerfile asserts
+# the same invariant with `test -d packages/owners-yaml/owners_yaml`; this image never copies that source
# tree, so assert importability instead of presence.
-RUN python -c "import posthog_owners"
+RUN python -c "import owners_yaml"
# Pre-warm the tiktoken BPE encoding cache into the image so runtime token counting reads the
# blobs from disk instead of fetching them from OpenAI's blob host on first use, which fails under
diff --git a/docs/internal/monorepo-layout.md b/docs/internal/monorepo-layout.md
index fc660b517203..944b8a53bf86 100644
--- a/docs/internal/monorepo-layout.md
+++ b/docs/internal/monorepo-layout.md
@@ -29,29 +29,32 @@ services/ # Independent services NOT owned by any one product
stripe-app/ # Stripe integration app
packages/ # Libraries shared across more than one product/service (e.g. quill)
+ owners/ # owners.yaml resolver (owners_yaml) — Python uv workspace member, RUNTIME dependency
common/ # Shared code — holding pen, NOT a destination (goal: shrink it)
hogql_parser/ # HogQL parser
-tools/ # Developer/CI tooling, with one exception noted below
+tools/ # Developer/CI tooling
hogli/ # Developer CLI framework (PyPI-publishable; uv workspace member)
hogli-commands/ # PostHog-specific hogli commands (consumed via hogli.yaml)
- owners/ # owners.yaml resolver (posthog_owners) — also a RUNTIME dependency
devenv/ # Developer environment config (intent map, process model)
```
-`tools/` is developer and CI tooling by default, and one directory in it is not. `tools/owners` is
-installed into the production venv, because stamphog's digest resolves a team's Slack channel through
-`posthog_owners` rather than reparsing `owners.yaml` itself. It is also copied into the production
-image as source, alongside stamphog's review engine at
+`tools/` is developer and CI tooling: code no runtime process imports.
+`packages/owners-yaml` is the counterexample that used to sit there.
+It is installed into the production venv, because stamphog's digest resolves a team's Slack channel
+through `owners_yaml` rather than reparsing `owners.yaml` itself.
+It is also copied into the production image as source, alongside stamphog's review engine at
`products/stamphog/packages/pr-approval-agent/`, because stamphog ships both into its review sandbox
at runtime.
-Inside that sandbox the engine is written to `<checkout>/tools/pr-approval-agent` with `tools/owners`
-beside it, and that placement is a contract rather than a leftover: the engine finds its repo root by
-walking up from its own file, so the path decides which policy it reads, and downstream repos vendor
-the two directories in exactly that arrangement.
+Inside that sandbox the engine is written to `<checkout>/tools/pr-approval-agent` with the resolver
+beside it at `<checkout>/tools/owners`, and that placement is a contract rather than a leftover: the
+engine finds its repo root by walking up from its own file, so the path decides which policy it
+reads, and downstream repos vendor the two directories in exactly that arrangement.
+The engine resolves the resolver by fixed offsets from its own file, `packages/owners-yaml` first and the
+sibling `owners/` second, so the monorepo and the vendored layout both work.
### Products
@@ -81,7 +84,9 @@ Nest because tooling boundaries become path-scoped (`products/<product>/**` for
### Packages
-This covers **pnpm workspace packages** (JS/TS). Python and Rust differ — there, location and import name matter directly (a top-level Python package can even shadow a stdlib module, which is why there's no top-level `platform/`), so these rules don't apply.
+Anything under `packages/` is a workspace member of its ecosystem: `package.json` for pnpm, `pyproject.toml` for uv.
+The placement rules below are about **pnpm workspace packages** (JS/TS).
+Rust differs, and Python has its own section after them, because there location and import name matter directly (a top-level Python package can even shadow a stdlib module, which is why there's no top-level `platform/`).
For pnpm packages, location doesn't gate who can import them (pnpm resolves by name), so location is an ownership signal, not access control. Place by current ownership:
@@ -91,6 +96,25 @@ For pnpm packages, location doesn't gate who can import them (pnpm resolves by n
`pnpm-workspace.yaml` globs are explicit (`products/*`, `packages/quill`, …) and don't yet match nested `products/<product>/packages/*` or a new top-level `packages/<name>/` — so register the package's path there when you add it, or `workspace:*` deps, filters, and scripts won't resolve.
+#### Python packages
+
+A Python package under `packages/<name>/` is a uv workspace member with its own `pyproject.toml`, registered in the root `pyproject.toml` under `[tool.uv.workspace].members` and `[tool.uv.sources]`.
+Its import name is independent of its location (`packages/owners-yaml` ships `owners_yaml`), so a move is a path rename with no import churn, the same property pnpm packages have.
+
+Reach for one only when a consumer must install it outside the monorepo venv: a bare-python CI step, the review sandbox, another repo, PyPI.
+Reuse inside the app is not a reason on its own.
+What puts it in `packages/` rather than `tools/` is that runtime code imports it.
+A distribution only CI and developer workflows use belongs in `tools/`, like `hogli`.
+
+Rules that follow from being a distribution rather than a module:
+
+- It is a leaf: no imports of `posthog/`, `ee/`, `products/`, `common/`, Django, or DRF. tach resolves a uv distribution as third-party and cannot police this, so each package gets a `forbidden` contract in the root `pyproject.toml` under `[tool.importlinter]` (see `packages/owners-yaml is a leaf`), which resolves by installed import name.
+- It carries a `package.json` (`@posthog/<name>`, private) and a `turbo.json` whose `backend:test` inputs cover its sources, so turbo can tell when it changed. The manifest also declares `pythonImportName`. `turbo-discover` reads that name, scans `products/` for imports of it, and re-tests the importers plus their tach dependents. Consumers declare nothing.
+- Its own tests are a step in `ci-python.yml`, not a matrix entry: `turbo-discover` treats it as a cascade source only.
+- Core (`posthog/`, `ee/`, `common/`) should not import it, so that a package change re-tests its product consumers rather than the Django suite. `turbo-discover` scans those trees too, and runs the full suite when one of them imports it.
+- Register its path in `pnpm-workspace.yaml`, in `.dockerignore` (an allowlist), and in the Dockerfile bind-mount list, because `uv sync` validates workspace membership at build time.
+- Same nest-then-promote rule as pnpm packages: promote on a second real consumer, not on intent.
+
### Services
- are their own deployment
diff --git a/docs/internal/ownership-model-proposal.md b/docs/internal/ownership-model-proposal.md
index 0d0070703d29..298d9bc05931 100644
--- a/docs/internal/ownership-model-proposal.md
+++ b/docs/internal/ownership-model-proposal.md
@@ -2,6 +2,11 @@
Status: implemented (landed with the PR that introduced this document)
+The format itself is now specified in [`packages/owners-yaml/SPEC.md`](../../packages/owners-yaml/SPEC.md), and the package README covers usage.
+This document keeps the design reasoning and how the PostHog monorepo wires the resolver in.
+PostHog's repo settings (`github_org`, `producers`, `reserved_dirs`, `codeowners`) live in the root `owners.yaml`.
+CI regenerates the CODEOWNERS projection before each Trunk test upload in `.github/scripts/trunk-codeowners.sh`, so Trunk Flaky Tests can attribute a test to a team.
+
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):
@@ -109,7 +114,7 @@ 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:
+`products/<name>/product.yaml` with an `owners:` key is read by the resolver as an `owners.yaml` with that same `owners:` list, because the root `owners.yaml` enables it with `alias_files: [product.yaml]`, which is also the default when a root file does not declare the setting. 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`).
@@ -143,7 +148,7 @@ Every value is a string starting with `#`, or `false` to mean "no channel, don't
`notifications` may also be a mapping of producer name to channel, so a team can silence or redirect one bot on its own.
A producer the mapping does not name falls through to `slack`.
-Only a producer the schema knows may be named, so a typo is a lint error rather than an opt-out that never applies.
+Only a producer listed in the root `producers:` setting may be named, so a typo is a lint error rather than an opt-out that never applies.
```yaml
# owners.yaml (repo root only)
@@ -209,22 +214,22 @@ The hard `.github/CODEOWNERS` stays outside this walk entirely. It keeps its own
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.
+- **Resolver**: single implementation in the installable `owners-yaml` package at `packages/owners-yaml/` 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).
+- **Validator**: `hogli owners:lint` — schema check, team slugs and `@handles` against the live GitHub org (`owners_yaml.github`, which `product/gh.py` reuses), 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`.
+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 (`packages/owners-yaml/owners_yaml/`) 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 is why it ships as the standalone, installable `packages/owners-yaml` package (`owners-yaml`), which any repo can run without vendoring: `uvx owners-yaml lint` (pin the version in CI).
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.
@@ -251,7 +256,7 @@ The division of labor: `owners:lint`'s fold/split suggestions are the everyday i
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`.
+1. **Resolver + schema.** `packages/owners-yaml/` (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.**
diff --git a/hogli.yaml b/hogli.yaml
index 60029e9617a4..36dc2c06556e 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -1074,25 +1074,25 @@ desktop:
owners:
owners:resolve:
- click: posthog_owners.cli:cmd_resolve
+ click: owners_yaml.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
+ click: owners_yaml.cli:cmd_who
description: Show who owns a single path (owners, status, slack, source)
owners:census:
- click: posthog_owners.cli:cmd_census
+ click: owners_yaml.cli:cmd_census
description: Count test files per owning team (optional PREFIX; --json for machine output)
owners:codeowners:
- click: posthog_owners.cli:cmd_codeowners
+ click: owners_yaml.cli:cmd_codeowners
description: Emit a CODEOWNERS projection of test-file ownership for tools that only read CODEOWNERS (-o writes a file)
owners:unowned:
- click: posthog_owners.cli:cmd_unowned
+ click: owners_yaml.cli:cmd_unowned
description: List unowned tracked files, respecting owners:null exemptions (optional PREFIX)
owners:lint:
- click: posthog_owners.cli:cmd_lint
+ click: owners_yaml.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
+ click: owners_yaml.cli:cmd_fmt
description: Dry-run oracle showing how the owners.yaml layout differs from canonical placement (never writes)
devex:
devex:feedback:
diff --git a/owners.yaml b/owners.yaml
index 6282dcbe69af..237ca80f04e2 100644
--- a/owners.yaml
+++ b/owners.yaml
@@ -1,5 +1,18 @@
version: 1
owners: []
+# Team slugs below are GitHub teams in this organization.
+github_org: PostHog
+# Automation that a team can redirect or silence under `notifications:`.
+producers: [stamphog, visual_review]
+# services/mcp generate-tools reads every YAML file in a product's mcp/ directory.
+reserved_dirs: ['products/**/mcp/**']
+# A product manifest already lists its owners, so it counts as an ownership file.
+alias_files: [product.yaml]
+# frontend/ runs the Jest suites of the product frontends, so their JUnit paths start from there.
+codeowners:
+ jest_root: frontend
+ jest_root_tests: 'products/**/frontend/**'
+ jest_root_packages: products
# Slack channel per team, declared once for the whole repo (root-only registry).
# A team only needs an entry where the derived '#<slug>' is wrong or missing; the
# other 22 slugs in use derive correctly and are deliberately absent.
@@ -121,9 +134,9 @@ rules:
- match: '/services/llm-gateway/'
owners: team-agent-infrastructure
- match:
+ - '/packages/owners-yaml/'
- '/tools/hogli-commands/'
- '/tools/hogli/'
- - '/tools/owners/'
- '/tools/phrocs/'
owners: team-devex
- match: '/products/stamphog/packages/pr-approval-agent/'
diff --git a/packages/owners-yaml/CHANGELOG.md b/packages/owners-yaml/CHANGELOG.md
new file mode 100644
index 000000000000..cca063921159
--- /dev/null
+++ b/packages/owners-yaml/CHANGELOG.md
@@ -0,0 +1,46 @@
+# Changelog
+
+Notable changes to the `owners-yaml` package. The format follows
+[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
+[semantic versioning](https://semver.org/spec/v2.0.0.html).
+
+`publish-owners-yaml.yml` reads the section matching the tagged version and uses it as
+the GitHub Release body, so add the entry here before you cut the tag.
+
+## 0.2.0
+
+First release on PyPI, as `owners-yaml`. The package was developed in the monorepo as `posthog-owners` and never published under that name.
+
+### Added
+
+- `SPEC.md` defines the `owners.yaml` format, version 1, with the resolution steps, a field merge table, a flow diagram, and a worked example. `owners.schema.json` describes the file for editors.
+- `SPEC.md` section 7 defines the resolver interface, and `resolution.schema.json` describes its JSON response.
+- `conformance/` holds language-neutral test cases for the resolution rules, which any implementation can run.
+- `publish-owners-yaml.yml` publishes the package to PyPI when an `owners-yaml-v*` tag is pushed.
+- Root-only repo settings in `owners.yaml`: `github_org`, `producers`, `reserved_dirs`, `alias_files`, and `codeowners`.
+- `alias_files` declares the file names, besides `owners.yaml`, that count as ownership files. It defaults to `[product.yaml]`, so a root file that predates the setting keeps resolving as before; a declared list replaces the default, and `alias_files: []` turns alias files off.
+- `--repo-root` on every CLI command, and `--org` on `lint` and `codeowners`.
+- A tree that is not a git worktree is read from disk, so the CLI works on an export or a scratch copy.
+- `owners_yaml.github.GitHubOrg` validates team slugs and handles without any host tooling.
+- An `owners-yaml` console script, so `uvx owners-yaml` works without `--from`.
+- `BatchOwnershipSource`, a source that fetches a batch's ownership files together. `OwnersResolver.map()` calls its `read_all` before it reads any file: first for the root `owners.yaml`, then for the batch.
+- The top-level `owners_yaml` package exports the full public API, so consumers do not import submodules.
+- `py.typed`, so type checkers read the package's annotations.
+
+### Fixed
+
+- Rule patterns support `[abc]`, `[a-z]` and `[!abc]` character classes, as SPEC section 3.5 now states. `match_is_glob` already counted `[` as a wildcard, so such a pattern passed lint, counted as a crosscutting glob, then matched nothing and let its paths fall through to an ancestor's owner.
+
+### Changed
+
+- The GitHub organization is no longer hardcoded. `codeowners` and `lint --live` read it from `github_org` or `--org`, and fail with a clear message when neither is set.
+- Producer names are no longer hardcoded. A repo that declares `producers` gets typo checks; a repo that does not accepts any name.
+- The reserved `products/**/mcp/**` location moved from the code into PostHog's own `reserved_dirs`. `.github/workflows/**` stays built in.
+- The CODEOWNERS projection reads its Jest spelling rules from the `codeowners` settings instead of PostHog's layout.
+- Outside a git worktree and without `--repo-root`, the CLI prints an error instead of a traceback.
+- `version: true` and `version: 1.0` no longer count as `version: 1`, so such a file counts as absent.
+- `product.yaml` is no longer a PostHog convention baked into the code. It is the default value of `alias_files`, which a root file can replace or empty.
+
+## 0.1.0
+
+First version, used inside the PostHog monorepo only.
diff --git a/packages/owners-yaml/LICENSE b/packages/owners-yaml/LICENSE
new file mode 100644
index 000000000000..4267194a9f62
--- /dev/null
+++ b/packages/owners-yaml/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 PostHog Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/owners-yaml/README.md b/packages/owners-yaml/README.md
new file mode 100644
index 000000000000..45721015caa8
--- /dev/null
+++ b/packages/owners-yaml/README.md
@@ -0,0 +1,286 @@
+# owners-yaml
+
+Code ownership in small `owners.yaml` files next to the code, with a resolver that people, tools, and agents can ask, a linter, and a CODEOWNERS export.
+
+`CODEOWNERS` answers one question for one consumer: who must approve this pull request on GitHub.
+Automation now does more of the work around a repo: review bots, coding agents that open pull requests, alert routers, flaky-test reports.
+Each of them needs ownership as data, and each asks a different question:
+
+- Which team owns this path, and who is the person to ask?
+- Which Slack channel takes this team's alerts, and has the team opted out of this bot?
+- Is this file generated or vendored, so a review can skip it?
+- Does anyone own this code at all?
+
+`owners-yaml` answers all of them from one resolver, so no tool parses ownership files itself or guesses an owner from `git blame`.
+
+Each directory declares its owners in a short file.
+Resolving a path takes more steps than a CODEOWNERS lookup: the nearest file wins field by field, `inherit: false` cuts off parent files, and rules override fields inside a file.
+So don't read the files to find an owner. Ask the resolver: `owners who <path>` for a person, and the library, CLI, or JSON entrypoint for a tool.
+GitHub's `CODEOWNERS` can stay in place for required approvals.
+
+The format is defined in [SPEC.md](https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/SPEC.md).
+PostHog's monorepo uses it for about 30 teams.
+The same files route review requests, give every agent-opened pull request one accountable owner, and send daily digests, flaky-test reports, and alerts to the right team channel.
+
+## Quick start
+
+```yaml
+# billing/owners.yaml
+version: 1
+owners: [team-billing, '@alice']
+```
+
+```console
+$ uvx owners-yaml who billing/api/invoices.py
+path: billing/api/invoices.py
+owners: team-billing, @alice
+status: active
+slack: #team-billing
+source: billing/owners.yaml
+```
+
+## Why use it
+
+A single `CODEOWNERS` file works well for small repos. In a large monorepo it has these problems:
+
+- **Line order changes the result.** The last matching line wins, so a broad pattern added at the bottom can take over the specific lines above it.
+- **One busy file.** Every team edits the same file, so it gets merge conflicts and nobody feels responsible for it.
+- **No lint.** Nothing reports a pattern that matches no files, a team that no longer exists, or a directory that nobody owns.
+- **Nothing but owners.** You can't say that code is generated or vendored, or which Slack channel a team uses.
+
+`owners.yaml` addresses these:
+
+- **The nearest file wins, field by field.** A child file that only sets `owners` keeps the `status` of its parent. `inherit: false` stops inheritance.
+- **Rules stay in their file.** A `rules:` pattern can only change paths below its own file, so a new rule can't take over another team's paths.
+- **"Unowned" is a decision.** `owners: null` marks code that nobody owns on purpose. Everything else without an owner shows up in `owners unowned`.
+- **A lifecycle status.** `status: generated`, `vendored`, or `deprecated` lets a review bot skip generated files without its own ignore list.
+- **A team channel registry.** The root file maps a team to its Slack channels, with a separate channel for automation and a per-bot opt-out.
+- **One resolver for every tool.** Review bots, CI jobs, and alerts all ask the same resolver, so none of them reimplements the resolution steps. It comes as a Python library, a CLI, and a JSON entrypoint that needs only PyYAML.
+
+## Install
+
+```bash
+uv tool install owners-yaml # or: pipx install owners-yaml
+uvx owners-yaml --help # run it once without installing
+```
+
+The package installs two identical commands, `owners` and `owners-yaml`.
+In CI, pin the version (`owners-yaml==0.2.0`), because a new release can change how paths resolve.
+
+Requirements: Python 3.10 or later, PyYAML, and click.
+The commands read tracked files through `git`. Outside a git worktree, pass `--repo-root` and they read the files from disk.
+`lint --live` needs the [GitHub CLI](https://cli.github.com/), signed in.
+
+## Usage
+
+### Write ownership files
+
+The smallest file sets `version` and `owners`:
+
+```yaml
+version: 1
+owners: team-billing
+```
+
+A file can override its own subtree with `rules:`. Within one file, the last matching rule wins:
+
+```yaml
+version: 1
+owners: [team-billing, team-payments]
+rules:
+ - match: 'generated/**'
+ status: generated
+ - match: 'vendor/'
+ owners: null
+```
+
+The root file can also hold repository settings:
+
+```yaml
+version: 1
+owners: []
+github_org: acme
+producers: [review-bot]
+alias_files: [package.yaml]
+teams:
+ team-billing:
+ slack: '#billing'
+ notifications:
+ review-bot: '#billing-reviews'
+```
+
+`alias_files` names the other files that count as ownership files, such as a package manifest that already lists owners.
+Only the `owners` field of such a file is read, and an `owners.yaml` next to it wins.
+The default is `[product.yaml]`, so a repository that never declares the setting still reads its product manifests.
+A declared list replaces the default, and `alias_files: []` turns alias files off.
+A reader that fetches files over a network should set `alias_files: []` in a repository that has no alias files, so it does not probe two names per directory.
+
+[SPEC.md](https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/SPEC.md) lists every field and the full resolution algorithm.
+For editor completion, point your YAML language server at [`owners.schema.json`](https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/owners.schema.json).
+
+### Look up owners
+
+```console
+$ owners resolve --json billing/vendor/stripe.py web/app.ts
+{
+ "billing/vendor/stripe.py": {
+ "owners": [],
+ "slack": null,
+ "source": "billing/owners.yaml",
+ "status": "active"
+ },
+ "web/app.ts": {
+ "owners": [
+ "team-platform"
+ ],
+ "slack": "#team-platform",
+ "source": "owners.yaml",
+ "status": "active"
+ }
+}
+```
+
+`resolve` also reads paths from stdin, one per line. Add `--purpose notifications` to get the channel where automation posts.
+
+To list what nobody owns, run `owners unowned`. Paths under `owners: null` are left out.
+
+### Lint in CI
+
+```console
+$ uvx owners-yaml==0.2.0 lint
+⚠ coverage: 0 of 5 tracked file(s) resolve to unowned
+
+✓ owners.yaml lint passed (1 warning(s))
+```
+
+`lint` fails on schema errors, a directory with two ownership files, and `owners.yaml` files in reserved locations.
+It warns about rule patterns that match no tracked file, and it reports coverage.
+`lint --live` also checks each team slug and `@handle` against the GitHub organization in `github_org`, or in `--org`.
+Pass the changed ownership files as arguments to check only those.
+
+`owners fmt` shows where files could be merged or split without changing any resolution. It never writes.
+
+### Call it from other tools
+
+From Python:
+
+```python
+from owners_yaml import OwnersResolver
+
+resolution = OwnersResolver().resolve("billing/api/invoices.py")
+resolution.owners # ['team-billing', '@alice']
+```
+
+The names exported from the top-level `owners_yaml` package are the public API.
+Submodules can change between minor releases.
+
+From any language, pipe paths to the JSON entrypoint. `uvx` fetches the package from PyPI, so the machine needs only `uv`:
+
+```bash
+echo "billing/api/invoices.py" | uvx --from owners-yaml==0.2.0 python -m owners_yaml --repo-root path/to/repo
+```
+
+The entrypoint imports only PyYAML. A tool that already has the source can run it with no install: `PYTHONPATH=path/to/packages/owners-yaml python3 -m owners_yaml`.
+
+It prints one JSON object keyed by path, in the same shape as `owners resolve --json`.
+`--repo-root` lets a tool resolve against a directory that holds only the ownership files, such as a sparse fetch.
+
+### Resolve without a checkout
+
+The resolver reads ownership files through a source, so it does not need a worktree.
+Implement `read(path)` on anything that can return a file's text: a repository API, an unpacked archive, or a dict in tests.
+`read` returns `None` when the file does not exist.
+
+```python
+from owners_yaml import OwnersResolver
+
+files = {
+ "owners.yaml": "version: 1\nowners: [team-platform]\n",
+ "billing/owners.yaml": "version: 1\nowners: [team-billing]\n",
+}
+
+
+class DictSource:
+ def read(self, path: str) -> str | None:
+ return files.get(path)
+
+
+resolver = OwnersResolver(source=DictSource())
+for path, resolution in resolver.map(["billing/api/invoices.py", "web/app.ts"]).items():
+ print(path, resolution.owners)
+```
+
+```console
+billing/api/invoices.py ['team-billing']
+web/app.ts ['team-platform']
+```
+
+A source that pays per read, such as one that fetches over the network, can also implement `read_all(paths)`.
+`map()` calls it twice before it reads any file: once for the root `owners.yaml`, which names the alias files, then once for the whole batch's ownership files.
+To prefetch yourself instead, ask `ownership_file_paths(paths)` for the same list.
+
+### Export to CODEOWNERS
+
+Some tools read only CODEOWNERS.
+`owners codeowners -o CODEOWNERS.generated` writes the owners of every test file in CODEOWNERS syntax, for test analytics that attribute a failing test to a team.
+The export covers test files only and never writes `.github/CODEOWNERS`.
+
+### Add the commands to your own CLI
+
+Each command is a plain [click](https://click.palletsprojects.com/) command named `owners:<name>`, such as `owners_yaml.cli:cmd_lint`.
+A click-based CLI can register them directly.
+PostHog's `hogli` does this in its `hogli.yaml`:
+
+```yaml
+owners:
+ owners:lint:
+ click: owners_yaml.cli:cmd_lint
+ description: Validate owners.yaml files
+```
+
+## Compared with other tools
+
+| | GitHub CODEOWNERS | Kubernetes/Prow OWNERS | [code_ownership](https://github.com/rubyatscale/code_ownership) | owners-yaml |
+| ---------------------- | ------------------------------ | --------------------------------------- | --------------------------------------------------------------- | ---------------------------------- |
+| Files | One central file | One per directory | Per directory, per file annotation, or per package | One per directory |
+| Resolution | Last matching line in the file | Owners of all parent files are combined | One ownership source per file | Nearest file, field by field |
+| Patterns inside a file | Yes | Yes, regex `filters` | Yes, in the central config | Yes, limited to the file's subtree |
+| Required approvals | Yes, GitHub enforces them | Yes, through Prow | Through the CODEOWNERS file it generates | No, routing only |
+| Coverage check | No | No | Yes | Yes |
+| Lifecycle status | No | No | No | Yes |
+| Team channel registry | No | No | Team config files | Yes, Slack |
+| Generates CODEOWNERS | n/a | No | Yes, the whole repo | Test files only |
+
+Other tools cover parts of this.
+[codeowners-validator](https://github.com/mszostok/codeowners-validator) lints a CODEOWNERS file.
+[codeowners-generator](https://github.com/gagoar/codeowners-generator) builds one from files spread across the repo.
+Backstage and other service catalogs track ownership per service, not per path.
+
+## When not to use it
+
+- **You need GitHub to block merges on an owner's approval.** Keep that in `.github/CODEOWNERS`. `owners.yaml` routes, it doesn't block. The CODEOWNERS export covers test files only.
+- **Your repo is small.** A CODEOWNERS file of a few dozen lines is easier to read than many small files.
+- **You use GitLab or Bitbucket code owner approvals.** The tool reads GitHub team slugs and `@handles`, and the live lint uses the GitHub API.
+- **You need a stable 1.0 API.** The package is at version 0.x. The file format is at version 1, but the Python API can still change between minor releases.
+
+## Project
+
+- [Changelog](https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/CHANGELOG.md)
+- [Specification](https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/SPEC.md)
+- [Issues](https://github.com/PostHog/posthog/issues)
+
+The package lives in the [PostHog monorepo](https://github.com/PostHog/posthog/tree/master/packages/owners-yaml). It has no dependencies on the rest of the monorepo.
+Run its tests with `uv run --no-project --with pyyaml --with click --with pytest pytest packages/owners-yaml/tests`.
+
+To release, bump `version` in `pyproject.toml`, add the matching section to `CHANGELOG.md`, merge, then tag `master`:
+
+```bash
+git tag owners-yaml-v0.2.0 && git push origin owners-yaml-v0.2.0
+```
+
+The tag starts [`publish-owners-yaml.yml`](https://github.com/PostHog/posthog/blob/master/.github/workflows/publish-owners-yaml.yml).
+It checks that the tag matches the version, builds and tests the wheel, and publishes to PyPI with trusted publishing.
+It then creates a GitHub release from the changelog section.
+To retry a failed run, dispatch the workflow on the same tag: `gh workflow run publish-owners-yaml.yml --ref owners-yaml-v0.2.0`.
+
+MIT licensed.
diff --git a/packages/owners-yaml/SPEC.md b/packages/owners-yaml/SPEC.md
new file mode 100644
index 000000000000..51ab1e3c4313
--- /dev/null
+++ b/packages/owners-yaml/SPEC.md
@@ -0,0 +1,425 @@
+# The owners.yaml format
+
+Version: 1
+Status: stable
+
+This document defines the `owners.yaml` file format and how a tool resolves the owner of a path from it.
+`owners-yaml` is the reference implementation.
+A JSON Schema for editors is in [`owners.schema.json`](https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/owners.schema.json).
+
+The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in BCP 14 [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119) [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174) when, and only when, they appear in all capitals, as shown here.
+
+## 1. Terminology
+
+- **Repository**: the tree of files that ownership covers. Paths are relative to its root and use `/` as the separator.
+- **Ownership file**: a file named `owners.yaml`, or an alias file (section 6).
+- **Root file**: the ownership file in the repository root.
+- **Owner**: a team slug, such as `team-billing`, or a person handle, such as `@alice`. A person handle starts with `@`.
+- **Primary owner**: the first entry of a resolved owners list.
+- **Rule**: an entry of `rules:` that overrides fields for the paths its pattern matches.
+- **Resolution**: the result of the algorithm in section 4 for one path.
+- **Unowned**: a path whose resolution has no owners and is not unowned by design.
+- **Unowned by design**: a path whose resolution comes from an explicit `owners: null`.
+
+## 2. File placement
+
+1. An ownership file applies to the directory that contains it and to everything below that directory.
+2. A directory MUST NOT contain more than one ownership file.
+3. A tool MUST read only the file named `owners.yaml` and the alias files of section 6. It MUST NOT read other file names as ownership files.
+4. An `owners.yaml` MUST NOT be placed in a directory where other tooling reads every YAML file. `.github/workflows/` and its subdirectories are always reserved. The root file MAY reserve more locations with `reserved_dirs` (section 5).
+
+## 3. Fields
+
+An ownership file is a YAML mapping.
+
+| Field | Required | Type | Meaning |
+| --------- | -------- | ---------------------------------- | ----------------------------------------------------------------------------- |
+| `version` | yes | integer | The format version. MUST be the integer `1`, not a boolean, float, or string. |
+| `owners` | yes | string, list of strings, or `null` | The owners of the directory. |
+| `status` | no | string | The lifecycle of the code. |
+| `inherit` | no | boolean | Whether fields fall through from ancestor files. Default `true`. |
+| `rules` | no | list of rule mappings | Per-path overrides inside this directory. |
+
+The root file MAY also carry the repository settings in section 5.
+Any other top-level field is an error.
+
+### 3.1 `owners`
+
+1. A string is a list with one entry.
+2. Each entry MUST be a non-empty string.
+3. A list MUST be ordered. The first entry is the primary owner.
+4. `null` means the directory is unowned by design. A coverage check MUST NOT report such paths.
+5. An empty list means the file sets no owners. The owners of the nearest ancestor apply.
+6. Any other value is an error. The file then sets no owners, as with an empty list, and its other fields still apply.
+
+### 3.2 `status`
+
+The value MUST be one of these:
+
+| Value | Meaning |
+| ------------ | ----------------------------------------------------------------------- |
+| `active` | Maintained code. This is the default. |
+| `deprecated` | Code that is due for removal. |
+| `generated` | Output of a generator. A review tool SHOULD NOT request reviews for it. |
+| `vendored` | Third-party code copied into the repository. |
+
+### 3.3 `inherit`
+
+`inherit: false` discards everything that ancestor files contributed, for every path the file applies to.
+A rule MAY set `inherit` to change this for the paths it matches.
+
+### 3.4 `rules`
+
+Each rule is a mapping with these fields:
+
+| Field | Required | Type | Meaning |
+| --------- | -------- | ----------------------------------- | ----------------------------------------------------- |
+| `match` | yes | string or non-empty list of strings | Patterns, relative to the directory of the file. |
+| `owners` | no | as in 3.1 | Replaces the file-level owners for matching paths. |
+| `status` | no | as in 3.2 | Replaces the file-level status for matching paths. |
+| `inherit` | no | boolean | Replaces the file-level `inherit` for matching paths. |
+
+1. A rule with a list of valid patterns is equal to one rule per pattern, in list order, with the same fields.
+2. Within one file, the last rule whose pattern matches a path applies. Earlier matching rules have no effect.
+3. A rule MUST NOT change the resolution of a path outside the directory of its file.
+4. A rule with a pattern that the matcher rejects is an error. A tool MUST ignore the whole rule, including its other patterns, and MAY continue with the rest of the file.
+
+### 3.5 Patterns
+
+Patterns use the GitHub CODEOWNERS syntax, applied to paths relative to the directory of the file:
+
+1. A pattern that starts with `/` is anchored to that directory.
+2. A pattern with no `/`, or with only a trailing `/`, matches at any depth.
+3. A pattern that contains a `/` other than at the end is anchored to that directory.
+4. A trailing `/` matches the directory and everything below it.
+5. A pattern whose last segment has no wildcard also matches everything below a directory of that name.
+6. `*` matches any characters except `/`. `?` matches one character except `/`. `**` matches zero or more directories.
+7. `[abc]` matches one character from the set. `[a-z]` matches one character from the range. A `[!` or a `[^` at the start negates the set. A set MUST NOT match `/`. A `]` in the first position is a member of the set, not the end of it. An unclosed `[` is a literal `[`. GitHub CODEOWNERS has no character classes, so this rule is an extension of that syntax.
+8. `\` escapes the next character.
+9. A pattern MUST NOT be empty and MUST NOT contain `***`.
+
+## 4. Resolution
+
+A consumer SHOULD get resolutions from an implementation of this algorithm, not by reading ownership files itself.
+
+To resolve a path `P`:
+
+1. Normalize `P`: replace `\` with `/`, then remove any leading `./` and `/`.
+2. List the directories from the repository root down to the parent directory of `P`, root first.
+3. For each directory, find its ownership file. Skip the directory when it has none. A file that is not a YAML mapping, or that lacks `version: 1` or `owners`, counts as absent.
+4. Start with an empty result: owners unset, status unset, source unset.
+5. For each file found in step 3, in order:
+ 1. Take the file-level `owners`, `status`, and `inherit`.
+ 2. Find the last rule in the file that matches `P` (section 3.4). If one matches, replace each field that the rule sets.
+ 3. If `inherit` is `false`, reset the result to empty.
+ 4. If `owners` is `null`, set the result owners to `null` and the source to this file.
+ 5. If `owners` is a non-empty list, set the result owners to that list and the source to this file.
+ 6. If `status` is set, set the result status to it.
+6. Return the resolution:
+ - `owners`: the result owners, or an empty list when unset or `null`.
+ - `unowned_by_design`: `true` when the result owners are `null`.
+ - `status`: the result status, or `active` when unset.
+ - `source`: the path of the file that set the owners, or none.
+ - `slack`: the channel from section 5.2, for the requested purpose.
+
+A path is unowned when `owners` is empty and `unowned_by_design` is `false`.
+
+### 4.1 Field merge
+
+Step 5 applies each file's values to the result as this table shows.
+The value is the file-level value after the matching rule replaced it.
+
+| Field | Value in the file | Effect on the result |
+| --------- | ----------------- | ------------------------------------------------------------------- |
+| `inherit` | `false` | The result is reset to empty before the other fields apply. |
+| `inherit` | `true` or absent | No effect. |
+| `owners` | non-empty list | Owners become this list. Source becomes this file. |
+| `owners` | `[]` | No effect. |
+| `owners` | `null` | Owners become `null` (unowned by design). Source becomes this file. |
+| `status` | set | Status becomes this value. |
+| `status` | absent | No effect. |
+
+### 4.2 Flow (non-normative)
+
+The numbered steps above are normative. This diagram shows the same walk.
+
+```mermaid
+flowchart TD
+ start([Path P]) --> walk[Take the next directory, from the root to the parent of P]
+ walk --> has{Has an ownership file?}
+ has -- no --> more
+ has -- yes --> take[Take the file's owners, status, and inherit]
+ take --> rule{Does a rule match P?<br/>The last match wins}
+ rule -- yes --> apply[Replace the fields that the rule sets]
+ rule -- no --> cut
+ apply --> cut{inherit is false?}
+ cut -- yes --> reset[Reset the result]
+ cut -- no --> merge
+ reset --> merge[Merge owners and status as in 4.1]
+ merge --> more{More directories?}
+ more -- yes --> walk
+ more -- no --> done([Return owners, unowned_by_design, status, source, slack])
+```
+
+### 4.3 Conformance
+
+The cases in [`conformance/`](https://github.com/PostHog/posthog/tree/master/packages/owners-yaml/conformance) are part of this specification.
+An implementation of section 4 and section 5.2 MUST produce the expected result for every case that applies to it.
+When the prose and a case disagree, the disagreement is a defect in this specification.
+
+## 5. Repository settings
+
+Only the root file MAY carry these fields. A tool MUST report them as errors in any other file.
+
+| Field | Type | Meaning |
+| --------------- | ---------------- | --------------------------------------------------------------------------------------------------------- |
+| `teams` | mapping | The team channel registry (section 5.2). |
+| `github_org` | string | The GitHub organization of the team slugs. |
+| `producers` | list of strings | The automation names a team can address in `notifications`. |
+| `reserved_dirs` | list of patterns | Extra locations where `owners.yaml` MUST NOT be placed. The patterns are relative to the repository root. |
+| `alias_files` | list of strings | The other file names that count as ownership files (section 6). Defaults to `[product.yaml]`. |
+| `codeowners` | mapping | How a CODEOWNERS export spells test file paths. This field is specific to `owners-yaml` (section 8). |
+
+### 5.1 `github_org`
+
+1. A tool that converts a team slug to a GitHub team MUST use the handle `@<github_org>/<slug>`.
+2. The value MUST NOT contain `/`.
+3. A tool MAY accept an override on its command line.
+
+### 5.2 Team channels
+
+`teams` maps a team slug to a mapping with these OPTIONAL fields:
+
+| Field | Type | Meaning |
+| --------------- | ---------------------------------------------------------------- | ------------------------------ |
+| `slack` | channel or `false` | Where people on the team talk. |
+| `notifications` | channel, `false`, or a mapping of producer to channel or `false` | Where automation posts. |
+
+1. A channel is a string that starts with `#`.
+2. `false` means the team has no channel for that purpose.
+3. A key of `teams` MUST be a team slug. It MUST NOT be a person handle.
+4. When the root file declares `producers`, each key of a `notifications` mapping MUST be in that list. When it does not, any non-empty name is valid.
+5. A tool that cannot read a `notifications` mapping SHOULD treat it as `false`, so a typo silences automation instead of posting to an unwanted channel. One rejected entry makes the whole mapping unreadable: keeping the other entries would send the rejected producer to the `slack` channel.
+
+To find the channel for a team slug `T`, a purpose, and an optional producer:
+
+1. If `T` has no entry in `teams`, return `#T`. The result is derived, not declared.
+2. For the purpose "people", check `slack`.
+3. For the purpose "notifications", check `notifications` first, then `slack`.
+4. When the checked value is a mapping, take the value for the producer. With no producer, or when the mapping does not name it, move to the next field.
+5. When the checked value is a channel, return it. When it is `false`, return no channel. Both results are declared.
+6. When no field gives a value, return `#T` as a derived result.
+
+The channel of a path is the channel of its primary owner.
+When the primary owner is a person handle, the path has no channel.
+
+## 6. Alias files
+
+An alias file is a file with another name that a tool reads as an ownership file, such as a package manifest that already lists owners.
+The root file declares the alias files in `alias_files` (section 5).
+
+1. Each entry of `alias_files` MUST be a bare file name. It MUST NOT contain `/` or `\`, and it MUST NOT be `.` or `..`.
+2. An entry MUST NOT be `owners.yaml`. An entry MUST NOT appear twice.
+3. `alias_files` MUST NOT hold more than 8 entries. A tool MUST ignore the whole list when it does.
+4. When the root file does not declare `alias_files`, the alias file names MUST be `product.yaml` and nothing else.
+5. When the root file declares `alias_files` and the declaration is valid, the alias file names MUST be exactly the declared entries. A tool MUST NOT add `product.yaml` to a declared list. An empty declared list means the repository has no alias file.
+6. When the root file declares `alias_files` and a tool ignores the declaration as invalid, the repository MUST have no alias file. A tool MUST NOT fall back to `product.yaml` there.
+7. A tool MUST NOT read a file as an ownership file unless the file is named `owners.yaml` or its name is one of the alias file names.
+8. A tool MUST read only the `owners` field of an alias file. All other fields have no effect on ownership.
+9. The `owners` field MUST be a list of non-empty strings. Otherwise the file counts as absent.
+10. An `owners.yaml` in the same directory takes precedence. A linter SHOULD report a directory that has both.
+11. When a directory holds more than one alias file, the first name in `alias_files` decides. A linter SHOULD report that directory.
+12. An alias file in the repository root has no effect. The names come from the root `owners.yaml`, and that file takes precedence over any alias file next to it.
+
+A repository with no root file has the default alias file name. A repository whose root file declares an empty `alias_files` has none, and only `owners.yaml` decides ownership there.
+
+## 7. Resolver interface
+
+This section applies to an implementation that answers resolution requests from other programs through a command.
+In `owners-yaml`, both `owners resolve --json` and `python -m owners_yaml` implement it.
+
+### 7.1 Request
+
+1. The caller MAY pass paths as command arguments.
+2. When the caller passes no path arguments, the resolver MUST read paths from standard input, one path per line. It MUST remove whitespace at the start and end of each line and MUST skip empty lines.
+3. The caller MAY name the repository root. Without one, the resolver MAY find the root itself, for example from the git worktree.
+4. The caller MAY name the purpose of the channel: people or notifications (section 5.2). The default is people. `owners-yaml` spells these `--purpose slack` and `--purpose notifications`.
+
+### 7.2 Response
+
+1. On success, the resolver MUST write one JSON object to standard output and exit with status 0.
+2. Each key MUST be a requested path after normalization (section 4, step 1). Two requests that normalize to the same path produce one key.
+3. Each value MUST be an object with these members:
+
+ | Member | Type | Value |
+ | -------- | ---------------- | ------------------------------------------------------------------------- |
+ | `owners` | array of strings | The resolved owners. Empty when the path is unowned or unowned by design. |
+ | `status` | string | The resolved status. |
+ | `slack` | string or `null` | The channel for the requested purpose. |
+ | `source` | string or `null` | The repository-relative path of the file that set the owners. |
+
+4. A path that is unowned by design has an empty `owners` array and a non-null `source`. An unowned path has an empty `owners` array and a `null` source.
+5. An unowned path is not an error.
+
+[`resolution.schema.json`](https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/resolution.schema.json) describes this object.
+
+### 7.3 Errors
+
+1. When the repository root does not exist or cannot be found, the resolver MUST exit with a non-zero status.
+2. On an error, the resolver MUST NOT write a partial response to standard output.
+
+### 7.4 Compatibility
+
+1. A consumer MUST ignore members that it does not know.
+2. An implementation MAY add members to a value.
+3. Removing a member, renaming it, or changing its meaning requires a new version of this specification.
+4. For the Python library, the names exported from the top-level `owners_yaml` package are the public API. Submodules can change between minor releases.
+
+## 8. The owners-yaml reference implementation
+
+This section describes the reference implementation. It is not part of the format.
+
+- It reads the alias files the root `owners.yaml` declares. PostHog's own repository declares `product.yaml`.
+- It removes the placeholder owner `team-CHANGEME` from every owners list.
+- Its linter reports schema errors, reserved locations, directories with both an `owners.yaml` and an alias file, rule patterns that match no tracked file, and the number of unowned files. With `--live`, it also checks team slugs and person handles against the GitHub organization.
+- Its CODEOWNERS export covers test files only: `test_*.py` and `*_test.py` for pytest, and `*.test.*` or `*.spec.*` with a `.js`, `.jsx`, `.ts`, or `.tsx` extension for Jest. The `codeowners` setting accepts these keys:
+
+ | Key | Meaning |
+ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
+ | `jest_root` | A directory whose Jest suite runs the tests of other packages. |
+ | `jest_root_tests` | A pattern, relative to the repository root, for the test files that `jest_root` runs. Those files get an extra spelling relative to `jest_root`. |
+ | `jest_root_packages` | A directory whose packages do not run their own Jest suite, so their files get no package-relative spelling. |
+
+## 9. Examples (non-normative)
+
+The smallest valid file:
+
+```yaml
+version: 1
+owners: team-billing
+```
+
+A file with every directory-level field:
+
+```yaml
+version: 1
+owners: [team-billing, '@alice']
+status: active
+inherit: true
+rules:
+ - match: 'generated/**'
+ status: generated
+ - match: 'vendor/'
+ status: vendored
+ owners: null
+ - match: ['migrations/', 'legacy/']
+ owners: [team-billing, team-data]
+```
+
+A root file with repository settings:
+
+```yaml
+version: 1
+owners: []
+github_org: acme
+producers: [review-bot, deploy-bot]
+reserved_dirs: ['services/*/openapi/**']
+alias_files: [package.yaml]
+teams:
+ team-billing:
+ slack: '#billing'
+ notifications:
+ review-bot: '#billing-reviews'
+ deploy-bot: false
+ team-legacy:
+ slack: false
+```
+
+A worked example. The repository has three ownership files:
+
+```yaml
+# owners.yaml
+version: 1
+owners: team-platform
+status: active
+teams:
+ team-billing:
+ notifications: '#billing-bots'
+```
+
+```yaml
+# billing/owners.yaml
+version: 1
+owners: [team-billing, '@alice']
+status: deprecated
+rules:
+ - match: 'api/'
+ status: active
+ - match: 'vendor/'
+ owners: null
+```
+
+```yaml
+# billing/legacy/owners.yaml
+version: 1
+owners: []
+inherit: false
+```
+
+The trace for `billing/api/invoices.py`:
+
+| Step | File | Values after the rule | Result after the step |
+| ---- | --------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
+| 1 | `owners.yaml` | owners `[team-platform]`, status `active` | owners `[team-platform]`, status `active`, source `owners.yaml` |
+| 2 | `billing/owners.yaml` | rule `api/` matches: owners `[team-billing, @alice]`, status `active` | owners `[team-billing, @alice]`, status `active`, source `billing/owners.yaml` |
+
+The primary owner is `team-billing`. Its registry entry has no `slack`, so the people channel is the derived `#team-billing`. The notifications channel is `#billing-bots`.
+
+The results for all four paths, with the purpose "people":
+
+| Path | `owners` | `unowned_by_design` | `status` | `source` | `slack` |
+| ------------------------- | ------------------------ | ------------------- | ------------ | --------------------- | --------------- |
+| `billing/api/invoices.py` | `[team-billing, @alice]` | `false` | `active` | `billing/owners.yaml` | `#team-billing` |
+| `billing/jobs/run.py` | `[team-billing, @alice]` | `false` | `deprecated` | `billing/owners.yaml` | `#team-billing` |
+| `billing/vendor/lib.py` | `[]` | `true` | `deprecated` | `billing/owners.yaml` | none |
+| `billing/legacy/old.py` | `[]` | `false` | `active` | none | none |
+
+`billing/legacy/old.py` is unowned: `inherit: false` drops everything from the parent files, and the file itself sets no owners. The status is the default, `active`.
+
+Invalid files:
+
+```yaml
+# Missing `version`: the file counts as absent.
+owners: team-billing
+```
+
+```yaml
+# `teams` outside the root file is an error.
+version: 1
+owners: team-billing
+teams:
+ team-billing:
+ slack: '#billing'
+```
+
+```yaml
+# `***` is not a valid pattern, so the rule is ignored.
+version: 1
+owners: team-billing
+rules:
+ - match: 'a***b'
+ owners: team-other
+```
+
+## 10. Design notes (non-normative)
+
+- **Nearest file wins, per field.** Kubernetes OWNERS files add approvers from every ancestor, which fits "someone must approve". For routing, the union tags too many teams, so the nearest file wins. The merge is per field, so a child file that sets only `owners` keeps the `status` of its ancestors.
+- **Rules stay in their file.** In a single CODEOWNERS file, a broad pattern added late can take over earlier specific lines. Here a rule changes only its own directory, so a new rule cannot take over paths in another directory.
+- **Unowned is a decision.** `owners: null` records that nobody owns a path on purpose. A missing owner fails the coverage check.
+- **The alias default is for old trees.** `product.yaml` is the default alias file name so that a repository written before `alias_files` existed resolves the same as it did then. A repository with no alias files sets `alias_files: []` and pays no lookups for it.
+- **Routing, not approval.** The format answers "who owns this path" for review requests, alerts, and reports. It does not replace a platform's required-approval rules.
+
+## Changelog
+
+- **1** (2026-09): First published version.
+- **1**, amended (2026-09): Section 3.5 adds `[...]` character classes. No pattern that was valid before the amendment changes meaning. Section 6 gives `alias_files` the default `[product.yaml]`, so a root file that does not declare the key now has one alias file instead of none.
diff --git a/packages/owners-yaml/conformance/README.md b/packages/owners-yaml/conformance/README.md
new file mode 100644
index 000000000000..5525c464a72d
--- /dev/null
+++ b/packages/owners-yaml/conformance/README.md
@@ -0,0 +1,104 @@
+# owners.yaml conformance suite
+
+This directory holds test cases for the resolution rules of the `owners.yaml` format.
+The cases are data, so an implementation in any language can run them.
+
+The cases are normative together with [SPEC.md section 4](https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/SPEC.md#4-resolution) and [section 5.2](https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/SPEC.md#52-team-channels).
+An implementation of those sections must give the expected result for every case that applies to it.
+
+## Contents
+
+- `cases/`: case files. Each file holds the cases for one topic.
+- `case.schema.json`: a JSON Schema (draft 2020-12) for one case file.
+
+## Case file format
+
+A case file is a YAML mapping with one key, `cases`.
+The value is a list of cases.
+Each case is a mapping with these keys:
+
+| Key | Required | Type | Meaning |
+| ---------- | -------- | ------------------------------- | ------------------------------------------------------------------------------------------- |
+| `name` | yes | string | A sentence that states the behavior. It is unique in its file. |
+| `files` | yes | mapping of string to string | The repository. Each key is a file path relative to the root. Each value is the content. |
+| `purpose` | no | `slack` or `notifications` | The channel purpose (section 5.2). `slack` is the purpose "people". The default is `slack`. |
+| `producer` | no | string | The producer for the channel lookup (section 5.2). The default is no producer. |
+| `expect` | yes | mapping of string to resolution | Each key is a path to resolve. Each value is the expected resolution of that path. |
+
+File paths in `files` use `/` as the separator.
+A file content can be empty or can be text that is not valid YAML, because some cases test files that count as absent.
+
+A path in `expect` is the input to the resolver, before normalization.
+Some keys start with `./` or `/`, or contain `\`, to test step 1 of the algorithm.
+A path in `expect` does not have to exist in `files`.
+
+Each resolution is a mapping with all five keys:
+
+| Key | Type | Meaning |
+| ------------------- | ---------------- | -------------------------------------------------------------------------- |
+| `owners` | list of strings | The resolved owners, in order. The list is empty when there are no owners. |
+| `unowned_by_design` | boolean | `true` when the owners come from an explicit `owners: null`. |
+| `status` | string | The resolved status. |
+| `source` | string or `null` | The path of the file that set the owners, or `null` when no file did. |
+| `slack` | string or `null` | The channel for the purpose and the producer of the case, or `null`. |
+
+A case never leaves a key out, so no value is implied.
+
+An example case:
+
+```yaml
+cases:
+ - name: a child file that sets only owners keeps the parent's status
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ status: deprecated
+ billing/owners.yaml: |
+ version: 1
+ owners: team-b
+ expect:
+ billing/x.py:
+ owners: [team-b]
+ unowned_by_design: false
+ status: deprecated
+ source: billing/owners.yaml
+ slack: '#team-b'
+```
+
+## How a runner uses a case
+
+For each case in each file in `cases/`:
+
+1. Make a new empty directory. This directory is the repository root. It is not a git repository.
+2. Write each entry of `files` to its path below the root. Make the parent directories first. Write the content exactly as given.
+3. Resolve each key of `expect` as given, with the `purpose` and the `producer` of the case.
+4. Compare all five keys of the result with the expected resolution. The order of `owners` is significant.
+5. The case passes when every path in `expect` passes.
+
+Give each test a name of the form `<file name>::<case name>`, such as `nearest-file.yaml::owners null marks paths as unowned by design`.
+Before a run, a runner can validate each case file against `case.schema.json`.
+
+## Cases that apply only to some implementations
+
+- `aliases.yaml` applies only to an implementation that supports alias files ([SPEC.md section 6](https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/SPEC.md#6-alias-files)). Its cases declare `product.yaml` in `alias_files`.
+- `owners-yaml-extensions.yaml` is not part of the format. It tests the `team-CHANGEME` placeholder of `owners-yaml` ([SPEC.md section 8](https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/SPEC.md#8-the-owners-yaml-reference-implementation)). Other implementations skip this file.
+- A case with a `producer` applies only to an implementation that accepts a producer.
+
+All other files apply to every implementation.
+
+## Reference runner
+
+The `owners-yaml` runner is [`tests/test_conformance.py`](https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/tests/test_conformance.py).
+From the repository root, run it with this command:
+
+```sh
+uv run pytest packages/owners-yaml/tests/test_conformance.py
+```
+
+## Add a case
+
+1. Put the case in the file for its topic. Make a new file only for a new topic.
+2. Write the `name` as a statement of the behavior.
+3. Get each expected value from SPEC.md, then run the reference runner to confirm it.
+4. When SPEC.md and a case disagree, the disagreement is a defect in SPEC.md ([section 4.3](https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/SPEC.md#43-conformance)). Fix SPEC.md or the case, not only the implementation.
diff --git a/packages/owners-yaml/conformance/case.schema.json b/packages/owners-yaml/conformance/case.schema.json
new file mode 100644
index 000000000000..22043f910045
--- /dev/null
+++ b/packages/owners-yaml/conformance/case.schema.json
@@ -0,0 +1,68 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/conformance/case.schema.json",
+ "title": "owners.yaml conformance case file",
+ "type": "object",
+ "required": ["cases"],
+ "additionalProperties": false,
+ "properties": {
+ "cases": {
+ "type": "array",
+ "minItems": 1,
+ "items": { "$ref": "#/$defs/case" }
+ }
+ },
+ "$defs": {
+ "case": {
+ "type": "object",
+ "required": ["name", "files", "expect"],
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "description": "A sentence that states the behavior. Unique within the file.",
+ "type": "string",
+ "minLength": 1
+ },
+ "files": {
+ "description": "Repository-relative path to file content. Paths use / as the separator.",
+ "type": "object",
+ "minProperties": 1,
+ "additionalProperties": { "type": "string" }
+ },
+ "purpose": {
+ "description": "The channel purpose of SPEC section 5.2. slack is the purpose \"people\".",
+ "enum": ["slack", "notifications"],
+ "default": "slack"
+ },
+ "producer": {
+ "description": "The automation name for the channel lookup of SPEC section 5.2.",
+ "type": "string",
+ "minLength": 1
+ },
+ "expect": {
+ "description": "Path to resolve, as given to the resolver, to its expected resolution.",
+ "type": "object",
+ "minProperties": 1,
+ "additionalProperties": { "$ref": "#/$defs/resolution" }
+ }
+ }
+ },
+ "resolution": {
+ "type": "object",
+ "required": ["owners", "unowned_by_design", "status", "source", "slack"],
+ "additionalProperties": false,
+ "properties": {
+ "owners": {
+ "type": "array",
+ "items": { "type": "string", "minLength": 1 }
+ },
+ "unowned_by_design": { "type": "boolean" },
+ "status": { "enum": ["active", "deprecated", "generated", "vendored"] },
+ "source": { "type": ["string", "null"] },
+ "slack": {
+ "oneOf": [{ "type": "string", "pattern": "^#" }, { "type": "null" }]
+ }
+ }
+ }
+ }
+}
diff --git a/packages/owners-yaml/conformance/cases/aliases.yaml b/packages/owners-yaml/conformance/cases/aliases.yaml
new file mode 100644
index 000000000000..40ff96ed95e2
--- /dev/null
+++ b/packages/owners-yaml/conformance/cases/aliases.yaml
@@ -0,0 +1,218 @@
+# These cases apply only to an implementation that supports alias files (SPEC section 6).
+# product.yaml is the default alias file name, and most cases here declare it explicitly.
+cases:
+ - name: a product.yaml owners list decides ownership
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ alias_files: [product.yaml]
+ products/foo/product.yaml: |
+ name: Foo
+ owners:
+ - team-foo
+ expect:
+ products/foo/backend/x.py:
+ owners: [team-foo]
+ unowned_by_design: false
+ status: active
+ source: products/foo/product.yaml
+ slack: '#team-foo'
+
+ - name: only the owners field of product.yaml has an effect
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ status: deprecated
+ alias_files: [product.yaml]
+ products/foo/product.yaml: |
+ name: Foo
+ owners: [team-foo]
+ status: generated
+ inherit: false
+ rules:
+ - match: '*.py'
+ owners: team-rule
+ expect:
+ products/foo/x.py:
+ owners: [team-foo]
+ unowned_by_design: false
+ status: deprecated
+ source: products/foo/product.yaml
+ slack: '#team-foo'
+
+ - name: an owners.yaml in the same directory takes precedence over product.yaml
+ files:
+ owners.yaml: |
+ version: 1
+ owners: []
+ alias_files: [product.yaml]
+ products/foo/owners.yaml: |
+ version: 1
+ owners: team-owners-file
+ products/foo/product.yaml: |
+ name: Foo
+ owners: [team-foo]
+ expect:
+ products/foo/x.py:
+ owners: [team-owners-file]
+ unowned_by_design: false
+ status: active
+ source: products/foo/owners.yaml
+ slack: '#team-owners-file'
+
+ - name: product.yaml applies when the owners.yaml next to it is invalid
+ files:
+ owners.yaml: |
+ version: 1
+ owners: []
+ alias_files: [product.yaml]
+ products/foo/owners.yaml: |
+ owners: team-owners-file
+ products/foo/product.yaml: |
+ name: Foo
+ owners: [team-foo]
+ expect:
+ products/foo/x.py:
+ owners: [team-foo]
+ unowned_by_design: false
+ status: active
+ source: products/foo/product.yaml
+ slack: '#team-foo'
+
+ - name: a product.yaml whose owners is not a list counts as absent
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ alias_files: [product.yaml]
+ products/string/product.yaml: |
+ owners: team-foo
+ products/null/product.yaml: |
+ owners: null
+ products/missing/product.yaml: |
+ name: Missing
+ products/bad-entry/product.yaml: |
+ owners: [team-foo, '']
+ expect:
+ products/string/x.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+ products/null/x.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+ products/missing/x.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+ products/bad-entry/x.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+
+ - name: a product.yaml with an empty owners list falls through
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ alias_files: [product.yaml]
+ products/foo/product.yaml: |
+ owners: []
+ expect:
+ products/foo/x.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+
+ - name: product.yaml is the alias file when the root file declares no alias_files
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ products/foo/product.yaml: |
+ name: Foo
+ owners:
+ - team-foo
+ expect:
+ products/foo/backend/x.py:
+ owners: [team-foo]
+ unowned_by_design: false
+ status: active
+ source: products/foo/product.yaml
+ slack: '#team-foo'
+
+ - name: an empty alias_files list leaves product.yaml as an ordinary file
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ alias_files: []
+ products/foo/product.yaml: |
+ name: Foo
+ owners:
+ - team-foo
+ expect:
+ products/foo/backend/x.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+
+ - name: a declared alias_files list without product.yaml leaves product.yaml as an ordinary file
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ alias_files: [package.yaml]
+ products/foo/product.yaml: |
+ name: Foo
+ owners:
+ - team-foo
+ products/bar/package.yaml: |
+ owners:
+ - team-bar
+ expect:
+ products/foo/backend/x.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+ products/bar/backend/x.py:
+ owners: [team-bar]
+ unowned_by_design: false
+ status: active
+ source: products/bar/package.yaml
+ slack: '#team-bar'
+
+ - name: the first declared alias file in a directory decides
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ alias_files: [product.yaml, package.yaml]
+ products/foo/package.yaml: |
+ owners: [team-package]
+ products/foo/product.yaml: |
+ owners: [team-product]
+ expect:
+ products/foo/x.py:
+ owners: [team-product]
+ unowned_by_design: false
+ status: active
+ source: products/foo/product.yaml
+ slack: '#team-product'
diff --git a/packages/owners-yaml/conformance/cases/channels.yaml b/packages/owners-yaml/conformance/cases/channels.yaml
new file mode 100644
index 000000000000..aa6d263f6e1d
--- /dev/null
+++ b/packages/owners-yaml/conformance/cases/channels.yaml
@@ -0,0 +1,577 @@
+cases:
+ - name: the slack purpose reads only the slack field of the registry
+ files:
+ owners.yaml: |
+ version: 1
+ owners: []
+ teams:
+ team-split:
+ slack: '#split-people'
+ notifications: '#split-bots'
+ team-people:
+ slack: '#people-only'
+ team-bots-only:
+ notifications: '#bots-only'
+ team-quiet-bots:
+ slack: '#quiet-people'
+ notifications: false
+ team-silent:
+ slack: false
+ team-empty: {}
+ team-mapped:
+ slack: '#mapped-people'
+ notifications:
+ review-bot: '#mapped-reviews'
+ deploy-bot: false
+ team-mapped-no-slack:
+ notifications:
+ review-bot: '#mapped-no-slack-reviews'
+ team-split/owners.yaml: |
+ version: 1
+ owners: team-split
+ team-people/owners.yaml: |
+ version: 1
+ owners: team-people
+ team-bots-only/owners.yaml: |
+ version: 1
+ owners: team-bots-only
+ team-quiet-bots/owners.yaml: |
+ version: 1
+ owners: team-quiet-bots
+ team-silent/owners.yaml: |
+ version: 1
+ owners: team-silent
+ team-empty/owners.yaml: |
+ version: 1
+ owners: team-empty
+ team-mapped/owners.yaml: |
+ version: 1
+ owners: team-mapped
+ team-unregistered/owners.yaml: |
+ version: 1
+ owners: team-unregistered
+ expect:
+ team-split/x.py:
+ owners: [team-split]
+ unowned_by_design: false
+ status: active
+ source: team-split/owners.yaml
+ slack: '#split-people'
+ team-people/x.py:
+ owners: [team-people]
+ unowned_by_design: false
+ status: active
+ source: team-people/owners.yaml
+ slack: '#people-only'
+ team-bots-only/x.py:
+ owners: [team-bots-only]
+ unowned_by_design: false
+ status: active
+ source: team-bots-only/owners.yaml
+ slack: '#team-bots-only'
+ team-quiet-bots/x.py:
+ owners: [team-quiet-bots]
+ unowned_by_design: false
+ status: active
+ source: team-quiet-bots/owners.yaml
+ slack: '#quiet-people'
+ team-silent/x.py:
+ owners: [team-silent]
+ unowned_by_design: false
+ status: active
+ source: team-silent/owners.yaml
+ slack: null
+ team-empty/x.py:
+ owners: [team-empty]
+ unowned_by_design: false
+ status: active
+ source: team-empty/owners.yaml
+ slack: '#team-empty'
+ team-mapped/x.py:
+ owners: [team-mapped]
+ unowned_by_design: false
+ status: active
+ source: team-mapped/owners.yaml
+ slack: '#mapped-people'
+ team-unregistered/x.py:
+ owners: [team-unregistered]
+ unowned_by_design: false
+ status: active
+ source: team-unregistered/owners.yaml
+ slack: '#team-unregistered'
+
+ - name: the notifications purpose checks notifications first and then slack
+ files:
+ owners.yaml: |
+ version: 1
+ owners: []
+ teams:
+ team-split:
+ slack: '#split-people'
+ notifications: '#split-bots'
+ team-people:
+ slack: '#people-only'
+ team-bots-only:
+ notifications: '#bots-only'
+ team-quiet-bots:
+ slack: '#quiet-people'
+ notifications: false
+ team-silent:
+ slack: false
+ team-empty: {}
+ team-mapped:
+ slack: '#mapped-people'
+ notifications:
+ review-bot: '#mapped-reviews'
+ deploy-bot: false
+ team-mapped-no-slack:
+ notifications:
+ review-bot: '#mapped-no-slack-reviews'
+ team-split/owners.yaml: |
+ version: 1
+ owners: team-split
+ team-people/owners.yaml: |
+ version: 1
+ owners: team-people
+ team-bots-only/owners.yaml: |
+ version: 1
+ owners: team-bots-only
+ team-quiet-bots/owners.yaml: |
+ version: 1
+ owners: team-quiet-bots
+ team-silent/owners.yaml: |
+ version: 1
+ owners: team-silent
+ team-empty/owners.yaml: |
+ version: 1
+ owners: team-empty
+ team-unregistered/owners.yaml: |
+ version: 1
+ owners: team-unregistered
+ purpose: notifications
+ expect:
+ team-split/x.py:
+ owners: [team-split]
+ unowned_by_design: false
+ status: active
+ source: team-split/owners.yaml
+ slack: '#split-bots'
+ team-people/x.py:
+ owners: [team-people]
+ unowned_by_design: false
+ status: active
+ source: team-people/owners.yaml
+ slack: '#people-only'
+ team-bots-only/x.py:
+ owners: [team-bots-only]
+ unowned_by_design: false
+ status: active
+ source: team-bots-only/owners.yaml
+ slack: '#bots-only'
+ team-quiet-bots/x.py:
+ owners: [team-quiet-bots]
+ unowned_by_design: false
+ status: active
+ source: team-quiet-bots/owners.yaml
+ slack: null
+ team-silent/x.py:
+ owners: [team-silent]
+ unowned_by_design: false
+ status: active
+ source: team-silent/owners.yaml
+ slack: null
+ team-empty/x.py:
+ owners: [team-empty]
+ unowned_by_design: false
+ status: active
+ source: team-empty/owners.yaml
+ slack: '#team-empty'
+ team-unregistered/x.py:
+ owners: [team-unregistered]
+ unowned_by_design: false
+ status: active
+ source: team-unregistered/owners.yaml
+ slack: '#team-unregistered'
+
+ - name: a notifications mapping without a producer moves on to slack
+ files:
+ owners.yaml: |
+ version: 1
+ owners: []
+ teams:
+ team-split:
+ slack: '#split-people'
+ notifications: '#split-bots'
+ team-people:
+ slack: '#people-only'
+ team-bots-only:
+ notifications: '#bots-only'
+ team-quiet-bots:
+ slack: '#quiet-people'
+ notifications: false
+ team-silent:
+ slack: false
+ team-empty: {}
+ team-mapped:
+ slack: '#mapped-people'
+ notifications:
+ review-bot: '#mapped-reviews'
+ deploy-bot: false
+ team-mapped-no-slack:
+ notifications:
+ review-bot: '#mapped-no-slack-reviews'
+ team-mapped/owners.yaml: |
+ version: 1
+ owners: team-mapped
+ team-mapped-no-slack/owners.yaml: |
+ version: 1
+ owners: team-mapped-no-slack
+ purpose: notifications
+ expect:
+ team-mapped/x.py:
+ owners: [team-mapped]
+ unowned_by_design: false
+ status: active
+ source: team-mapped/owners.yaml
+ slack: '#mapped-people'
+ team-mapped-no-slack/x.py:
+ owners: [team-mapped-no-slack]
+ unowned_by_design: false
+ status: active
+ source: team-mapped-no-slack/owners.yaml
+ slack: '#team-mapped-no-slack'
+
+ - name: a notifications mapping that names the producer gives its channel
+ files:
+ owners.yaml: |
+ version: 1
+ owners: []
+ teams:
+ team-split:
+ slack: '#split-people'
+ notifications: '#split-bots'
+ team-people:
+ slack: '#people-only'
+ team-bots-only:
+ notifications: '#bots-only'
+ team-quiet-bots:
+ slack: '#quiet-people'
+ notifications: false
+ team-silent:
+ slack: false
+ team-empty: {}
+ team-mapped:
+ slack: '#mapped-people'
+ notifications:
+ review-bot: '#mapped-reviews'
+ deploy-bot: false
+ team-mapped-no-slack:
+ notifications:
+ review-bot: '#mapped-no-slack-reviews'
+ team-mapped/owners.yaml: |
+ version: 1
+ owners: team-mapped
+ team-mapped-no-slack/owners.yaml: |
+ version: 1
+ owners: team-mapped-no-slack
+ team-split/owners.yaml: |
+ version: 1
+ owners: team-split
+ team-people/owners.yaml: |
+ version: 1
+ owners: team-people
+ team-quiet-bots/owners.yaml: |
+ version: 1
+ owners: team-quiet-bots
+ team-unregistered/owners.yaml: |
+ version: 1
+ owners: team-unregistered
+ purpose: notifications
+ producer: review-bot
+ expect:
+ team-mapped/x.py:
+ owners: [team-mapped]
+ unowned_by_design: false
+ status: active
+ source: team-mapped/owners.yaml
+ slack: '#mapped-reviews'
+ team-mapped-no-slack/x.py:
+ owners: [team-mapped-no-slack]
+ unowned_by_design: false
+ status: active
+ source: team-mapped-no-slack/owners.yaml
+ slack: '#mapped-no-slack-reviews'
+ team-split/x.py:
+ owners: [team-split]
+ unowned_by_design: false
+ status: active
+ source: team-split/owners.yaml
+ slack: '#split-bots'
+ team-people/x.py:
+ owners: [team-people]
+ unowned_by_design: false
+ status: active
+ source: team-people/owners.yaml
+ slack: '#people-only'
+ team-quiet-bots/x.py:
+ owners: [team-quiet-bots]
+ unowned_by_design: false
+ status: active
+ source: team-quiet-bots/owners.yaml
+ slack: null
+ team-unregistered/x.py:
+ owners: [team-unregistered]
+ unowned_by_design: false
+ status: active
+ source: team-unregistered/owners.yaml
+ slack: '#team-unregistered'
+
+ - name: a notifications mapping that maps the producer to false gives no channel
+ files:
+ owners.yaml: |
+ version: 1
+ owners: []
+ teams:
+ team-split:
+ slack: '#split-people'
+ notifications: '#split-bots'
+ team-people:
+ slack: '#people-only'
+ team-bots-only:
+ notifications: '#bots-only'
+ team-quiet-bots:
+ slack: '#quiet-people'
+ notifications: false
+ team-silent:
+ slack: false
+ team-empty: {}
+ team-mapped:
+ slack: '#mapped-people'
+ notifications:
+ review-bot: '#mapped-reviews'
+ deploy-bot: false
+ team-mapped-no-slack:
+ notifications:
+ review-bot: '#mapped-no-slack-reviews'
+ team-mapped/owners.yaml: |
+ version: 1
+ owners: team-mapped
+ team-mapped-no-slack/owners.yaml: |
+ version: 1
+ owners: team-mapped-no-slack
+ purpose: notifications
+ producer: deploy-bot
+ expect:
+ team-mapped/x.py:
+ owners: [team-mapped]
+ unowned_by_design: false
+ status: active
+ source: team-mapped/owners.yaml
+ slack: null
+ team-mapped-no-slack/x.py:
+ owners: [team-mapped-no-slack]
+ unowned_by_design: false
+ status: active
+ source: team-mapped-no-slack/owners.yaml
+ slack: '#team-mapped-no-slack'
+
+ - name: a notifications mapping that does not name the producer moves on to slack
+ files:
+ owners.yaml: |
+ version: 1
+ owners: []
+ teams:
+ team-split:
+ slack: '#split-people'
+ notifications: '#split-bots'
+ team-people:
+ slack: '#people-only'
+ team-bots-only:
+ notifications: '#bots-only'
+ team-quiet-bots:
+ slack: '#quiet-people'
+ notifications: false
+ team-silent:
+ slack: false
+ team-empty: {}
+ team-mapped:
+ slack: '#mapped-people'
+ notifications:
+ review-bot: '#mapped-reviews'
+ deploy-bot: false
+ team-mapped-no-slack:
+ notifications:
+ review-bot: '#mapped-no-slack-reviews'
+ team-mapped/owners.yaml: |
+ version: 1
+ owners: team-mapped
+ team-mapped-no-slack/owners.yaml: |
+ version: 1
+ owners: team-mapped-no-slack
+ purpose: notifications
+ producer: other-bot
+ expect:
+ team-mapped/x.py:
+ owners: [team-mapped]
+ unowned_by_design: false
+ status: active
+ source: team-mapped/owners.yaml
+ slack: '#mapped-people'
+ team-mapped-no-slack/x.py:
+ owners: [team-mapped-no-slack]
+ unowned_by_design: false
+ status: active
+ source: team-mapped-no-slack/owners.yaml
+ slack: '#team-mapped-no-slack'
+
+ - name: the slack purpose ignores the producer
+ files:
+ owners.yaml: |
+ version: 1
+ owners: []
+ teams:
+ team-split:
+ slack: '#split-people'
+ notifications: '#split-bots'
+ team-people:
+ slack: '#people-only'
+ team-bots-only:
+ notifications: '#bots-only'
+ team-quiet-bots:
+ slack: '#quiet-people'
+ notifications: false
+ team-silent:
+ slack: false
+ team-empty: {}
+ team-mapped:
+ slack: '#mapped-people'
+ notifications:
+ review-bot: '#mapped-reviews'
+ deploy-bot: false
+ team-mapped-no-slack:
+ notifications:
+ review-bot: '#mapped-no-slack-reviews'
+ team-mapped/owners.yaml: |
+ version: 1
+ owners: team-mapped
+ team-mapped-no-slack/owners.yaml: |
+ version: 1
+ owners: team-mapped-no-slack
+ purpose: slack
+ producer: review-bot
+ expect:
+ team-mapped/x.py:
+ owners: [team-mapped]
+ unowned_by_design: false
+ status: active
+ source: team-mapped/owners.yaml
+ slack: '#mapped-people'
+ team-mapped-no-slack/x.py:
+ owners: [team-mapped-no-slack]
+ unowned_by_design: false
+ status: active
+ source: team-mapped-no-slack/owners.yaml
+ slack: '#team-mapped-no-slack'
+
+ - name: a path without a team channel registry gets a derived channel
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ expect:
+ x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a person handle as primary owner gives no channel
+ files:
+ owners.yaml: |
+ version: 1
+ owners: []
+ teams:
+ team-a:
+ slack: '#a-people'
+ indiv/owners.yaml: |
+ version: 1
+ owners: ['@alice', team-a]
+ team-first/owners.yaml: |
+ version: 1
+ owners: [team-a, '@alice']
+ expect:
+ indiv/x.py:
+ owners: ['@alice', team-a]
+ unowned_by_design: false
+ status: active
+ source: indiv/owners.yaml
+ slack: null
+ team-first/x.py:
+ owners: [team-a, '@alice']
+ unowned_by_design: false
+ status: active
+ source: team-first/owners.yaml
+ slack: '#a-people'
+
+ - name: a teams registry outside the root file has no effect
+ files:
+ owners.yaml: |
+ version: 1
+ owners: []
+ sub/owners.yaml: |
+ version: 1
+ owners: team-a
+ teams:
+ team-a:
+ slack: '#a-people'
+ expect:
+ sub/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: sub/owners.yaml
+ slack: '#team-a'
+
+ - name: a notifications mapping that names an undeclared producer silences notifications
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ producers: [review-bot]
+ teams:
+ team-a:
+ slack: '#a-people'
+ notifications:
+ review-bott: '#a-reviews'
+ purpose: notifications
+ producer: review-bot
+ expect:
+ x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: null
+
+ - name: a notifications mapping with one undeclared producer silences the declared ones too
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ producers: [review-bot]
+ teams:
+ team-a:
+ slack: '#a-people'
+ notifications:
+ review-bot: '#a-reviews'
+ review-bott: '#a-typo'
+ purpose: notifications
+ producer: review-bot
+ expect:
+ x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: null
diff --git a/packages/owners-yaml/conformance/cases/inherit.yaml b/packages/owners-yaml/conformance/cases/inherit.yaml
new file mode 100644
index 000000000000..79408b7956ec
--- /dev/null
+++ b/packages/owners-yaml/conformance/cases/inherit.yaml
@@ -0,0 +1,177 @@
+cases:
+ - name: inherit false discards the owners of ancestor files
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ island/owners.yaml: |
+ version: 1
+ owners: []
+ inherit: false
+ expect:
+ island/x.py:
+ owners: []
+ unowned_by_design: false
+ status: active
+ source: null
+ slack: null
+
+ - name: inherit false discards the status of ancestor files
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ status: deprecated
+ island/owners.yaml: |
+ version: 1
+ owners: team-b
+ inherit: false
+ expect:
+ island/x.py:
+ owners: [team-b]
+ unowned_by_design: false
+ status: active
+ source: island/owners.yaml
+ slack: '#team-b'
+
+ - name: inherit false discards an ancestor's owners null
+ files:
+ owners.yaml: |
+ version: 1
+ owners: null
+ island/owners.yaml: |
+ version: 1
+ owners: []
+ inherit: false
+ expect:
+ island/x.py:
+ owners: []
+ unowned_by_design: false
+ status: active
+ source: null
+ slack: null
+
+ - name: files below a cut still fall through to the file that cut
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ status: deprecated
+ island/owners.yaml: |
+ version: 1
+ owners: team-a
+ inherit: false
+ island/sub/owners.yaml: |
+ version: 1
+ owners: []
+ status: generated
+ expect:
+ island/sub/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: generated
+ source: island/owners.yaml
+ slack: '#team-a'
+ island/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: island/owners.yaml
+ slack: '#team-a'
+
+ - name: inherit true is the same as no inherit field
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ status: deprecated
+ sub/owners.yaml: |
+ version: 1
+ owners: []
+ inherit: true
+ expect:
+ sub/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: deprecated
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a rule with inherit false cuts ancestors only for the paths it matches
+ files:
+ a/owners.yaml: |
+ version: 1
+ owners: team-a
+ status: deprecated
+ a/b/owners.yaml: |
+ version: 1
+ owners: []
+ rules:
+ - match: '/cut/'
+ owners: team-b
+ inherit: false
+ expect:
+ a/b/cut/x.py:
+ owners: [team-b]
+ unowned_by_design: false
+ status: active
+ source: a/b/owners.yaml
+ slack: '#team-b'
+ a/b/other.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: deprecated
+ source: a/owners.yaml
+ slack: '#team-a'
+
+ - name: a rule with inherit true restores ancestors under a file-level cut
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ status: deprecated
+ a/owners.yaml: |
+ version: 1
+ owners: []
+ inherit: false
+ rules:
+ - match: '/keep/'
+ inherit: true
+ expect:
+ a/x.py:
+ owners: []
+ unowned_by_design: false
+ status: active
+ source: null
+ slack: null
+ a/keep/x.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: deprecated
+ source: owners.yaml
+ slack: '#team-root'
+
+ - name: a rule with inherit false and no owners leaves its paths unowned
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ a/owners.yaml: |
+ version: 1
+ owners: []
+ rules:
+ - match: '*.lock'
+ inherit: false
+ expect:
+ a/deps/yarn.lock:
+ owners: []
+ unowned_by_design: false
+ status: active
+ source: null
+ slack: null
+ a/x.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
diff --git a/packages/owners-yaml/conformance/cases/invalid-files.yaml b/packages/owners-yaml/conformance/cases/invalid-files.yaml
new file mode 100644
index 000000000000..10d05cc04f16
--- /dev/null
+++ b/packages/owners-yaml/conformance/cases/invalid-files.yaml
@@ -0,0 +1,257 @@
+# In every case the file under sub/ is invalid, so sub/x.py resolves as if that file did not exist.
+cases:
+ - name: a file without version counts as absent
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ sub/owners.yaml: |
+ owners: team-b
+ status: deprecated
+ expect:
+ sub/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a file with a version other than 1 counts as absent
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ sub/owners.yaml: |
+ version: 2
+ owners: team-b
+ expect:
+ sub/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a file with version as a string counts as absent
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ sub/owners.yaml: |
+ version: '1'
+ owners: team-b
+ expect:
+ sub/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a file with version true counts as absent
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ sub/owners.yaml: |
+ version: true
+ owners: team-b
+ expect:
+ sub/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a file with version 1.0 counts as absent
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ sub/owners.yaml: |
+ version: 1.0
+ owners: team-b
+ expect:
+ sub/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a file without owners counts as absent and its status has no effect
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ sub/owners.yaml: |
+ version: 1
+ status: deprecated
+ inherit: false
+ expect:
+ sub/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a file that is a YAML list counts as absent
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ sub/owners.yaml: |
+ - version: 1
+ - owners: team-b
+ expect:
+ sub/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a file that is a YAML scalar counts as absent
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ sub/owners.yaml: |
+ team-b
+ expect:
+ sub/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: an empty file counts as absent
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ sub/owners.yaml: ''
+ expect:
+ sub/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a file that is not valid YAML counts as absent
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ sub/owners.yaml: |
+ version: 1
+ owners: [team-b
+ expect:
+ sub/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: an invalid root file counts as absent
+ files:
+ owners.yaml: |
+ owners: team-a
+ sub/owners.yaml: |
+ version: 1
+ owners: []
+ expect:
+ sub/x.py:
+ owners: []
+ unowned_by_design: false
+ status: active
+ source: null
+ slack: null
+
+ - name: a file with an unknown top-level field still applies
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ sub/owners.yaml: |
+ version: 1
+ owners: team-b
+ reviewers: team-c
+ expect:
+ sub/x.py:
+ owners: [team-b]
+ unowned_by_design: false
+ status: active
+ source: sub/owners.yaml
+ slack: '#team-b'
+
+ - name: a rule with a rejected pattern is ignored and the rest of the file applies
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ status: deprecated
+ rules:
+ - match: 'a***b'
+ owners: team-bad
+ - match: ''
+ owners: team-bad
+ - match: '*.md'
+ owners: team-docs
+ expect:
+ aXb:
+ owners: [team-a]
+ unowned_by_design: false
+ status: deprecated
+ source: owners.yaml
+ slack: '#team-a'
+ 'a***b':
+ owners: [team-a]
+ unowned_by_design: false
+ status: deprecated
+ source: owners.yaml
+ slack: '#team-a'
+ README.md:
+ owners: [team-docs]
+ unowned_by_design: false
+ status: deprecated
+ source: owners.yaml
+ slack: '#team-docs'
+
+ - name: a rule with one rejected pattern in its list is ignored for all its patterns
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ rules:
+ - match: ['*.md', 'a***b']
+ owners: team-docs
+ expect:
+ README.md:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: an owners value of the wrong type sets no owners and the other fields still apply
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ sub/owners.yaml: |
+ version: 1
+ owners: 5
+ status: generated
+ expect:
+ sub/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: generated
+ source: owners.yaml
+ slack: '#team-a'
diff --git a/packages/owners-yaml/conformance/cases/nearest-file.yaml b/packages/owners-yaml/conformance/cases/nearest-file.yaml
new file mode 100644
index 000000000000..63e53d0a5c63
--- /dev/null
+++ b/packages/owners-yaml/conformance/cases/nearest-file.yaml
@@ -0,0 +1,206 @@
+cases:
+ - name: a single root file owns every path
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ expect:
+ x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+ deep/a/b.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a nearer file replaces the owners of an ancestor
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ billing/owners.yaml: |
+ version: 1
+ owners: team-b
+ expect:
+ billing/x.py:
+ owners: [team-b]
+ unowned_by_design: false
+ status: active
+ source: billing/owners.yaml
+ slack: '#team-b'
+ billing/deep/y.py:
+ owners: [team-b]
+ unowned_by_design: false
+ status: active
+ source: billing/owners.yaml
+ slack: '#team-b'
+ other/z.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a child file that sets only owners keeps the parent's status
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ status: deprecated
+ billing/owners.yaml: |
+ version: 1
+ owners: team-b
+ expect:
+ billing/x.py:
+ owners: [team-b]
+ unowned_by_design: false
+ status: deprecated
+ source: billing/owners.yaml
+ slack: '#team-b'
+
+ - name: a child file with an empty owners list keeps the parent's owners
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ billing/owners.yaml: |
+ version: 1
+ owners: []
+ status: generated
+ expect:
+ billing/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: generated
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a path with no ownership file on its walk is unowned
+ files:
+ billing/owners.yaml: |
+ version: 1
+ owners: team-b
+ expect:
+ other/x.py:
+ owners: []
+ unowned_by_design: false
+ status: active
+ source: null
+ slack: null
+ README.md:
+ owners: []
+ unowned_by_design: false
+ status: active
+ source: null
+ slack: null
+
+ - name: a root file with an empty owners list leaves paths unowned
+ files:
+ owners.yaml: |
+ version: 1
+ owners: []
+ expect:
+ x.py:
+ owners: []
+ unowned_by_design: false
+ status: active
+ source: null
+ slack: null
+
+ - name: a file applies only to its own directory and the directories below it
+ files:
+ billing/owners.yaml: |
+ version: 1
+ owners: team-b
+ expect:
+ billing-extra/x.py:
+ owners: []
+ unowned_by_design: false
+ status: active
+ source: null
+ slack: null
+ billing.py:
+ owners: []
+ unowned_by_design: false
+ status: active
+ source: null
+ slack: null
+ billing/owners.yaml:
+ owners: [team-b]
+ unowned_by_design: false
+ status: active
+ source: billing/owners.yaml
+ slack: '#team-b'
+
+ - name: owners null marks paths as unowned by design
+ files:
+ owners.yaml: |
+ version: 1
+ owners: null
+ expect:
+ x.py:
+ owners: []
+ unowned_by_design: true
+ status: active
+ source: owners.yaml
+ slack: null
+
+ - name: a deeper file with owners replaces an ancestor's owners null
+ files:
+ owners.yaml: |
+ version: 1
+ owners: null
+ sub/owners.yaml: |
+ version: 1
+ owners: team-a
+ expect:
+ sub/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: sub/owners.yaml
+ slack: '#team-a'
+ x.py:
+ owners: []
+ unowned_by_design: true
+ status: active
+ source: owners.yaml
+ slack: null
+
+ - name: a deeper file with owners null replaces an owned ancestor
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ vendor/owners.yaml: |
+ version: 1
+ owners: null
+ expect:
+ vendor/lib.py:
+ owners: []
+ unowned_by_design: true
+ status: active
+ source: vendor/owners.yaml
+ slack: null
+
+ - name: an empty owners list below owners null keeps the path unowned by design
+ files:
+ owners.yaml: |
+ version: 1
+ owners: null
+ sub/owners.yaml: |
+ version: 1
+ owners: []
+ status: deprecated
+ expect:
+ sub/x.py:
+ owners: []
+ unowned_by_design: true
+ status: deprecated
+ source: owners.yaml
+ slack: null
diff --git a/packages/owners-yaml/conformance/cases/owners-values.yaml b/packages/owners-yaml/conformance/cases/owners-values.yaml
new file mode 100644
index 000000000000..27207ed02a3b
--- /dev/null
+++ b/packages/owners-yaml/conformance/cases/owners-values.yaml
@@ -0,0 +1,55 @@
+cases:
+ - name: a string owner is a list with one entry
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ expect:
+ x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a list of owners keeps its order and the first entry is the primary owner
+ files:
+ owners.yaml: |
+ version: 1
+ owners: [team-b, team-a, '@alice']
+ expect:
+ x.py:
+ owners: [team-b, team-a, '@alice']
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-b'
+
+ - name: a nearer owners list replaces the ancestor list and does not merge with it
+ files:
+ owners.yaml: |
+ version: 1
+ owners: [team-a, team-b]
+ sub/owners.yaml: |
+ version: 1
+ owners: [team-c]
+ expect:
+ sub/x.py:
+ owners: [team-c]
+ unowned_by_design: false
+ status: active
+ source: sub/owners.yaml
+ slack: '#team-c'
+
+ - name: a person handle is a valid owner
+ files:
+ owners.yaml: |
+ version: 1
+ owners: '@alice'
+ expect:
+ x.py:
+ owners: ['@alice']
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: null
diff --git a/packages/owners-yaml/conformance/cases/owners-yaml-extensions.yaml b/packages/owners-yaml/conformance/cases/owners-yaml-extensions.yaml
new file mode 100644
index 000000000000..d85340d436b2
--- /dev/null
+++ b/packages/owners-yaml/conformance/cases/owners-yaml-extensions.yaml
@@ -0,0 +1,63 @@
+# These cases cover owners-yaml behavior that is not part of the format (SPEC section 8).
+cases:
+ - name: the team-CHANGEME placeholder is removed from an owners.yaml list
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ only/owners.yaml: |
+ version: 1
+ owners: team-CHANGEME
+ mixed/owners.yaml: |
+ version: 1
+ owners: [team-CHANGEME, team-b]
+ expect:
+ only/x.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+ mixed/x.py:
+ owners: [team-b]
+ unowned_by_design: false
+ status: active
+ source: mixed/owners.yaml
+ slack: '#team-b'
+
+ - name: a rule with only the placeholder falls through to ancestor files
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ a/owners.yaml: |
+ version: 1
+ owners: team-a
+ rules:
+ - match: new.py
+ owners: team-CHANGEME
+ expect:
+ a/new.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+
+ - name: a product.yaml with only the placeholder falls through
+ files:
+ owners.yaml: |
+ version: 1
+ owners: null
+ alias_files: [product.yaml]
+ products/bar/product.yaml: |
+ name: Bar
+ owners:
+ - team-CHANGEME
+ expect:
+ products/bar/thing.py:
+ owners: []
+ unowned_by_design: true
+ status: active
+ source: owners.yaml
+ slack: null
diff --git a/packages/owners-yaml/conformance/cases/path-normalization.yaml b/packages/owners-yaml/conformance/cases/path-normalization.yaml
new file mode 100644
index 000000000000..579294ebe51f
--- /dev/null
+++ b/packages/owners-yaml/conformance/cases/path-normalization.yaml
@@ -0,0 +1,55 @@
+cases:
+ - name: a path is normalized before resolution
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ billing/owners.yaml: |
+ version: 1
+ owners: team-b
+ rules:
+ - match: '/api/'
+ owners: team-api
+ expect:
+ ./billing/x.py:
+ owners: [team-b]
+ unowned_by_design: false
+ status: active
+ source: billing/owners.yaml
+ slack: '#team-b'
+ /billing/x.py:
+ owners: [team-b]
+ unowned_by_design: false
+ status: active
+ source: billing/owners.yaml
+ slack: '#team-b'
+ //billing/x.py:
+ owners: [team-b]
+ unowned_by_design: false
+ status: active
+ source: billing/owners.yaml
+ slack: '#team-b'
+ 'billing\x.py':
+ owners: [team-b]
+ unowned_by_design: false
+ status: active
+ source: billing/owners.yaml
+ slack: '#team-b'
+ '.\billing\x.py':
+ owners: [team-b]
+ unowned_by_design: false
+ status: active
+ source: billing/owners.yaml
+ slack: '#team-b'
+ 'billing\api\views.py':
+ owners: [team-api]
+ unowned_by_design: false
+ status: active
+ source: billing/owners.yaml
+ slack: '#team-api'
+ ./x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
diff --git a/packages/owners-yaml/conformance/cases/patterns.yaml b/packages/owners-yaml/conformance/cases/patterns.yaml
new file mode 100644
index 000000000000..43e2d1ada61c
--- /dev/null
+++ b/packages/owners-yaml/conformance/cases/patterns.yaml
@@ -0,0 +1,593 @@
+# Each case has one rule. A path the pattern matches resolves to team-rule, any other path to team-file.
+cases:
+ - name: a leading slash anchors the pattern to the directory of the file
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ a/owners.yaml: |
+ version: 1
+ owners: []
+ rules:
+ - match: '/docs'
+ owners: team-rule
+ expect:
+ 'a/docs/x.md':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: a/owners.yaml
+ slack: '#team-rule'
+ 'a/docs':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: a/owners.yaml
+ slack: '#team-rule'
+ 'a/b/docs/x.md':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: a pattern with a slash in the middle is anchored
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: 'foo/bar'
+ owners: team-rule
+ expect:
+ 'foo/bar':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'foo/bar/baz.py':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'x/foo/bar':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: a pattern with no slash matches at any depth
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: 'foo'
+ owners: team-rule
+ expect:
+ 'foo':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'a/b/foo':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'a/b/foo/c':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'a/foobar':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: a slash-free wildcard pattern matches at any depth
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: '*.js'
+ owners: team-rule
+ expect:
+ 'c.js':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'a/b/c.js':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'a/b/c.ts':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: a slash-free wildcard pattern can match inside a name
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: 'docker-compose*.yml'
+ owners: team-rule
+ expect:
+ 'a/b/docker-compose.dev.yml':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'a/b/compose.yml':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: a trailing slash matches everything below a directory of that name at any depth
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: 'docs/'
+ owners: team-rule
+ expect:
+ 'docs/x':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'docs/x/y':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'a/docs/y':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'docsx/y':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: a literal last segment also owns the subtree below it
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: '/foo/bar'
+ owners: team-rule
+ expect:
+ 'foo/bar/baz.py':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'foo/bar/deep/baz.py':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'foo/barbaz.py':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: a single star does not cross a slash
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: '/docs/*'
+ owners: team-rule
+ expect:
+ 'docs/x.md':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'docs/a/b.md':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: a single star as the last segment does not own a subtree
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: 'src/*'
+ owners: team-rule
+ expect:
+ 'src/a.py':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'src/a/b.py':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: a double star matches zero or more directories
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: 'a/**/b'
+ owners: team-rule
+ expect:
+ 'a/b':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'a/x/y/b':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'a/b/c':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'a/xb':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: a leading double star matches at any depth including the top
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: '**/foo'
+ owners: team-rule
+ expect:
+ 'foo':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'a/foo':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'a/b/foo':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+
+ - name: a trailing double star matches everything below the directory
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: 'gen/**'
+ owners: team-rule
+ expect:
+ 'gen/x':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'gen/a/b':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'other/gen/x':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: a lone double star matches every path
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: '**'
+ owners: team-rule
+ expect:
+ 'x.py':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'anything/x':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+
+ - name: a question mark matches exactly one character except a slash
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: 'file?.txt'
+ owners: team-rule
+ expect:
+ 'file1.txt':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'a/fileX.txt':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'file12.txt':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+ 'file.txt':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: a backslash escapes the next character
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: '\*.txt'
+ owners: team-rule
+ expect:
+ '*.txt':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'a/*.txt':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'a.txt':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: patterns are relative to the directory of the file
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ web/owners.yaml: |
+ version: 1
+ owners: []
+ rules:
+ - match: '/src/*.ts'
+ owners: team-rule
+ expect:
+ 'web/src/a.ts':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: web/owners.yaml
+ slack: '#team-rule'
+ 'src/a.ts':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+ 'web/lib/src/a.ts':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: a character class matches one character from the set
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: '/docs/[ab].md'
+ owners: team-rule
+ expect:
+ 'docs/a.md':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'docs/b.md':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'docs/c.md':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: a character class matches one character from a range
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: '/docs/[a-c]*.py'
+ owners: team-rule
+ expect:
+ 'docs/bar.py':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'docs/zar.py':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: an exclamation mark at the start of a character class negates it
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: '/docs/[!ab]?.md'
+ owners: team-rule
+ expect:
+ 'docs/cx.md':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'docs/ax.md':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: a closing bracket in the first position is a member of the character class
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: '/docs/[]a].md'
+ owners: team-rule
+ expect:
+ 'docs/].md':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'docs/a.md':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'docs/b.md':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: a character class does not match a slash
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: '/a[/]b'
+ owners: team-rule
+ expect:
+ 'a/b':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
+
+ - name: an unclosed bracket is a literal bracket
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-file
+ rules:
+ - match: '/docs/[ab.md'
+ owners: team-rule
+ expect:
+ 'docs/[ab.md':
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-rule'
+ 'docs/a.md':
+ owners: [team-file]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-file'
diff --git a/packages/owners-yaml/conformance/cases/rules.yaml b/packages/owners-yaml/conformance/cases/rules.yaml
new file mode 100644
index 000000000000..274a3ee83fc5
--- /dev/null
+++ b/packages/owners-yaml/conformance/cases/rules.yaml
@@ -0,0 +1,247 @@
+cases:
+ - name: a rule replaces the file owners only for the paths it matches
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ rules:
+ - match: Dockerfile
+ owners: team-infra
+ expect:
+ Dockerfile:
+ owners: [team-infra]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-infra'
+ main.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a rule that sets only status keeps the file owners
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ rules:
+ - match: 'generated/**'
+ status: generated
+ expect:
+ generated/api.ts:
+ owners: [team-a]
+ unowned_by_design: false
+ status: generated
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a rule with owners null marks its paths as unowned by design
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ a/owners.yaml: |
+ version: 1
+ owners: team-a
+ rules:
+ - match: '/vendor/**'
+ owners: null
+ expect:
+ a/vendor/lib.py:
+ owners: []
+ unowned_by_design: true
+ status: active
+ source: a/owners.yaml
+ slack: null
+ a/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: a/owners.yaml
+ slack: '#team-a'
+
+ - name: a rule with an empty owners list falls through to ancestor files
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ a/owners.yaml: |
+ version: 1
+ owners: team-a
+ rules:
+ - match: '/shared/'
+ owners: []
+ expect:
+ a/shared/x.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+
+ - name: the last matching rule in a file wins
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ rules:
+ - match: '*.yml'
+ owners: team-yaml
+ - match: 'docker-compose*.yml'
+ owners: team-infra
+ expect:
+ docker-compose.dev.yml:
+ owners: [team-infra]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-infra'
+ other.yml:
+ owners: [team-yaml]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-yaml'
+ main.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: an earlier matching rule has no effect even for fields the last rule does not set
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ rules:
+ - match: '*.py'
+ status: generated
+ - match: 'special.py'
+ owners: team-b
+ expect:
+ special.py:
+ owners: [team-b]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-b'
+ other.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: generated
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a rule with a list of patterns acts as one rule per pattern in list order
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ rules:
+ - match: '*.yml'
+ owners: team-yaml
+ - match: [Dockerfile, 'docker-compose*.yml']
+ owners: team-infra
+ status: generated
+ expect:
+ Dockerfile:
+ owners: [team-infra]
+ unowned_by_design: false
+ status: generated
+ source: owners.yaml
+ slack: '#team-infra'
+ docker-compose.dev.yml:
+ owners: [team-infra]
+ unowned_by_design: false
+ status: generated
+ source: owners.yaml
+ slack: '#team-infra'
+ other.yml:
+ owners: [team-yaml]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-yaml'
+
+ - name: a rule does not change paths outside the directory of its file
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ a/owners.yaml: |
+ version: 1
+ owners: team-a
+ rules:
+ - match: '**'
+ owners: team-rule
+ expect:
+ x.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+ b/x.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+ a/x.py:
+ owners: [team-rule]
+ unowned_by_design: false
+ status: active
+ source: a/owners.yaml
+ slack: '#team-rule'
+
+ - name: a nearer file with owners wins over a matching rule in an ancestor file
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ rules:
+ - match: '/a/'
+ owners: team-rule
+ status: deprecated
+ a/owners.yaml: |
+ version: 1
+ owners: team-a
+ b/owners.yaml: |
+ version: 1
+ owners: []
+ expect:
+ a/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: deprecated
+ source: a/owners.yaml
+ slack: '#team-a'
+ b/x.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+
+ - name: a matching rule in an ancestor file applies below a nearer file with no owners
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ rules:
+ - match: '/a/'
+ owners: team-rule
+ a/owners.yaml: |
+ version: 1
+ owners: []
+ status: generated
+ expect:
+ a/x.py:
+ owners: [team-rule]
+ unowned_by_design: false
+ status: generated
+ source: owners.yaml
+ slack: '#team-rule'
diff --git a/packages/owners-yaml/conformance/cases/spec-example.yaml b/packages/owners-yaml/conformance/cases/spec-example.yaml
new file mode 100644
index 000000000000..7bb1f01bb2a2
--- /dev/null
+++ b/packages/owners-yaml/conformance/cases/spec-example.yaml
@@ -0,0 +1,80 @@
+# The worked example in SPEC section 9.
+cases:
+ - name: the worked example resolves as the specification states for people
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-platform
+ status: active
+ teams:
+ team-billing:
+ notifications: '#billing-bots'
+ billing/owners.yaml: |
+ version: 1
+ owners: [team-billing, '@alice']
+ status: deprecated
+ rules:
+ - match: 'api/'
+ status: active
+ - match: 'vendor/'
+ owners: null
+ billing/legacy/owners.yaml: |
+ version: 1
+ owners: []
+ inherit: false
+ expect:
+ billing/api/invoices.py:
+ owners: [team-billing, '@alice']
+ unowned_by_design: false
+ status: active
+ source: billing/owners.yaml
+ slack: '#team-billing'
+ billing/jobs/run.py:
+ owners: [team-billing, '@alice']
+ unowned_by_design: false
+ status: deprecated
+ source: billing/owners.yaml
+ slack: '#team-billing'
+ billing/vendor/lib.py:
+ owners: []
+ unowned_by_design: true
+ status: deprecated
+ source: billing/owners.yaml
+ slack: null
+ billing/legacy/old.py:
+ owners: []
+ unowned_by_design: false
+ status: active
+ source: null
+ slack: null
+
+ - name: the worked example resolves as the specification states for notifications
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-platform
+ status: active
+ teams:
+ team-billing:
+ notifications: '#billing-bots'
+ billing/owners.yaml: |
+ version: 1
+ owners: [team-billing, '@alice']
+ status: deprecated
+ rules:
+ - match: 'api/'
+ status: active
+ - match: 'vendor/'
+ owners: null
+ billing/legacy/owners.yaml: |
+ version: 1
+ owners: []
+ inherit: false
+ purpose: notifications
+ expect:
+ billing/api/invoices.py:
+ owners: [team-billing, '@alice']
+ unowned_by_design: false
+ status: active
+ source: billing/owners.yaml
+ slack: '#billing-bots'
diff --git a/packages/owners-yaml/conformance/cases/status.yaml b/packages/owners-yaml/conformance/cases/status.yaml
new file mode 100644
index 000000000000..971100e4db99
--- /dev/null
+++ b/packages/owners-yaml/conformance/cases/status.yaml
@@ -0,0 +1,118 @@
+cases:
+ - name: status is active when no file sets it
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ sub/owners.yaml: |
+ version: 1
+ owners: team-b
+ expect:
+ sub/x.py:
+ owners: [team-b]
+ unowned_by_design: false
+ status: active
+ source: sub/owners.yaml
+ slack: '#team-b'
+
+ - name: each status value passes through to the resolution
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ old/owners.yaml: |
+ version: 1
+ owners: []
+ status: deprecated
+ gen/owners.yaml: |
+ version: 1
+ owners: []
+ status: generated
+ third_party/owners.yaml: |
+ version: 1
+ owners: []
+ status: vendored
+ live/owners.yaml: |
+ version: 1
+ owners: []
+ status: active
+ expect:
+ old/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: deprecated
+ source: owners.yaml
+ slack: '#team-a'
+ gen/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: generated
+ source: owners.yaml
+ slack: '#team-a'
+ third_party/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: vendored
+ source: owners.yaml
+ slack: '#team-a'
+ live/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a nearer status replaces the ancestor status
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ status: deprecated
+ sub/owners.yaml: |
+ version: 1
+ owners: []
+ status: active
+ expect:
+ sub/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-a'
+ x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: deprecated
+ source: owners.yaml
+ slack: '#team-a'
+
+ - name: a file with owners null can still set a status
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ vendor/owners.yaml: |
+ version: 1
+ owners: null
+ status: vendored
+ expect:
+ vendor/lib.py:
+ owners: []
+ unowned_by_design: true
+ status: vendored
+ source: vendor/owners.yaml
+ slack: null
+
+ - name: status applies to a path that has no owners
+ files:
+ owners.yaml: |
+ version: 1
+ owners: []
+ status: generated
+ expect:
+ x.py:
+ owners: []
+ unowned_by_design: false
+ status: generated
+ source: null
+ slack: null
diff --git a/packages/owners-yaml/owners.schema.json b/packages/owners-yaml/owners.schema.json
new file mode 100644
index 000000000000..bff034fa847f
--- /dev/null
+++ b/packages/owners-yaml/owners.schema.json
@@ -0,0 +1,120 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/owners.schema.json",
+ "title": "owners.yaml",
+ "description": "Code ownership for a directory, version 1. See SPEC.md. Keys under 'Repository settings' are valid only in the repository root file.",
+ "type": "object",
+ "required": ["version", "owners"],
+ "additionalProperties": false,
+ "properties": {
+ "version": { "const": 1, "description": "The format version." },
+ "owners": { "$ref": "#/$defs/owners" },
+ "status": { "$ref": "#/$defs/status" },
+ "inherit": {
+ "type": "boolean",
+ "description": "Whether fields fall through from ancestor files. Default true."
+ },
+ "rules": {
+ "type": "array",
+ "description": "Per-path overrides inside this directory. The last matching rule applies.",
+ "items": { "$ref": "#/$defs/rule" }
+ },
+ "teams": {
+ "type": "object",
+ "description": "Repository settings: team slug to its channels.",
+ "propertyNames": { "not": { "pattern": "^@" } },
+ "additionalProperties": { "$ref": "#/$defs/teamEntry" }
+ },
+ "github_org": {
+ "type": "string",
+ "minLength": 1,
+ "pattern": "^[^/]+$",
+ "description": "Repository settings: the GitHub organization of the team slugs."
+ },
+ "producers": {
+ "type": "array",
+ "items": { "type": "string", "minLength": 1 },
+ "description": "Repository settings: automation names a team can address in notifications."
+ },
+ "reserved_dirs": {
+ "type": "array",
+ "items": { "$ref": "#/$defs/pattern" },
+ "description": "Repository settings: patterns where owners.yaml must not be placed."
+ },
+ "alias_files": {
+ "type": "array",
+ "maxItems": 8,
+ "uniqueItems": true,
+ "items": { "type": "string", "minLength": 1, "not": { "pattern": "[/\\\\]|^\\.{1,2}$|^owners\\.yaml$" } },
+ "default": ["product.yaml"],
+ "description": "Repository settings: other bare file names that count as ownership files. Undeclared means [product.yaml]; a declared list replaces that default, and [] turns alias files off."
+ },
+ "codeowners": {
+ "type": "object",
+ "description": "Repository settings: how the owners-yaml CODEOWNERS export spells test paths.",
+ "additionalProperties": false,
+ "properties": {
+ "jest_root": { "type": "string", "minLength": 1 },
+ "jest_root_tests": { "$ref": "#/$defs/pattern" },
+ "jest_root_packages": { "type": "string", "minLength": 1 }
+ }
+ }
+ },
+ "$defs": {
+ "owners": {
+ "description": "Team slugs or @handles, primary owner first. null means unowned by design.",
+ "oneOf": [
+ { "type": "string", "minLength": 1 },
+ { "type": "array", "items": { "type": "string", "minLength": 1 } },
+ { "type": "null" }
+ ]
+ },
+ "status": {
+ "enum": ["active", "deprecated", "generated", "vendored"],
+ "description": "The lifecycle of the code. Default active."
+ },
+ "pattern": {
+ "type": "string",
+ "minLength": 1,
+ "not": { "pattern": "\\*\\*\\*" },
+ "description": "A GitHub CODEOWNERS pattern."
+ },
+ "rule": {
+ "type": "object",
+ "required": ["match"],
+ "additionalProperties": false,
+ "properties": {
+ "match": {
+ "oneOf": [
+ { "$ref": "#/$defs/pattern" },
+ { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/pattern" } }
+ ]
+ },
+ "owners": { "$ref": "#/$defs/owners" },
+ "status": { "$ref": "#/$defs/status" },
+ "inherit": { "type": "boolean" }
+ }
+ },
+ "channel": {
+ "description": "A Slack channel, or false for no channel.",
+ "oneOf": [{ "type": "string", "pattern": "^#" }, { "const": false }]
+ },
+ "teamEntry": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "slack": { "$ref": "#/$defs/channel" },
+ "notifications": {
+ "oneOf": [
+ { "$ref": "#/$defs/channel" },
+ {
+ "type": "object",
+ "minProperties": 1,
+ "additionalProperties": { "$ref": "#/$defs/channel" }
+ }
+ ]
+ }
+ }
+ }
+ }
+}
diff --git a/packages/owners-yaml/owners_yaml/__init__.py b/packages/owners-yaml/owners_yaml/__init__.py
new file mode 100644
index 000000000000..3baa08e1db7d
--- /dev/null
+++ b/packages/owners-yaml/owners_yaml/__init__.py
@@ -0,0 +1,49 @@
+"""Distributed ownership: owners.yaml matcher, schema, resolver, and CLI."""
+
+from .census import TeamTestCensus, census, first_team_owner, runner_for_path
+from .codeowners import CodeownersProjection, owner_handle, package_dirs_from, project, spellings
+from .github import GitHubLookupError, GitHubOrg
+from .matcher import compile_pattern, normalize_path, path_matches_pattern
+from .resolver import (
+ BatchOwnershipSource,
+ DiskSource,
+ OwnershipSource,
+ OwnersResolver,
+ Purpose,
+ RepoRootNotFound,
+ Resolution,
+ TeamChannel,
+ team_channel,
+ teams_registry,
+)
+from .schema import Producer, RepoSettings, TeamEntry
+
+__all__ = [
+ "BatchOwnershipSource",
+ "CodeownersProjection",
+ "DiskSource",
+ "GitHubLookupError",
+ "GitHubOrg",
+ "OwnersResolver",
+ "OwnershipSource",
+ "Producer",
+ "Purpose",
+ "RepoRootNotFound",
+ "RepoSettings",
+ "Resolution",
+ "TeamChannel",
+ "TeamEntry",
+ "TeamTestCensus",
+ "census",
+ "compile_pattern",
+ "first_team_owner",
+ "normalize_path",
+ "owner_handle",
+ "package_dirs_from",
+ "path_matches_pattern",
+ "project",
+ "runner_for_path",
+ "spellings",
+ "team_channel",
+ "teams_registry",
+]
diff --git a/tools/owners/posthog_owners/__main__.py b/packages/owners-yaml/owners_yaml/__main__.py
similarity index 67%
rename from tools/owners/posthog_owners/__main__.py
rename to packages/owners-yaml/owners_yaml/__main__.py
index 4103c245a53f..48e27416927c 100644
--- a/tools/owners/posthog_owners/__main__.py
+++ b/packages/owners-yaml/owners_yaml/__main__.py
@@ -10,17 +10,18 @@ JSON object keyed by normalized path to stdout::
``--codeowners FILE`` switches to the other mode: it ignores the path arguments and writes a
CODEOWNERS projection of every tracked test file's ownership to FILE (``-`` for stdout), for a
-consumer that reads CODEOWNERS and cannot read ``owners.yaml``.
+consumer that reads CODEOWNERS and cannot read ``owners.yaml``. The GitHub organization comes from
+``--org``, else from ``github_org`` in the root ``owners.yaml``.
``--repo-root`` names the directory holding the ownership files. Without it the
resolver locates the repo with ``git rev-parse``, which needs a real worktree; a
-consumer that fetched only the ``owners.yaml`` / ``product.yaml`` files into a
-scratch directory passes the flag instead.
+consumer that fetched only the ownership files into a scratch directory passes
+the flag instead.
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.
+``python -m owners_yaml`` after installing just pyyaml, with no project sync.
+The click CLI (``owners resolve --json``) emits the identical shape; both build it
+via ``resolution_to_wire`` so there is one format.
"""
from __future__ import annotations
@@ -31,13 +32,13 @@ import argparse
from pathlib import Path
from typing import cast
-from .codeowners import package_dirs_from, project
+from .codeowners import project_repo
from .matcher import normalize_path
-from .resolver import DEFAULT_PURPOSE, OwnersResolver, Purpose, read_stdin_paths, resolution_to_wire
+from .resolver import DEFAULT_PURPOSE, OwnersResolver, Purpose, RepoRootNotFound, read_stdin_paths, resolution_to_wire
def main() -> None:
- parser = argparse.ArgumentParser(prog="python -m posthog_owners")
+ parser = argparse.ArgumentParser(prog="python -m owners_yaml")
parser.add_argument("--purpose", choices=["slack", "notifications"], default=DEFAULT_PURPOSE)
parser.add_argument(
"--repo-root",
@@ -50,6 +51,11 @@ def main() -> None:
default=None,
help="Write a CODEOWNERS projection of test-file ownership to FILE ('-' for stdout) and exit",
)
+ parser.add_argument(
+ "--org",
+ default=None,
+ help="GitHub organization for --codeowners; default: github_org in the root owners.yaml",
+ )
parser.add_argument("paths", nargs="*")
ns = parser.parse_args()
# A root that is not a directory reads as a repo with no ownership files, so every path
@@ -58,11 +64,18 @@ def main() -> None:
if ns.repo_root is not None and not (ns.repo_root and Path(ns.repo_root).is_dir()):
parser.error(f"--repo-root {ns.repo_root!r} is not a directory")
repo_root = Path(ns.repo_root) if ns.repo_root is not None else None
- resolver = OwnersResolver(repo_root=repo_root, purpose=cast("Purpose", ns.purpose))
+ try:
+ resolver = OwnersResolver(repo_root=repo_root, purpose=cast("Purpose", ns.purpose))
+ except RepoRootNotFound as exc:
+ parser.error(str(exc))
if ns.codeowners:
- tracked = resolver.tracked_files()
- rendered = project(tracked, resolver, package_dirs_from(tracked)).render()
+ org = ns.org or resolver.settings().github_org
+ if not org:
+ parser.error(
+ "--codeowners needs a GitHub organization: set github_org in the root owners.yaml or pass --org"
+ )
+ rendered = project_repo(resolver, org).render()
if ns.codeowners == "-":
sys.stdout.write(rendered)
else:
diff --git a/tools/owners/posthog_owners/census.py b/packages/owners-yaml/owners_yaml/census.py
similarity index 100%
rename from tools/owners/posthog_owners/census.py
rename to packages/owners-yaml/owners_yaml/census.py
diff --git a/tools/owners/posthog_owners/cli.py b/packages/owners-yaml/owners_yaml/cli.py
similarity index 69%
rename from tools/owners/posthog_owners/cli.py
rename to packages/owners-yaml/owners_yaml/cli.py
index 58b78d40df2a..98432706fb67 100644
--- a/tools/owners/posthog_owners/cli.py
+++ b/packages/owners-yaml/owners_yaml/cli.py
@@ -1,10 +1,13 @@
-"""hogli owners:* commands — resolve, who, unowned, lint, fmt."""
+"""The ``owners`` CLI: resolve, who, census, codeowners, unowned, lint, fmt.
+
+Each command is a plain click command named ``owners:<name>``, so a host CLI can register it
+directly. The ``owners`` console script groups the same commands without the prefix.
+"""
from __future__ import annotations
import sys
import json
-import subprocess
from collections import defaultdict
from pathlib import Path
from typing import cast
@@ -12,10 +15,41 @@ from typing import cast
import click
from .census import census
-from .codeowners import package_dirs_from, project
+from .codeowners import project_repo
+from .github import GitHubLookupError, GitHubOrg
from .matcher import compile_pattern, normalize_path
-from .resolver import OWNERS_FILENAME, PRODUCT_FILENAME, OwnersResolver, Purpose, read_stdin_paths, resolution_to_wire
-from .schema import is_simple_owners_file, normalize_product_owners
+from .resolver import OWNERS_FILENAME, OwnersResolver, Purpose, RepoRootNotFound, read_stdin_paths, resolution_to_wire
+from .schema import RepoSettings, is_simple_owners_file, normalize_owners
+
+# GitHub Actions parses every YAML file under this directory as a workflow, in any repo.
+BUILTIN_RESERVED_DIRS = (".github/workflows/**",)
+
+repo_root_option = click.option(
+ "--repo-root",
+ type=click.Path(exists=True, file_okay=False, path_type=Path),
+ default=None,
+ help="Directory that holds the ownership files. Default: the enclosing git worktree.",
+)
+
+org_option = click.option(
+ "--org",
+ default=None,
+ help="GitHub organization of the team slugs. Default: `github_org` in the root owners.yaml.",
+)
+
+
+def _resolver(repo_root: Path | None, purpose: Purpose = "slack") -> OwnersResolver:
+ try:
+ return OwnersResolver(repo_root=repo_root, purpose=purpose)
+ except RepoRootNotFound as exc:
+ raise click.ClickException(str(exc)) from exc
+
+
+def _github_org(org: str | None, settings: RepoSettings) -> str:
+ resolved = org or settings.github_org
+ if not resolved:
+ raise click.ClickException("no GitHub organization: set `github_org` in the root owners.yaml or pass --org")
+ return resolved
def _read_paths(paths: tuple[str, ...]) -> list[str]:
@@ -35,9 +69,10 @@ def _read_paths(paths: tuple[str, ...]) -> list[str]:
default="slack",
help="Which team channel `slack` resolves to: where people are, or where automation posts",
)
+@repo_root_option
@click.argument("paths", nargs=-1)
-def cmd_resolve(as_json: bool, purpose: str, paths: tuple[str, ...]) -> None:
- resolver = OwnersResolver(purpose=cast(Purpose, purpose))
+def cmd_resolve(as_json: bool, purpose: str, repo_root: Path | None, paths: tuple[str, ...]) -> None:
+ resolver = _resolver(repo_root, cast(Purpose, purpose))
targets = _read_paths(paths)
result = {normalize_path(path): resolution_to_wire(resolver.resolve(path)) for path in targets}
if as_json:
@@ -49,9 +84,10 @@ def cmd_resolve(as_json: bool, purpose: str, paths: tuple[str, ...]) -> None:
@click.command(name="owners:who", help="Show who owns a single path")
+@repo_root_option
@click.argument("path")
-def cmd_who(path: str) -> None:
- r = OwnersResolver().resolve(path)
+def cmd_who(repo_root: Path | None, path: str) -> None:
+ r = _resolver(repo_root).resolve(path)
click.echo(f"path: {r.path}")
if r.owners:
click.echo(f"owners: {', '.join(r.owners)}")
@@ -66,9 +102,10 @@ def cmd_who(path: str) -> None:
@click.command(name="owners:census", help="Count test files per owning team")
@click.option("--json", "as_json", is_flag=True, help="Emit a JSON list of per-team counts")
+@repo_root_option
@click.argument("prefix", required=False)
-def cmd_census(as_json: bool, prefix: str | None) -> None:
- resolver = OwnersResolver()
+def cmd_census(as_json: bool, repo_root: Path | None, prefix: str | None) -> None:
+ resolver = _resolver(repo_root)
rows = census(resolver.tracked_files(prefix), resolver.repo_root)
if as_json:
click.echo(json.dumps([row.as_payload() for row in rows], indent=2))
@@ -87,10 +124,11 @@ def cmd_census(as_json: bool, prefix: str | None) -> None:
type=click.Path(dir_okay=False, writable=True),
help="Write to this file instead of stdout",
)
-def cmd_codeowners(output: str | None) -> None:
- resolver = OwnersResolver()
- tracked = resolver.tracked_files()
- projection = project(tracked, resolver, package_dirs_from(tracked))
+@org_option
+@repo_root_option
+def cmd_codeowners(output: str | None, org: str | None, repo_root: Path | None) -> None:
+ resolver = _resolver(repo_root)
+ projection = project_repo(resolver, _github_org(org, resolver.settings()))
if output:
Path(output).write_text(projection.render())
else:
@@ -103,9 +141,10 @@ def cmd_codeowners(output: str | None) -> None:
@click.command(name="owners:unowned", help="List unowned tracked files (respecting owners: null exemptions)")
+@repo_root_option
@click.argument("prefix", required=False)
-def cmd_unowned(prefix: str | None) -> None:
- resolver = OwnersResolver()
+def cmd_unowned(repo_root: Path | None, prefix: str | None) -> None:
+ resolver = _resolver(repo_root)
files = resolver.tracked_files(prefix)
unowned = resolver.unowned(files)
for path in unowned:
@@ -113,50 +152,40 @@ def cmd_unowned(prefix: str | None) -> None:
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]:
+def _validate_owners_live(all_owners: set[str], github: GitHubOrg) -> 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}")
+ try:
+ valid_slugs = github.team_slugs()
+ except GitHubLookupError as exc:
+ return [f"could not validate team slugs: {exc}"]
+ 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}")
+ # A review request to someone outside the org fails, so account existence is not enough.
+ try:
+ is_member = github.is_member(handle)
+ except GitHubLookupError as exc:
+ errors.append(f"could not validate @{handle}: {exc}")
+ continue
+ if not is_member:
+ errors.append(f"not a {github.org} 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"
+def _reserved_location_error(rel: str, reserved_dirs: tuple[str, ...]) -> str | None:
+ """Reject an owners.yaml where other tooling reads every YAML file in the directory. Hoist its
+ ownership into a parent's rules instead."""
+ for pattern in (*BUILTIN_RESERVED_DIRS, *reserved_dirs):
+ if compile_pattern(pattern).test(rel):
+ return (
+ f"{rel}: owners.yaml is not allowed here, because the reserved pattern '{pattern}' matches it"
+ " (other tooling reads every YAML file there); move the ownership into a parent owners.yaml"
+ )
return None
@@ -223,10 +252,13 @@ def _live_scope(owners_by_file: dict[str, set[str]], paths: tuple[str, ...]) ->
@click.command(name="owners:lint", help="Validate owners.yaml files, conflicts, dead globs, and coverage")
@click.option("--live", is_flag=True, help="Also validate team slugs and @handles against the GitHub org")
+@org_option
+@repo_root_option
@click.argument("paths", nargs=-1)
-def cmd_lint(live: bool, paths: tuple[str, ...]) -> None:
- resolver = OwnersResolver()
+def cmd_lint(live: bool, org: str | None, repo_root: Path | None, paths: tuple[str, ...]) -> None:
+ resolver = _resolver(repo_root)
repo_root = resolver.repo_root
+ settings = resolver.settings()
errors: list[str] = []
warnings: list[str] = []
owners_by_file: defaultdict[str, set[str]] = defaultdict(set)
@@ -240,6 +272,7 @@ def cmd_lint(live: bool, paths: tuple[str, ...]) -> None:
entries = resolver.parsed_ownership_files() # the single parse pass
owners_yaml_dirs = {e.rel_dir for e in entries if e.name == OWNERS_FILENAME}
+ alias_by_dir: dict[str, str] = {}
for entry in entries:
rel = entry.path.relative_to(repo_root).as_posix()
@@ -247,16 +280,22 @@ def cmd_lint(live: bool, paths: tuple[str, ...]) -> None:
parsed = entry.parsed
if entry.name == OWNERS_FILENAME:
- reserved_error = _reserved_location_error(rel)
+ reserved_error = _reserved_location_error(rel, settings.reserved_dirs)
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 entry.is_alias:
+ # Only flags a conflict. A host that scaffolds the alias file validates its owners itself.
+ # A file without a usable `owners:` list counts as absent (SPEC section 6), so it is
+ # not a conflict: any repo naming a general manifest as an alias holds plenty of them.
+ if parsed is not None and directory in owners_yaml_dirs:
+ errors.append(f"{directory or '<root>'}: has both {entry.name} (with owners) and owners.yaml")
+ elif parsed is not None and directory in alias_by_dir:
+ errors.append(f"{directory}: has both {alias_by_dir[directory]} and {entry.name} (with owners)")
+ elif parsed is not None:
+ alias_by_dir[directory] = entry.name
if parsed and parsed.owners:
- owners_by_file[rel].update(normalize_product_owners(parsed.owners))
+ owners_by_file[rel].update(normalize_owners(parsed.owners))
continue
for err in entry.errors:
@@ -285,7 +324,8 @@ def cmd_lint(live: bool, paths: tuple[str, ...]) -> None:
warnings.append(f"{rel}: rule '{rule.match}' matches zero tracked files (dead glob)")
if live:
- errors.extend(_validate_owners_live(_live_scope(owners_by_file, paths)))
+ github = GitHubOrg(_github_org(org, settings))
+ errors.extend(_validate_owners_live(_live_scope(owners_by_file, paths), github))
unowned = resolver.unowned(tracked)
warnings.append(f"coverage: {len(unowned)} of {len(tracked)} tracked file(s) resolve to unowned")
@@ -316,10 +356,11 @@ def cmd_lint(live: bool, paths: tuple[str, ...]) -> None:
name="owners:fmt",
help="Dry-run oracle: show how the current owners.yaml layout differs from the canonical placement",
)
-def cmd_fmt() -> None:
+@repo_root_option
+def cmd_fmt(repo_root: Path | None) -> None:
from .fmt import ALPHA, GAMMA, MAX_RULES, CanonicalPlacer # noqa: PLC0415 — keeps the DP off the CLI import path
- placer = CanonicalPlacer(OwnersResolver())
+ placer = CanonicalPlacer(_resolver(repo_root))
plan = placer.build()
if plan.is_canonical:
@@ -348,14 +389,9 @@ def cmd_fmt() -> None:
@click.group()
[email protected]_option(package_name="owners-yaml")
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.
- """
+ """Resolve, lint, and format distributed owners.yaml ownership files."""
main.add_command(cmd_census, name="census")
diff --git a/tools/owners/posthog_owners/codeowners.py b/packages/owners-yaml/owners_yaml/codeowners.py
similarity index 71%
rename from tools/owners/posthog_owners/codeowners.py
rename to packages/owners-yaml/owners_yaml/codeowners.py
index 73c367fe8f91..5ef4ee815406 100644
--- a/tools/owners/posthog_owners/codeowners.py
+++ b/packages/owners-yaml/owners_yaml/codeowners.py
@@ -1,8 +1,8 @@
"""A CODEOWNERS projection of the distributed owners.yaml map.
-Some tools read CODEOWNERS and nothing else. Trunk Flaky Tests is the one this exists for: it
-attributes each test to an owner by matching the JUnit ``file`` attribute against a CODEOWNERS file
-in the checkout, so the repo's real ownership map is invisible to it.
+Some tools read CODEOWNERS and nothing else. Test analytics tools such as Trunk Flaky Tests
+attribute each test to an owner by matching the JUnit ``file`` attribute against a CODEOWNERS file
+in the checkout, so the repo's real ownership map is invisible to them.
The projection covers test files only, because that is all a test-attribution consumer looks up, and
it never writes to ``.github/CODEOWNERS``, which carries GitHub's blocking-approval semantics and
@@ -16,49 +16,55 @@ from dataclasses import dataclass
from posixpath import dirname
from .census import runner_for_path
+from .matcher import compile_pattern
from .resolver import OwnersResolver
+from .schema import CodeownersSettings
-GITHUB_ORG = "PostHog"
-# The jest project that runs the product frontends, so their tests are spelled from here and not
-# from the product package that holds them.
-JEST_PROJECT_DIR = "frontend"
-
-
-def owner_handle(owner: str, org: str = GITHUB_ORG) -> str:
+def owner_handle(owner: str, org: str) -> str:
"""A CODEOWNERS handle for one owners.yaml owner: a team slug becomes ``@org/slug``,
an ``@handle`` for an individual is already in CODEOWNERS form."""
return owner if owner.startswith("@") else f"@{org}/{owner}"
-def _package_relative(path: str, package_dirs: tuple[str, ...]) -> str | None:
+def _package_relative(path: str, package_dirs: tuple[str, ...], settings: CodeownersSettings) -> str | None:
"""``path`` as the nearest enclosing Node package would spell it, else None.
- A package under `products/` is excluded: its frontend tests belong to JEST_PROJECT_DIR.
+ A package under ``jest_root_packages`` is excluded, because ``jest_root`` runs its tests.
"""
+ excluded = settings.jest_root_packages
for directory in package_dirs:
if path.startswith(f"{directory}/"):
- if directory.startswith("products/"):
+ if excluded is not None and directory.startswith(f"{excluded}/"):
return None
return path[len(directory) + 1 :]
return None
-def spellings(path: str, package_dirs: tuple[str, ...] = ()) -> list[str]:
+def _jest_root_relative(path: str, settings: CodeownersSettings) -> str | None:
+ """``path`` as a suite running from ``jest_root`` spells it, for a file ``jest_root_tests`` matches."""
+ if settings.jest_root is None or settings.jest_root_tests is None:
+ return None
+ if not compile_pattern(settings.jest_root_tests).test(path):
+ return None
+ depth = len(settings.jest_root.split("/"))
+ return "../" * depth + path
+
+
+def spellings(path: str, package_dirs: tuple[str, ...] = (), settings: CodeownersSettings | None = None) -> list[str]:
"""Every way a test runner can spell ``path`` in a JUnit ``file`` attribute.
jest-junit writes the attribute relative to the working directory the suite ran from, which is
not always the package that holds the file. pytest runs from the repo root, so a Python test
has one spelling.
"""
+ settings = settings or CodeownersSettings()
found = [path]
if runner_for_path(path) != "jest":
return found
- relative = _package_relative(path, package_dirs)
- if relative is not None:
- found.append(relative)
- if path.startswith("products/") and f"/{JEST_PROJECT_DIR}/" in path:
- found.append(f"../{path}")
+ for spelling in (_package_relative(path, package_dirs, settings), _jest_root_relative(path, settings)):
+ if spelling is not None:
+ found.append(spelling)
return found
@@ -73,7 +79,7 @@ class CodeownersProjection:
def render(self) -> str:
header = [
- "# Generated from the repo's owners.yaml map by `hogli owners:codeowners`. Do not edit.",
+ "# Generated from the repo's owners.yaml map by `owners codeowners`. Do not edit.",
"# Test files only, for tools that attribute a test to a team through CODEOWNERS.",
"# GitHub reads .github/CODEOWNERS for review assignment, never this file.",
"",
@@ -88,8 +94,9 @@ def _rule_depth(pattern: str) -> int:
def project(
paths: Iterable[str],
resolver: OwnersResolver,
+ org: str,
package_dirs: tuple[str, ...] = (),
- org: str = GITHUB_ORG,
+ settings: CodeownersSettings | None = None,
) -> CodeownersProjection:
"""Project the ownership of every test file in ``paths`` into CODEOWNERS rules.
@@ -112,7 +119,7 @@ def project(
# An unowned file keeps an empty tuple, which renders as a rule with no owner after the
# pattern. CODEOWNERS reads that as "nobody owns this", so an ancestor rule cannot claim it.
handles = tuple(owner_handle(owner, org) for owner in owners or ())
- for spelling in spellings(path, package_dirs):
+ for spelling in spellings(path, package_dirs, settings):
previous = owners_by_spelling.get(spelling)
if previous is not None and previous != handles:
ambiguous.add(spelling)
@@ -153,3 +160,15 @@ def package_dirs_from(paths: Iterable[str]) -> tuple[str, ...]:
repo-relative spelling."""
directories = {dirname(path) for path in paths if path.endswith("package.json") and dirname(path)}
return tuple(sorted(directories, key=len, reverse=True))
+
+
+def project_repo(resolver: OwnersResolver, org: str) -> CodeownersProjection:
+ """The projection of every tracked file, with the root file's ``codeowners`` settings."""
+ tracked = resolver.tracked_files()
+ return project(
+ tracked,
+ resolver,
+ org=org,
+ package_dirs=package_dirs_from(tracked),
+ settings=resolver.settings().codeowners,
+ )
diff --git a/tools/owners/posthog_owners/fmt.py b/packages/owners-yaml/owners_yaml/fmt.py
similarity index 96%
rename from tools/owners/posthog_owners/fmt.py
rename to packages/owners-yaml/owners_yaml/fmt.py
index 9471aaee2959..8d100af3799f 100644
--- a/tools/owners/posthog_owners/fmt.py
+++ b/packages/owners-yaml/owners_yaml/fmt.py
@@ -16,7 +16,7 @@ split suggestions from ``owners:lint`` are the everyday incremental mechanism
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``,
+ Pinned carriers (alias files, 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).
@@ -34,7 +34,7 @@ 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 .resolver import OWNERS_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.
@@ -89,10 +89,10 @@ class _Node:
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: bool = False # an alias file / 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,
+ alias: bool = False # the pin is an alias file: only its owners list is read,
# so it can never physically carry rules — placements must land elsewhere
@@ -173,7 +173,7 @@ class CanonicalPlacer:
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``
+ Pinned and frozen dirs isolate: they carry their own owners (an alias file
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():
@@ -235,10 +235,10 @@ class CanonicalPlacer:
"""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
+ Pinned carriers (an alias file 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
+ the alias-file subset of pinned: the file 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] = {}
@@ -246,7 +246,7 @@ class CanonicalPlacer:
alias: set[str] = set()
for entry in entries:
parsed = entry.parsed
- if entry.name == PRODUCT_FILENAME:
+ if entry.is_alias:
if parsed and parsed.owners:
pinned[entry.rel_dir] = tuple(parsed.owners)
alias.add(entry.rel_dir)
@@ -311,7 +311,7 @@ class CanonicalPlacer:
# 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
+ # A glob file or alias file lives here — it can never carry
# new rules; statements pass through.
memo[key] = (carry_up, False)
return memo[key]
@@ -370,7 +370,7 @@ class CanonicalPlacer:
# 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.
+ # hosting a glob file or alias file 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.
@@ -396,13 +396,14 @@ class CanonicalPlacer:
# --- current layout cost + diff -------------------------------------
def build(self) -> CanonicalPlan:
- entries = self.resolver.parsed_ownership_files() # the single parse pass
+ entries = self.resolver.effective_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)]
+ ownership_filenames = self.resolver.ownership_filenames()
+ code_files = [p for p in tracked if p.rsplit("/", 1)[-1] not in ownership_filenames]
# 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.
@@ -453,7 +454,7 @@ class CanonicalPlacer:
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:
+ if entry.is_alias or entry.parsed is None:
continue
parsed = entry.parsed
if _is_simple_file(parsed) and entry.rel_dir != "":
@@ -476,7 +477,7 @@ class CanonicalPlacer:
parsed = entry.parsed
if parsed is None:
continue
- if entry.name == PRODUCT_FILENAME:
+ if entry.is_alias:
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.
diff --git a/packages/owners-yaml/owners_yaml/github.py b/packages/owners-yaml/owners_yaml/github.py
new file mode 100644
index 000000000000..f2c41780c7a6
--- /dev/null
+++ b/packages/owners-yaml/owners_yaml/github.py
@@ -0,0 +1,62 @@
+"""Live checks of owners against a GitHub organization, through the ``gh`` CLI."""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+
+
+class GitHubLookupError(Exception):
+ """The ``gh`` CLI is missing, failed, or timed out."""
+
+
+class GitHubOrg:
+ """Team slugs and members of one GitHub organization.
+
+ Team slugs are fetched once per instance, and a failed fetch is not retried, so a caller that
+ checks many files waits for one timeout at most.
+
+ The lookup uses ``/orgs/{org}/teams``, which needs ``members: read``. The repo-level teams
+ endpoint would be a tighter check, because only teams with repo access can review, but many
+ app tokens lack that scope.
+ """
+
+ def __init__(self, org: str, timeout_seconds: int = 15) -> None:
+ self.org = org
+ self.timeout_seconds = timeout_seconds
+ self._team_slugs: set[str] | None = None
+ self._team_slugs_error: GitHubLookupError | None = None
+
+ def _gh_api(self, *args: str) -> subprocess.CompletedProcess[str]:
+ if not shutil.which("gh"):
+ raise GitHubLookupError("gh CLI not found; install it to validate owners against GitHub")
+ try:
+ return subprocess.run(
+ ["gh", "api", *args],
+ capture_output=True,
+ text=True,
+ timeout=self.timeout_seconds,
+ )
+ except subprocess.TimeoutExpired as exc:
+ raise GitHubLookupError(f"gh api timed out after {self.timeout_seconds}s") from exc
+
+ def _fetch_team_slugs(self) -> set[str]:
+ result = self._gh_api(f"orgs/{self.org}/teams", "--paginate", "--jq", ".[].slug")
+ if result.returncode != 0 or not result.stdout.strip():
+ raise GitHubLookupError(f"gh api failed (rc={result.returncode}): {result.stderr.strip()}")
+ return set(result.stdout.strip().split("\n"))
+
+ def team_slugs(self) -> set[str]:
+ if self._team_slugs_error is not None:
+ raise self._team_slugs_error
+ if self._team_slugs is None:
+ try:
+ self._team_slugs = self._fetch_team_slugs()
+ except GitHubLookupError as exc:
+ self._team_slugs_error = exc
+ raise
+ return self._team_slugs
+
+ def is_member(self, handle: str) -> bool:
+ """Org membership, not only account existence: a review request to a non-member fails."""
+ return self._gh_api(f"orgs/{self.org}/members/{handle}").returncode == 0
diff --git a/tools/owners/posthog_owners/matcher.py b/packages/owners-yaml/owners_yaml/matcher.py
similarity index 70%
rename from tools/owners/posthog_owners/matcher.py
rename to packages/owners-yaml/owners_yaml/matcher.py
index 27c32534311e..2d6e3b53a61e 100644
--- a/tools/owners/posthog_owners/matcher.py
+++ b/packages/owners-yaml/owners_yaml/matcher.py
@@ -6,6 +6,10 @@ 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.
+``[...]`` character classes are the one addition GitHub does not implement.
+gitignore and fnmatch both have them, and ``schema.match_is_glob`` counts ``[``
+as a glob character, so the matcher must read a class the same way.
+
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.
"""
@@ -68,23 +72,74 @@ def pattern_to_segments(pattern: str) -> list[str]:
return collapsed
+def _class_char(ch: str) -> str:
+ """One character as it must be spelled inside a regex ``[...]`` class."""
+ return "\\" + ch if ch in "^]\\-" else ch
+
+
+def _char_class(seg: str, start: int) -> tuple[str, int] | None:
+ """Convert the ``[...]`` class opening at ``start`` into a regex class.
+
+ Returns the regex plus the index just past the closing ``]``, or None when the
+ class never closes. An unmatched ``[`` is then a literal, as in fnmatch. This is
+ the one place where gitignore differs: its wildmatch makes such a pattern match
+ nothing, which is the silent failure this matcher exists to prevent. ``/`` is
+ dropped from the member list so no class can match across a segment boundary.
+ """
+ i = start + 1
+ negated = i < len(seg) and seg[i] in "!^"
+ if negated:
+ i += 1
+ body: list[str] = []
+ first = True
+ while i < len(seg):
+ ch = seg[i]
+ # A `]` in first position is a member, not the terminator.
+ if ch == "]" and not first:
+ if not body:
+ # `[/]` has no members left: it can never match. `[!/]` keeps the
+ # negation and becomes "any character but the separator".
+ return ("[^/]" if negated else "(?!)"), i + 1
+ inner = "".join(body)
+ return (f"[^{inner}/]" if negated else f"[{inner}]"), i + 1
+ first = False
+ # A range needs both endpoints, so a `-` before the terminator is a member.
+ if i + 2 < len(seg) and seg[i + 1] == "-" and seg[i + 2] != "]":
+ body.append(f"{_class_char(ch)}-{_class_char(seg[i + 2])}")
+ i += 3
+ continue
+ if ch != SEP:
+ body.append(_class_char(ch))
+ i += 1
+ return None
+
+
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 ``/``)."""
+ """Compile one pattern segment (may contain ``*``, ``?``, ``[...]`` classes and
+ ``\\`` escapes) into an anchored regex matching exactly one path segment (never
+ crossing ``/``)."""
out = ["^"]
- escape = False
- for ch in seg:
- if escape:
- escape = False
+ i = 0
+ while i < len(seg):
+ ch = seg[i]
+ if ch == "\\" and i + 1 < len(seg):
+ out.append(re.escape(seg[i + 1]))
+ i += 2
+ continue
+ if ch == "[":
+ compiled = _char_class(seg, i)
+ if compiled is not None:
+ out.append(compiled[0])
+ i = compiled[1]
+ continue
out.append(re.escape(ch))
- elif ch == "\\":
- escape = True
elif ch == "*":
out.append("[^/]*")
elif ch == "?":
out.append("[^/]")
else:
out.append(re.escape(ch))
+ i += 1
out.append("$")
return re.compile("".join(out))
@@ -143,7 +198,7 @@ class PatternMatcher:
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):
+ if not re.search(r"[*?\\\[]", pattern) and pattern.startswith(SEP):
self._literal_prefix = pattern[1:]
return
diff --git a/packages/owners-yaml/owners_yaml/py.typed b/packages/owners-yaml/owners_yaml/py.typed
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/tools/owners/posthog_owners/resolver.py b/packages/owners-yaml/owners_yaml/resolver.py
similarity index 68%
rename from tools/owners/posthog_owners/resolver.py
rename to packages/owners-yaml/owners_yaml/resolver.py
index 24e8c9263588..5059e910e0d1 100644
--- a/tools/owners/posthog_owners/resolver.py
+++ b/packages/owners-yaml/owners_yaml/resolver.py
@@ -1,8 +1,8 @@
"""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``.
+Walks from the repo root toward the path, collecting ``owners.yaml`` (or alias file)
+contributions, honoring ``inherit: false`` as a hard cut, and merges them nearest-file-wins
+per field. SPEC.md in this package defines the format.
"""
from __future__ import annotations
@@ -12,13 +12,20 @@ import subprocess
from collections.abc import Mapping
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Literal, Protocol, TypedDict
+from typing import Literal, Protocol, TypedDict, runtime_checkable
from .matcher import compile_pattern, normalize_path
-from .schema import UNSET, OwnersFile, Producer, TeamEntry, _Unset, parse_owners_file, parse_product_yaml_as_owners
-
-OWNERS_FILENAME = "owners.yaml"
-PRODUCT_FILENAME = "product.yaml"
+from .schema import (
+ OWNERS_FILENAME,
+ UNSET,
+ OwnersFile,
+ Producer,
+ RepoSettings,
+ TeamEntry,
+ _Unset,
+ parse_alias_file_as_owners,
+ parse_owners_file,
+)
@dataclass(frozen=True)
@@ -108,7 +115,7 @@ class Resolution:
class WireResolution(TypedDict):
"""The JSON wire shape shared by ``hogli owners:resolve --json`` and the
- dependency-light ``python -m posthog_owners`` entrypoint. Both emit
+ dependency-light ``python -m owners_yaml`` entrypoint. Both emit
exactly this dict per path so consumers see one format."""
owners: list[str]
@@ -132,10 +139,14 @@ class ParsedOwnershipFile:
path: Path # absolute
rel_dir: str # repo-relative posix dir ("" = root)
- name: str # OWNERS_FILENAME or PRODUCT_FILENAME
+ name: str # OWNERS_FILENAME or one of the configured alias file names
parsed: OwnersFile | None
errors: list[str] = field(default_factory=list)
+ @property
+ def is_alias(self) -> bool:
+ return self.name != OWNERS_FILENAME
+
@dataclass
class _Merged:
@@ -144,16 +155,37 @@ class _Merged:
source: str | None = None
+class RepoRootNotFound(Exception):
+ """No repo root was given and the working directory is not inside a git worktree."""
+
+
def _git_repo_root() -> Path:
- result = subprocess.run(
- ["git", "rev-parse", "--show-toplevel"],
- capture_output=True,
- text=True,
- check=True,
- )
+ try:
+ result = subprocess.run(
+ ["git", "rev-parse", "--show-toplevel"],
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ except (OSError, subprocess.CalledProcessError) as exc:
+ raise RepoRootNotFound(
+ "not inside a git worktree; pass --repo-root with the directory that holds the ownership files"
+ ) from exc
return Path(result.stdout.strip())
+def _walk_files(root: Path, prefix: str | None) -> list[str]:
+ """Repo-relative paths of every file under ``root``, for a tree that is not a git worktree."""
+ start = root / prefix if prefix else root
+ if start.is_file():
+ return [start.relative_to(root).as_posix()]
+ return sorted(
+ path.relative_to(root).as_posix()
+ for path in start.rglob("*")
+ if path.is_file() and ".git" not in path.relative_to(root).parts
+ )
+
+
class OwnershipSource(Protocol):
"""An ownership file's text by repo-relative path, or None when absent. Only ``resolve`` reads
through this; lint and format still walk a real worktree."""
@@ -161,6 +193,17 @@ class OwnershipSource(Protocol):
def read(self, path: str) -> str | None: ...
+@runtime_checkable
+class BatchOwnershipSource(OwnershipSource, Protocol):
+ """A source that pays per read, such as one that fetches over a network. ``read_all`` hands it
+ every file a batch can need before the resolver reads any, so it can fetch them together.
+
+ ``map`` calls it twice: once for the root ``owners.yaml`` alone, which names the alias files,
+ then once for the whole batch. No file is read before a ``read_all`` that covers it."""
+
+ def read_all(self, paths: list[str]) -> None: ...
+
+
@dataclass(frozen=True)
class DiskSource:
"""Ownership files read from a worktree."""
@@ -177,7 +220,7 @@ VIRTUAL_ROOT = Path("/")
class OwnersResolver:
- """Resolves ownership by reading ``owners.yaml`` / ``product.yaml`` through an ``OwnershipSource``.
+ """Resolves ownership by reading ``owners.yaml`` and alias files through an ``OwnershipSource``.
Reads a worktree by default, locating the repo root via ``git rev-parse`` (override with
``repo_root`` for testing). Pass ``source`` to resolve without one. Parsed files are cached per
@@ -199,6 +242,14 @@ class OwnersResolver:
self._parsed_ownership: list[ParsedOwnershipFile] | None = None
self._teams_cache: dict[str, TeamEntry] | None = None
+ def alias_files(self) -> tuple[str, ...]:
+ """The alias file names the root file declares, in the order that decides a tie."""
+ return self.settings().alias_files
+
+ def ownership_filenames(self) -> tuple[str, ...]:
+ """Every file name that counts as an ownership file, ``owners.yaml`` first."""
+ return (OWNERS_FILENAME, *self.alias_files())
+
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:
@@ -213,15 +264,18 @@ class OwnersResolver:
parsed, _errors = parse_owners_file(owners_text, path=self.repo_root / owners_rel, 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_rel = f"{prefix}{PRODUCT_FILENAME}"
- product_text = self.source.read(product_rel)
- if product_text is not None:
- result = parse_product_yaml_as_owners(
- product_text, path=self.repo_root / product_rel, directory=directory
- )
+ # An alias only applies when there is no owners.yaml (a directory with both is a lint
+ # error; resolve prefers owners.yaml). The root directory is skipped because the alias
+ # names come from the root owners.yaml, which is the file an alias there would replace.
+ if result is None and directory:
+ for name in self.alias_files():
+ alias_rel = f"{prefix}{name}"
+ alias_text = self.source.read(alias_rel)
+ if alias_text is None:
+ continue
+ result = parse_alias_file_as_owners(alias_text, path=self.repo_root / alias_rel, directory=directory)
+ if result is not None:
+ break
self._dir_cache[directory] = result
return result
@@ -279,13 +333,11 @@ class OwnersResolver:
def ownership_file_paths(self, paths: list[str]) -> list[str]:
"""Every ownership file that could decide any of ``paths``. A source that fetches over the
network reads this first, so it can fetch the batch's files together."""
+ directories = {d for path in paths for d in self._ancestor_dirs(normalize_path(path))}
+ filenames = self.ownership_filenames()
+ # No alias applies in the root directory (see _load_dir_file), so none is listed there.
return sorted(
- {
- f"{directory}/{name}" if directory else name
- for path in paths
- for directory in self._ancestor_dirs(normalize_path(path))
- for name in (OWNERS_FILENAME, PRODUCT_FILENAME)
- }
+ {OWNERS_FILENAME} | {f"{directory}/{name}" for directory in directories if directory for name in filenames}
)
def resolve(self, path: str) -> Resolution:
@@ -325,6 +377,12 @@ class OwnersResolver:
self._teams_cache = dict(root.teams) if root is not None else {}
return self._teams_cache
+ def settings(self) -> RepoSettings:
+ """Repo-wide settings from the root ``owners.yaml``. Defaults when there is no root file,
+ so a repo without one still reads the default alias files."""
+ root = self._load_dir_file("")
+ return root.settings if root is not None else RepoSettings()
+
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
@@ -354,6 +412,11 @@ class OwnersResolver:
return path.relative_to(self.repo_root).as_posix()
def map(self, paths: list[str]) -> dict[str, Resolution]:
+ if isinstance(self.source, BatchOwnershipSource):
+ # Two fetches, because the root file names the alias files the batch needs. A source
+ # whose read() only serves what read_all fetched has nothing to answer with otherwise.
+ self.source.read_all([OWNERS_FILENAME])
+ self.source.read_all(self.ownership_file_paths(paths))
return {p: self.resolve(p) for p in paths}
def unowned(self, paths: list[str]) -> list[str]:
@@ -362,21 +425,23 @@ class OwnersResolver:
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."""
+
+ A root that is not a git worktree, such as an unpacked export, falls back to every file on
+ disk. Cached per prefix, because the tree 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]
+ try:
+ result = subprocess.run(args, capture_output=True, text=True, check=True)
+ paths = [p for p in result.stdout.split("\0") if p]
+ except (OSError, subprocess.CalledProcessError):
+ paths = _walk_files(self.repo_root, prefix)
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
@@ -384,17 +449,40 @@ class OwnersResolver:
if self._parsed_ownership is not None:
return self._parsed_ownership
entries: list[ParsedOwnershipFile] = []
+ filenames = self.ownership_filenames()
for rel in self.tracked_files():
name = rel.rsplit("/", 1)[-1]
- if name not in (OWNERS_FILENAME, PRODUCT_FILENAME):
+ if name not in filenames:
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)
+ # No alias applies in the root directory (see _load_dir_file), so listing one would
+ # hand consumers a file resolution never reads.
+ if not rel_dir and name != OWNERS_FILENAME:
+ continue
+ abs_path = self.repo_root / rel
+ if name != OWNERS_FILENAME:
+ parsed = parse_alias_file_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 entries
+
+ def effective_ownership_files(self) -> list[ParsedOwnershipFile]:
+ """The one file per directory that ``resolve`` reads there, ordered by directory.
+
+ ``parsed_ownership_files`` lists every tracked ownership file, including the ones a
+ directory's ``owners.yaml`` or an earlier alias shadows. A consumer that models resolution
+ must see the same precedence, or it models a file the resolver never reads. Lint is the
+ exception: reporting the shadowed file is its job.
+ """
+ rank = {name: index for index, name in enumerate(self.ownership_filenames())}
+ chosen: dict[str, ParsedOwnershipFile] = {}
+ for entry in self.parsed_ownership_files():
+ if entry.parsed is None:
+ continue
+ current = chosen.get(entry.rel_dir)
+ if current is None or rank[entry.name] < rank[current.name]:
+ chosen[entry.rel_dir] = entry
+ return [chosen[directory] for directory in sorted(chosen)]
diff --git a/tools/owners/posthog_owners/schema.py b/packages/owners-yaml/owners_yaml/schema.py
similarity index 57%
rename from tools/owners/posthog_owners/schema.py
rename to packages/owners-yaml/owners_yaml/schema.py
index 5fcf4da6b560..b5c31104b4f6 100644
--- a/tools/owners/posthog_owners/schema.py
+++ b/packages/owners-yaml/owners_yaml/schema.py
@@ -1,8 +1,8 @@
"""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.
+Also loads an *alias* file as an ownership file: only its ``owners:`` list is read
+(``@handles`` kept, a ``team-CHANGEME``-only list treated as empty), every other field
+ignored. The root file names the alias files in ``alias_files``.
"""
from __future__ import annotations
@@ -10,7 +10,7 @@ from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Literal, TypeGuard, get_args
+from typing import TypeGuard
import yaml
@@ -18,18 +18,29 @@ from .matcher import compile_pattern
VALID_STATUSES = ("active", "deprecated", "generated", "vendored")
CHANGEME_SLUG = "team-CHANGEME"
+OWNERS_FILENAME = "owners.yaml"
+# Keys that only the repo-root owners.yaml may carry. They describe the repo, not a directory.
+ROOT_ONLY_KEYS = {"teams", "github_org", "producers", "reserved_dirs", "codeowners", "alias_files"}
# 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"}
+# and `rules`, plus the required `match`.
+TOP_LEVEL_KEYS = {"version", "owners", "status", "inherit", "rules"} | ROOT_ONLY_KEYS
_RULE_KEYS = {"match", "owners", "status", "inherit"}
+# Every alias name is one more file to read per directory, and a hosted resolver reads a root file
+# it does not control, so the list has a ceiling.
+MAX_ALIAS_FILES = 8
+# A root file written before `alias_files` existed still expects its product manifests to own
+# their trees, so an undeclared list means this rather than no aliases at all. `alias_files: []`
+# turns aliases off.
+DEFAULT_ALIAS_FILES: tuple[str, ...] = ("product.yaml",)
_TEAMS_ENTRY_KEYS = {"slack", "notifications"}
-# Automation that posts to a team's notifications channel and can be silenced on its own. A
-# producer must be named here to be nameable in `notifications:`. Lint reports a typo where lint
-# runs; where it does not, an unreadable mapping silences rather than posts (see _validate_teams).
-Producer = Literal["stamphog", "visual_review"]
-PRODUCERS = frozenset(get_args(Producer))
-_KNOWN_PRODUCERS = ", ".join(sorted(PRODUCERS))
+_CODEOWNERS_KEYS = {"jest_root", "jest_root_tests", "jest_root_packages"}
+
+# The name of an automation that posts to a team's notifications channel, such as a review bot.
+# When the root file declares a `producers:` list, only a declared producer is nameable in
+# `notifications:`, so a typo is an error. Lint reports it where lint runs; where it does not, an
+# unreadable mapping silences rather than posts (see _validate_teams).
+Producer = str
@dataclass(frozen=True)
@@ -69,6 +80,41 @@ class _Unset:
UNSET = _Unset()
+@dataclass(frozen=True)
+class CodeownersSettings:
+ """How the CODEOWNERS projection spells test paths.
+
+ A Jest project can run the tests of other packages from its own directory. Its JUnit report
+ then spells those files relative to ``jest_root``. ``jest_root_tests`` is a glob of the test
+ files that run that way. ``jest_root_packages`` names the tree whose packages never run their
+ own suite, so their files get no package-relative spelling.
+ """
+
+ jest_root: str | None = None
+ jest_root_tests: str | None = None
+ jest_root_packages: str | None = None
+
+
+@dataclass(frozen=True)
+class RepoSettings:
+ """Repo-wide settings from the root ``owners.yaml``.
+
+ ``github_org`` turns a team slug into ``@org/slug`` and scopes the live lint. ``producers``
+ lists the automation names a team may address in ``notifications:``; ``None`` means the repo
+ declared no list, so any name is accepted. ``reserved_dirs`` lists
+ globs where an ``owners.yaml`` must not live, because other tooling reads every YAML file there.
+ ``alias_files`` lists the other file names that count as ownership files, in the order that
+ decides which one wins when a directory holds several. A root file that does not declare it
+ gets ``DEFAULT_ALIAS_FILES``; an empty list turns aliases off.
+ """
+
+ github_org: str | None = None
+ producers: frozenset[str] | None = None
+ reserved_dirs: tuple[str, ...] = ()
+ alias_files: tuple[str, ...] = DEFAULT_ALIAS_FILES
+ codeowners: CodeownersSettings = field(default_factory=CodeownersSettings)
+
+
@dataclass
class OwnersRule:
"""A per-path override inside a file, evaluated last-match-wins within the file."""
@@ -81,7 +127,7 @@ class OwnersRule:
@dataclass
class OwnersFile:
- """A parsed ownership file (real ``owners.yaml`` or an aliased ``product.yaml``)."""
+ """A parsed ownership file (a real ``owners.yaml`` or an alias file)."""
path: Path
directory: str # repo-relative posix dir containing the file ("" for repo root)
@@ -94,12 +140,13 @@ class OwnersFile:
# Root-only Slack registry: team slug -> TeamEntry. Empty everywhere but the repo-root
# file; lets a team declare its channels once instead of per file.
teams: dict[str, TeamEntry] = field(default_factory=dict)
+ settings: RepoSettings = field(default_factory=RepoSettings)
-def normalize_product_owners(owners: list[str]) -> list[str]:
+def normalize_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."""
+ signal, so a list consisting only of it is empty. Applied to both alias files
+ and ``owners.yaml`` owners lists — one CHANGEME semantics everywhere."""
return [o for o in owners if o != CHANGEME_SLUG]
@@ -113,7 +160,7 @@ def _validate_owners_value(value: object, where: str, errors: list[str]) -> list
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])
+ return normalize_owners([str(x) for x in value])
def _is_valid_slack(raw: object) -> TypeGuard[str | bool]:
@@ -123,9 +170,9 @@ def _is_valid_slack(raw: object) -> TypeGuard[str | bool]:
def _validate_producer_map(
- value: dict[object, object], where: str, key: str, errors: list[str]
+ value: dict[object, object], where: str, key: str, producers: frozenset[str] | None, errors: list[str]
) -> dict[str, str | bool]:
- """The producers a ``notifications:`` mapping names, without the entries it rejects."""
+ """The producers a ``notifications:`` mapping names, or nothing when any entry is rejected."""
if key != "notifications":
errors.append(f"{where}: '{key}' takes a single channel, not a per-producer mapping")
return {}
@@ -133,17 +180,26 @@ def _validate_producer_map(
errors.append(f"{where}: '{key}' mapping names no producer")
return {}
declared: dict[str, str | bool] = {}
+ readable = True
for producer, raw in value.items():
- if not isinstance(producer, str) or producer not in PRODUCERS:
- errors.append(f"{where}: unknown producer '{producer}' (known: {_KNOWN_PRODUCERS})")
+ if not isinstance(producer, str) or not producer:
+ errors.append(f"{where}: producer names must be non-empty strings, got {producer!r}")
+ readable = False
+ elif producers is not None and producer not in producers:
+ known = ", ".join(sorted(producers))
+ errors.append(f"{where}: unknown producer '{producer}' (declared in 'producers': {known})")
+ readable = False
elif _is_valid_slack(raw):
declared[producer] = raw
else:
errors.append(f"{where}: '{producer}' must be a string starting with '#' or false")
- return declared
+ readable = False
+ # One rejected entry makes the whole mapping unreadable, which the caller turns into `false`:
+ # keeping the rest would route the rejected producer to the team's people channel.
+ return declared if readable else {}
-def _validate_teams(value: object, errors: list[str]) -> dict[str, TeamEntry]:
+def _validate_teams(value: object, producers: frozenset[str] | None, errors: list[str]) -> dict[str, TeamEntry]:
"""Validate the root-only ``teams:`` registry, a mapping of team slug to its channels.
A slug registers only when it declares at least one channel. Membership of the returned
@@ -170,7 +226,7 @@ def _validate_teams(value: object, errors: list[str]) -> dict[str, TeamEntry]:
if not isinstance(key, str) or key not in _TEAMS_ENTRY_KEYS:
errors.append(f"{where}: unknown field '{key}'")
elif isinstance(raw, dict):
- per_producer = _validate_producer_map(raw, where, key, errors)
+ per_producer = _validate_producer_map(raw, where, key, producers, errors)
if per_producer:
declared[key] = per_producer
elif key == "notifications":
@@ -187,6 +243,93 @@ def _validate_teams(value: object, errors: list[str]) -> dict[str, TeamEntry]:
return registry
+def _validate_string_list(value: object, key: str, errors: list[str]) -> list[str]:
+ if isinstance(value, list) and all(isinstance(x, str) and x for x in value):
+ return [str(x) for x in value]
+ errors.append(f"'{key}' must be a list of non-empty strings")
+ return []
+
+
+def _validate_codeowners(value: object, errors: list[str]) -> CodeownersSettings:
+ if not isinstance(value, dict):
+ errors.append(f"'codeowners' must be a mapping with keys {', '.join(sorted(_CODEOWNERS_KEYS))}")
+ return CodeownersSettings()
+ declared: dict[str, str] = {}
+ for key, raw in value.items():
+ if key not in _CODEOWNERS_KEYS:
+ errors.append(f"codeowners: unknown field '{key}'")
+ elif not isinstance(raw, str) or not raw:
+ errors.append(f"codeowners: '{key}' must be a non-empty string")
+ elif key == "jest_root_tests":
+ try:
+ compile_pattern(raw)
+ except ValueError as exc:
+ errors.append(f"codeowners: invalid jest_root_tests pattern '{raw}': {exc}")
+ continue
+ declared[key] = raw
+ else:
+ declared[key] = raw.strip("/")
+ return CodeownersSettings(**declared)
+
+
+def _validate_settings(data: dict[object, object], errors: list[str]) -> RepoSettings:
+ """Read the root-only repo settings. An invalid value is reported and left at its default."""
+ github_org: str | None = None
+ if "github_org" in data:
+ raw_org = data["github_org"]
+ if isinstance(raw_org, str) and raw_org and "/" not in raw_org:
+ github_org = raw_org
+ else:
+ errors.append("'github_org' must be a GitHub organization name, such as 'my-org'")
+
+ producers = (
+ frozenset(_validate_string_list(data["producers"], "producers", errors)) if "producers" in data else None
+ )
+
+ reserved_dirs: list[str] = []
+ for pattern in (
+ _validate_string_list(data["reserved_dirs"], "reserved_dirs", errors) if "reserved_dirs" in data else []
+ ):
+ try:
+ compile_pattern(pattern)
+ except ValueError as exc:
+ errors.append(f"reserved_dirs: invalid pattern '{pattern}': {exc}")
+ continue
+ reserved_dirs.append(pattern)
+
+ # A declaration replaces the default outright, including an empty list, because an author who
+ # writes the key has decided which names count. An invalid declaration is also a decision, so
+ # it yields no aliases and a lint error rather than falling back to the default.
+ alias_files: list[str] = [] if "alias_files" in data else list(DEFAULT_ALIAS_FILES)
+ declared_aliases = (
+ _validate_string_list(data["alias_files"], "alias_files", errors) if "alias_files" in data else []
+ )
+ for name in declared_aliases:
+ # A separator or a dot entry would let a name reach outside the directory it is read in.
+ if "/" in name or "\\" in name or name in {".", ".."}:
+ errors.append(f"alias_files: '{name}' must be a bare file name, without a path separator")
+ continue
+ if name == OWNERS_FILENAME:
+ errors.append(f"alias_files: '{OWNERS_FILENAME}' is the ownership file, not an alias")
+ continue
+ if name in alias_files:
+ errors.append(f"alias_files: '{name}' is listed twice")
+ continue
+ alias_files.append(name)
+ if len(declared_aliases) > MAX_ALIAS_FILES:
+ errors.append(f"alias_files: at most {MAX_ALIAS_FILES} names are allowed")
+ alias_files = []
+
+ codeowners = _validate_codeowners(data["codeowners"], errors) if "codeowners" in data else CodeownersSettings()
+ return RepoSettings(
+ github_org=github_org,
+ producers=producers,
+ reserved_dirs=tuple(reserved_dirs),
+ alias_files=tuple(alias_files),
+ codeowners=codeowners,
+ )
+
+
def _validate_status(value: object, where: str, errors: list[str]) -> str | _Unset:
if isinstance(value, str) and value in VALID_STATUSES:
return value
@@ -252,6 +395,11 @@ def _parse_rule(raw: object, index: int, errors: list[str]) -> list[OwnersRule]:
return [OwnersRule(match=pattern, owners=owners, status=status, inherit=inherit) for pattern in patterns]
+def _is_version_one(value: object) -> bool:
+ """YAML ``true`` and ``1.0`` compare equal to 1 in Python, but the format requires the integer."""
+ return type(value) is int and value == 1
+
+
def parse_owners_file(text: str, *, path: Path, directory: str) -> tuple[OwnersFile | None, list[str]]:
"""Parse and validate ``owners.yaml`` contents.
@@ -267,10 +415,11 @@ def parse_owners_file(text: str, *, path: Path, directory: str) -> tuple[OwnersF
return None, ["owners.yaml must be a YAML mapping"]
for key in data:
- if key not in _TOP_LEVEL_KEYS:
+ if key not in TOP_LEVEL_KEYS:
errors.append(f"unknown top-level field '{key}'")
- if data.get("version") != 1:
+ version_ok = _is_version_one(data.get("version"))
+ if not version_ok:
errors.append("'version: 1' is required")
if "owners" not in data:
@@ -288,13 +437,15 @@ def parse_owners_file(text: str, *, path: Path, directory: str) -> tuple[OwnersF
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)
+ # Repo-wide settings and the team registry are single lookups, so they only make sense at
+ # the root; a nested file carrying them would silently do nothing.
+ if directory != "":
+ for key in sorted(ROOT_ONLY_KEYS & data.keys()):
+ errors.append(f"'{key}' is only allowed in the repo-root owners.yaml")
+ else:
+ file.settings = _validate_settings(data, errors)
+ if "teams" in data:
+ file.teams = _validate_teams(data["teams"], file.settings.producers, errors)
if "rules" in data:
raw_rules = data["rules"]
@@ -305,13 +456,13 @@ def parse_owners_file(text: str, *, path: Path, directory: str) -> tuple[OwnersF
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:
+ if not version_ok 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
+def parse_alias_file_as_owners(text: str, *, path: Path, directory: str) -> OwnersFile | None:
+ """Load an alias file as an ownership file, or None if it has no
usable ``owners:`` list."""
try:
data = yaml.safe_load(text)
@@ -322,7 +473,7 @@ def parse_product_yaml_as_owners(text: str, *, path: Path, directory: str) -> Ow
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)
+ owners = normalize_owners(raw)
return OwnersFile(path=path, directory=directory, owners=owners, is_alias=True)
@@ -335,8 +486,8 @@ def match_is_glob(match: str) -> bool:
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:
+ Both callers agree that status/``inherit: false`` (and being an
+ alias file) 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:
diff --git a/packages/owners-yaml/package.json b/packages/owners-yaml/package.json
new file mode 100644
index 000000000000..3d6435fb54b2
--- /dev/null
+++ b/packages/owners-yaml/package.json
@@ -0,0 +1,10 @@
+{
+ "name": "@posthog/owners-yaml",
+ "version": "0.0.1",
+ "private": true,
+ "description": "owners.yaml resolver (owners-yaml). Python uv workspace member; this manifest registers it in the turbo graph so turbo-discover can see when it changed and re-test the products that import it.",
+ "scripts": {
+ "backend:test": "pytest tests -v --tb=short"
+ },
+ "pythonImportName": "owners_yaml"
+}
diff --git a/tools/owners/pyproject.toml b/packages/owners-yaml/pyproject.toml
similarity index 64%
rename from tools/owners/pyproject.toml
rename to packages/owners-yaml/pyproject.toml
index 329ce936fe34..5143c7c0ff32 100644
--- a/tools/owners/pyproject.toml
+++ b/packages/owners-yaml/pyproject.toml
@@ -3,16 +3,16 @@ requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
-name = "posthog-owners"
-version = "0.1.0"
-description = "Distributed owners.yaml ownership resolver, linter, and formatter"
+name = "owners-yaml"
+version = "0.2.0"
+description = "Code ownership in owners.yaml files next to the code: resolver, linter, and CODEOWNERS export"
readme = "README.md"
license = "MIT"
requires-python = ">=3.10"
authors = [
{ name = "PostHog", email = "[email protected]" }
]
-keywords = ["ownership", "codeowners", "devex", "yaml"]
+keywords = ["ownership", "codeowners", "owners.yaml", "monorepo", "code-review", "devex"]
classifiers = [
"Development Status :: 4 - Beta",
"Environment :: Console",
@@ -38,15 +38,20 @@ dev = [
]
[project.scripts]
-owners = "posthog_owners.cli:main"
+owners = "owners_yaml.cli:main"
+# Lets `uvx owners-yaml` work without `--from`.
+owners-yaml = "owners_yaml.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"
+Documentation = "https://github.com/PostHog/posthog/tree/master/packages/owners-yaml#readme"
+Specification = "https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/SPEC.md"
+Changelog = "https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/CHANGELOG.md"
+Repository = "https://github.com/PostHog/posthog/tree/master/packages/owners-yaml"
+Issues = "https://github.com/PostHog/posthog/issues"
[tool.hatch.build.targets.wheel]
-packages = ["posthog_owners"]
+packages = ["owners_yaml"]
[tool.uv]
exclude-newer = "7 days"
@@ -54,7 +59,7 @@ exclude-newer = "7 days"
# the stale wheel in the cache and uv installs it again. List the sources to key on them too.
cache-keys = [
{ file = "pyproject.toml" },
- { file = "posthog_owners/**/*.py" },
+ { file = "owners_yaml/**/*.py" },
]
[tool.pytest.ini_options]
diff --git a/packages/owners-yaml/resolution.schema.json b/packages/owners-yaml/resolution.schema.json
new file mode 100644
index 000000000000..c2161ea02cc0
--- /dev/null
+++ b/packages/owners-yaml/resolution.schema.json
@@ -0,0 +1,29 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://github.com/PostHog/posthog/blob/master/packages/owners-yaml/resolution.schema.json",
+ "title": "owners.yaml resolver response",
+ "description": "The JSON object a resolver writes for a resolution request, keyed by normalized path. See SPEC.md section 7.",
+ "type": "object",
+ "additionalProperties": {
+ "type": "object",
+ "required": ["owners", "status", "slack", "source"],
+ "properties": {
+ "owners": {
+ "type": "array",
+ "items": { "type": "string", "minLength": 1 },
+ "description": "The resolved owners, primary owner first. Empty when the path is unowned or unowned by design."
+ },
+ "status": { "enum": ["active", "deprecated", "generated", "vendored"] },
+ "slack": {
+ "type": ["string", "null"],
+ "pattern": "^#",
+ "description": "The channel for the requested purpose."
+ },
+ "source": {
+ "type": ["string", "null"],
+ "minLength": 1,
+ "description": "The repository-relative path of the file that set the owners."
+ }
+ }
+ }
+}
diff --git a/packages/owners-yaml/tests/test_conformance.py b/packages/owners-yaml/tests/test_conformance.py
new file mode 100644
index 000000000000..17c9117e1705
--- /dev/null
+++ b/packages/owners-yaml/tests/test_conformance.py
@@ -0,0 +1,80 @@
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+import yaml
+from owners_yaml.resolver import OWNERS_FILENAME, OwnersResolver, Purpose, team_channel, teams_registry
+
+CONFORMANCE_DIR = Path(__file__).parent.parent / "conformance"
+CASE_FILES = sorted((CONFORMANCE_DIR / "cases").glob("*.yaml"))
+
+
+@dataclass(frozen=True)
+class ConformanceCase:
+ name: str
+ files: dict[str, str]
+ purpose: Purpose
+ producer: str | None
+ expect: dict[str, dict[str, Any]]
+
+
+def load_cases() -> list[pytest.ParameterSet]:
+ params = []
+ for case_file in CASE_FILES:
+ for raw in yaml.safe_load(case_file.read_text())["cases"]:
+ case = ConformanceCase(
+ name=raw["name"],
+ files=raw["files"],
+ purpose=raw.get("purpose", "slack"),
+ producer=raw.get("producer"),
+ expect=raw["expect"],
+ )
+ params.append(pytest.param(case, id=f"{case_file.name}::{case.name}"))
+ return params
+
+
+def resolve_channel(case: ConformanceCase, owners: list[str], resolved_slack: str | None) -> str | None:
+ if case.producer is None or not owners or owners[0].startswith("@"):
+ return resolved_slack
+ # OwnersResolver takes no producer, so a producer case looks the channel up with team_channel.
+ registry = teams_registry(case.files.get(OWNERS_FILENAME, ""))
+ return team_channel(owners[0], registry, case.purpose, case.producer).channel
+
+
[email protected]("case", load_cases())
+def test_conformance_case(tmp_path: Path, case: ConformanceCase) -> None:
+ for rel, text in case.files.items():
+ target = tmp_path / rel
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(text)
+ resolver = OwnersResolver(repo_root=tmp_path, purpose=case.purpose)
+
+ actual = {}
+ for path in case.expect:
+ resolution = resolver.resolve(path)
+ owners = resolution.owners or []
+ actual[path] = {
+ "owners": owners,
+ "unowned_by_design": resolution.unowned_by_design,
+ "status": resolution.status,
+ "source": resolution.source,
+ "slack": resolve_channel(case, owners, resolution.slack),
+ }
+
+ assert actual == case.expect
+
+
[email protected]("case_file", CASE_FILES, ids=[f.name for f in CASE_FILES])
+def test_case_file_matches_schema(case_file: Path) -> None:
+ jsonschema = pytest.importorskip("jsonschema")
+ schema = json.loads((CONFORMANCE_DIR / "case.schema.json").read_text())
+ document = yaml.safe_load(case_file.read_text())
+
+ jsonschema.validate(document, schema, cls=jsonschema.Draft202012Validator)
+ names = [case["name"] for case in document["cases"]]
+ assert len(names) == len(set(names)), "case names must be unique within a file"
diff --git a/tools/owners/tests/test_owners.py b/packages/owners-yaml/tests/test_owners.py
similarity index 76%
rename from tools/owners/tests/test_owners.py
rename to packages/owners-yaml/tests/test_owners.py
index 5ad11e10e3b1..249a25bdd4c2 100644
--- a/tools/owners/tests/test_owners.py
+++ b/packages/owners-yaml/tests/test_owners.py
@@ -7,7 +7,8 @@ from pathlib import Path
import pytest
-from posthog_owners import (
+from click.testing import CliRunner
+from owners_yaml import (
census,
first_team_owner,
fmt as fmt_module,
@@ -17,36 +18,17 @@ from posthog_owners import (
runner_for_path,
spellings,
)
-from posthog_owners.cli import _consolidation_suggestions, _live_scope, _reserved_location_error
-from posthog_owners.fmt import CanonicalPlacer, CanonicalPlan
-from posthog_owners.matcher import path_matches_pattern
-from posthog_owners.resolver import OwnersResolver, team_channel
-from posthog_owners.schema import TeamEntry, 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),
- ],
+from owners_yaml.cli import _consolidation_suggestions, _live_scope, _reserved_location_error, main
+from owners_yaml.fmt import CanonicalPlacer, CanonicalPlan
+from owners_yaml.resolver import OwnersResolver, team_channel
+from owners_yaml.schema import (
+ DEFAULT_ALIAS_FILES,
+ TOP_LEVEL_KEYS,
+ CodeownersSettings,
+ TeamEntry,
+ is_simple_owners_file,
+ parse_owners_file,
)
-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:
@@ -55,77 +37,6 @@ def _write(root: Path, rel: str, text: str) -> None:
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,
@@ -197,23 +108,6 @@ def test_multi_match_validation_errors_drop_the_rule(tmp_path: Path, rules_yaml:
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)
@@ -223,19 +117,6 @@ def test_resolver_no_contribution_is_unowned_not_exempt(tmp_path: Path) -> None:
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
-
-
@pytest.fixture
def registry_repo(tmp_path: Path) -> Path:
_write(
@@ -254,29 +135,61 @@ def registry_repo(tmp_path: Path) -> Path:
return tmp_path
- "path,purpose,slack",
- [
- ("reg/x.py", "slack", "#registry-chan"), # registry hit for the primary owner beats derived
- ("silent/x.py", "slack", None), # registry false suppresses derivation
- ("derive/x.py", "slack", "#team-nonreg"), # no registry entry: derive #<primary owner>
- ("indiv/x.py", "slack", None), # primary owner is an @handle: registry ignored, no derive
- ("split/x.py", "slack", "#split-people"), # a declared notifications channel stays off the people lookup
- ("split/x.py", "notifications", "#split-bots"), # automation resolves to the declared bot channel
- ("reg/x.py", "notifications", "#registry-chan"), # no notifications entry: automation follows the people
- ],
-)
-def test_slack_registry_precedence(registry_repo: Path, path: str, purpose: str, slack: str | None) -> None:
- assert OwnersResolver(repo_root=registry_repo, purpose=purpose).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"
+def test_teams_registry_and_settings_are_root_only(tmp_path: Path) -> None:
+ text = (
+ "version: 1\nowners: [team-a]\ngithub_org: acme\nproducers: [bot]\n"
+ "reserved_dirs: ['gen/**']\nalias_files: [package.yaml]\ncodeowners:\n jest_root: web\n"
+ "teams:\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)
+ assert sorted(e.split("'")[1] for e in sub_errors if "only allowed in the repo-root" in e) == [
+ "alias_files",
+ "codeowners",
+ "github_org",
+ "producers",
+ "reserved_dirs",
+ "teams",
+ ]
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": TeamEntry(slack="#a")}
+ assert root.settings.github_org == "acme"
+ assert root.settings.producers == frozenset({"bot"})
+ assert root.settings.reserved_dirs == ("gen/**",)
+ assert root.settings.alias_files == ("package.yaml",)
+ assert root.settings.codeowners == CodeownersSettings(jest_root="web")
+
+
+def test_json_schema_accepts_the_same_top_level_keys_as_the_parser() -> None:
+ schema = json.loads((Path(__file__).parent.parent / "owners.schema.json").read_text())
+ assert set(schema["properties"]) == TOP_LEVEL_KEYS
+
+
+ "settings_yaml,needle",
+ [
+ ("github_org: acme/repo\n", "'github_org' must be a GitHub organization name"),
+ ("producers: bot\n", "'producers' must be a list"),
+ ("reserved_dirs: ['a***b']\n", "reserved_dirs: invalid pattern"),
+ ("alias_files: ['pkg/product.yaml']\n", "must be a bare file name"),
+ ("alias_files: ['..\\..\\outside.yaml']\n", "must be a bare file name"),
+ ("alias_files: ['..']\n", "must be a bare file name"),
+ ("alias_files: [owners.yaml]\n", "is the ownership file, not an alias"),
+ ("alias_files: [a, b, c, d, e, f, g, h, i]\n", "at most 8 names"),
+ ("alias_files: [a.yaml, b.yaml, a.yaml]\n", "is listed twice"),
+ ("alias_files: [a, b, c, d, e, f, g, h, a]\n", "at most 8 names"),
+ ("codeowners:\n jest_dir: web\n", "codeowners: unknown field 'jest_dir'"),
+ ],
+)
+def test_invalid_repo_settings_are_schema_errors(tmp_path: Path, settings_yaml: str, needle: str) -> None:
+ file, errors = parse_owners_file(
+ "version: 1\nowners: []\n" + settings_yaml, path=tmp_path / "owners.yaml", directory=""
+ )
+ assert any(needle in e for e in errors), errors
+ assert file is not None
+ if settings_yaml.startswith("alias_files:"):
+ # A rejected declaration keeps the entries that were valid; it never falls back to the default.
+ assert file.settings.alias_files != DEFAULT_ALIAS_FILES
@pytest.mark.parametrize(
@@ -297,7 +210,7 @@ def test_teams_registry_is_root_only(tmp_path: Path) -> None:
],
)
def test_teams_registry_invalid_shapes(tmp_path: Path, teams_yaml: str, needle: str) -> None:
- text = "version: 1\nowners: []\n" + teams_yaml
+ text = "version: 1\nowners: []\nproducers: [stamphog, visual_review]\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
@@ -355,15 +268,30 @@ def test_team_channel_derives_for_an_unregistered_slug() -> None:
)
-def test_an_unreadable_producer_map_registers_as_silence(tmp_path: Path) -> None:
+ "notifications_yaml",
+ [
+ " stamphogg: false\n",
+ " stamphog: '#a-bots'\n stamphogg: false\n",
+ ],
+ ids=["only-entry-rejected", "one-of-two-entries-rejected"],
+)
+def test_an_unreadable_producer_map_registers_as_silence(tmp_path: Path, notifications_yaml: str) -> None:
# Dropping the key instead would fall through to the derived channel, so a typo in a repo our
# lint never reads would post the digest the team asked to be left out of.
- text = "version: 1\nowners: []\nteams:\n team-a:\n notifications:\n stamphogg: false\n"
+ text = "version: 1\nowners: []\nproducers: [stamphog]\nteams:\n team-a:\n notifications:\n" + notifications_yaml
file, errors = parse_owners_file(text, path=tmp_path / "owners.yaml", directory="")
assert any("unknown producer" in e for e in errors)
assert file is not None and file.teams == {"team-a": TeamEntry(notifications=False)}
+def test_a_repo_without_a_producers_list_accepts_any_producer(tmp_path: Path) -> None:
+ text = "version: 1\nowners: []\nteams:\n team-a:\n notifications:\n reviewbot: '#a-bots'\n"
+ file, errors = parse_owners_file(text, path=tmp_path / "owners.yaml", directory="")
+ assert errors == []
+ assert file is not None and file.teams == {"team-a": TeamEntry(notifications={"reviewbot": "#a-bots"})}
+
+
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="")
@@ -385,7 +313,7 @@ def test_teams_registry_pins_file_as_non_simple(tmp_path: Path) -> None:
],
)
def test_reserved_location_error(rel: str, reserved: bool) -> None:
- assert (_reserved_location_error(rel) is not None) is reserved
+ assert (_reserved_location_error(rel, ("products/**/mcp/**",)) is not None) is reserved
@pytest.mark.parametrize(
@@ -485,16 +413,28 @@ def test_fmt_never_exiles_singleton_rules_on_overflow(tmp_path: Path, monkeypatc
assert plan.creations == []
-def test_fmt_product_yaml_is_a_free_carrier(tmp_path: Path) -> None:
+ "extra_files,alias_setting",
+ [
+ ({}, "[product.yaml]"),
+ # The second alias sorts after the first in tracked order, so a formatter that takes the
+ # last one models a directory the resolver never reads, and the proof fails.
+ ({"products/foo/zz.yaml": "owners:\n - team-other\n"}, "[product.yaml, zz.yaml]"),
+ ],
+ ids=["one-alias", "two-aliases-in-one-dir"],
+)
+def test_fmt_product_yaml_is_a_free_carrier(tmp_path: Path, extra_files: dict[str, str], alias_setting: str) -> 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,
{
+ "owners.yaml": f"version: 1\nowners: []\nalias_files: {alias_setting}\n",
"products/foo/product.yaml": "name: Foo\nowners:\n - team-foo\n",
"products/foo/x.py": "x",
"r1.py": "x",
"r2.py": "x",
+ **extra_files,
},
)
assert plan.is_canonical
@@ -508,6 +448,7 @@ def test_fmt_never_places_rules_on_a_product_yaml_dir(tmp_path: Path) -> None:
plan = _fmt_plan(
tmp_path,
{
+ "owners.yaml": "version: 1\nowners: []\nalias_files: [product.yaml]\n",
"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",
@@ -623,7 +564,7 @@ def test_fmt_reports_stale_rule_removals(tmp_path: Path) -> None:
plan = _fmt_plan(
tmp_path,
{
- "owners.yaml": "version: 1\nowners: []\n",
+ "owners.yaml": "version: 1\nowners: []\nalias_files: [product.yaml]\n",
"products/foo/product.yaml": "name: Foo\nowners:\n - team-p\n",
"products/foo/x.py": "x",
"products/foo/backend/owners.yaml": (
@@ -765,6 +706,60 @@ def test_resolver_reads_through_an_injected_source() -> None:
assert resolver.resolve("posthog/temporal/test_run.py").source == "posthog/temporal/owners.yaml"
+ "root_text,expected_prefetch",
+ [
+ ("version: 1\nowners: [team-root]\nalias_files: []\n", ["a/b/owners.yaml", "a/owners.yaml", "owners.yaml"]),
+ (
+ "version: 1\nowners: [team-root]\n",
+ [
+ "a/b/owners.yaml",
+ "a/b/product.yaml",
+ "a/owners.yaml",
+ "a/product.yaml",
+ "owners.yaml",
+ ],
+ ),
+ (
+ "version: 1\nowners: [team-root]\nalias_files: [package.yaml]\n",
+ [
+ "a/b/owners.yaml",
+ "a/b/package.yaml",
+ "a/owners.yaml",
+ "a/package.yaml",
+ "owners.yaml",
+ ],
+ ),
+ ],
+ ids=["aliases-off", "default-alias", "declared-alias"],
+)
+def test_map_prefetches_a_batch_through_read_all_before_the_per_path_reads(
+ root_text: str, expected_prefetch: list[str]
+) -> None:
+ calls: list[tuple[str, object]] = []
+
+ class BatchDictSource:
+ def read(self, path: str) -> str | None:
+ calls.append(("read", path))
+ return root_text if path == "owners.yaml" else None
+
+ def read_all(self, paths: list[str]) -> None:
+ calls.append(("read_all", list(paths)))
+
+ resolver = OwnersResolver(source=BatchDictSource())
+ resolver.map(["a/b/x.py"])
+
+ # The root file is prefetched on its own first, because it names the alias files the batch
+ # needs. A source that only serves what read_all fetched must never see a read before that.
+ assert [argument for kind, argument in calls if kind == "read_all"] == [["owners.yaml"], expected_prefetch]
+ fetched: set[str] = set()
+ for kind, argument in calls:
+ if kind == "read_all":
+ fetched.update(argument) # type: ignore[arg-type]
+ else:
+ assert argument in fetched, f"read {argument!r} before a read_all covering it"
+
+
def test_census_counts_test_files_per_team_and_folds_gaps_into_unowned(tmp_path: Path) -> None:
_write(tmp_path, "owners.yaml", "version: 1\nowners: []\n")
_write(tmp_path, "products/a/owners.yaml", "version: 1\nowners: [team-a]\n")
@@ -794,7 +789,7 @@ def test_first_team_owner_skips_handles() -> None:
def _run_entrypoint(repo: Path, *args: str, stdin: str = "") -> subprocess.CompletedProcess[str]:
return subprocess.run(
- [sys.executable, "-m", "posthog_owners", *args],
+ [sys.executable, "-m", "owners_yaml", *args],
cwd=repo,
input=stdin,
capture_output=True,
@@ -809,7 +804,8 @@ def test_json_entrypoint_resolves_against_an_explicit_repo_root(registry_repo: P
result = _run_entrypoint(registry_repo, "--repo-root", str(registry_repo), "reg/x.py")
assert result.returncode == 0, result.stderr
- assert json.loads(result.stdout) == {
+ response = json.loads(result.stdout)
+ assert response == {
"reg/x.py": {
"owners": ["team-registry"],
"status": "active",
@@ -817,6 +813,9 @@ def test_json_entrypoint_resolves_against_an_explicit_repo_root(registry_repo: P
"source": "reg/owners.yaml",
}
}
+ jsonschema = pytest.importorskip("jsonschema")
+ schema = json.loads((Path(__file__).parent.parent / "resolution.schema.json").read_text())
+ jsonschema.validate(response, schema)
def test_json_entrypoint_repo_root_reads_stdin_paths_and_honors_purpose(registry_repo: Path) -> None:
@@ -865,7 +864,11 @@ def _codeowners_lookup(rendered: str, path: str) -> list[str]:
@pytest.fixture
def projection_repo(tmp_path: Path) -> Path:
- _write(tmp_path, "owners.yaml", "version: 1\nowners: []\n")
+ _write(
+ tmp_path,
+ "owners.yaml",
+ "version: 1\nowners: []\ngithub_org: PostHog\n",
+ )
_write(tmp_path, "posthog/security/owners.yaml", "version: 1\nowners: [team-security]\n")
_write(tmp_path, "posthog/security/test/owners.yaml", "version: 1\nowners: null\n")
_write(tmp_path, "products/alpha/owners.yaml", "version: 1\nowners: [team-alpha, '@someone']\n")
@@ -875,6 +878,11 @@ def projection_repo(tmp_path: Path) -> Path:
return tmp_path
+JEST_ROOT_SETTINGS = CodeownersSettings(
+ jest_root="frontend", jest_root_tests="products/**/frontend/**", jest_root_packages="products"
+)
+
+
@pytest.mark.parametrize(
"path,expected",
[
@@ -888,7 +896,8 @@ def projection_repo(tmp_path: Path) -> Path:
ids=["pytest-runs-from-the-repo-root", "jest-runs-from-its-package", "product-frontends-run-from-frontend"],
)
def test_spellings_cover_how_each_runner_writes_the_file_attribute(path: str, expected: list[str]) -> None:
- assert spellings(path, package_dirs_from(["frontend/package.json", "products/alpha/package.json"])) == expected
+ package_dirs = package_dirs_from(["frontend/package.json", "products/alpha/package.json"])
+ assert spellings(path, package_dirs, JEST_ROOT_SETTINGS) == expected
def test_projection_resolves_every_spelling_to_what_the_resolver_says(projection_repo: Path) -> None:
@@ -905,14 +914,16 @@ def test_projection_resolves_every_spelling_to_what_the_resolver_says(projection
]
resolver = OwnersResolver(projection_repo)
- projection = project(tracked, resolver, package_dirs_from(tracked))
+ projection = project(
+ tracked, resolver, org="PostHog", package_dirs=package_dirs_from(tracked), settings=JEST_ROOT_SETTINGS
+ )
rendered = projection.render()
for path in tracked:
if runner_for_path(path) is None:
continue
- expected = [owner_handle(owner) for owner in resolver.resolve(path).owners or []]
- for spelling in spellings(path, package_dirs_from(tracked)):
+ expected = [owner_handle(owner, "PostHog") for owner in resolver.resolve(path).owners or []]
+ for spelling in spellings(path, package_dirs_from(tracked), JEST_ROOT_SETTINGS):
assert _codeowners_lookup(rendered, spelling) == expected, f"{spelling} resolved wrongly"
assert projection.owned_file_count == 5
assert projection.unowned_file_count == 1
@@ -929,7 +940,9 @@ def test_projection_drops_a_spelling_two_teams_would_both_claim(projection_repo:
"frontend/src/solo.test.ts",
]
- projection = project(tracked, OwnersResolver(projection_repo), package_dirs_from(tracked))
+ projection = project(
+ tracked, OwnersResolver(projection_repo), org="PostHog", package_dirs=package_dirs_from(tracked)
+ )
rendered = projection.render()
assert projection.ambiguous_spellings == ["src/shared.test.ts"]
@@ -937,3 +950,61 @@ def test_projection_drops_a_spelling_two_teams_would_both_claim(projection_repo:
assert _codeowners_lookup(rendered, "src/solo.test.ts") == ["@PostHog/team-web"]
assert _codeowners_lookup(rendered, "frontend/src/shared.test.ts") == ["@PostHog/team-web"]
assert _codeowners_lookup(rendered, "nodejs/src/shared.test.ts") == ["@PostHog/team-pipeline"]
+
+
+def test_cli_lint_reports_no_alias_conflict_the_resolver_does_not_see(tmp_path: Path) -> None:
+ # An alias in the root never applies, and a manifest without an owners list counts as absent —
+ # so neither is a conflict with the owners.yaml next to it.
+ _write(tmp_path, "owners.yaml", "version: 1\nowners: [team-a]\nalias_files: [package.yaml]\n")
+ _write(tmp_path, "package.yaml", "name: root\nowners:\n - team-root-manifest\n")
+ _write(tmp_path, "web/owners.yaml", "version: 1\nowners: [team-web]\n")
+ _write(tmp_path, "web/package.yaml", "name: web\nversion: 2.0.0\n")
+ _write(tmp_path, "web/app.ts", "")
+
+ result = CliRunner().invoke(main, ["lint", "--repo-root", str(tmp_path)])
+
+ assert result.exit_code == 0, result.output
+ assert "has both" not in result.output
+
+
+def test_cli_lint_reports_two_aliases_with_owners_in_one_directory(tmp_path: Path) -> None:
+ _write(tmp_path, "owners.yaml", "version: 1\nowners: [team-a]\nalias_files: [product.yaml, package.yaml]\n")
+ _write(tmp_path, "web/product.yaml", "owners:\n - team-web\n")
+ _write(tmp_path, "web/package.yaml", "owners:\n - team-other\n")
+
+ result = CliRunner().invoke(main, ["lint", "--repo-root", str(tmp_path)])
+
+ assert result.exit_code != 0
+ assert "web: has both" in result.output
+
+
+def test_cli_lints_a_tree_that_is_not_a_git_worktree(registry_repo: Path) -> None:
+ _write(registry_repo, "reg/code.py", "")
+ _write(registry_repo, "loose/code.py", "")
+
+ result = CliRunner().invoke(main, ["lint", "--repo-root", str(registry_repo)])
+
+ assert result.exit_code == 0, result.output
+ # The walk finds the six ownership files plus the two code files, and only loose/code.py is unowned.
+ assert "coverage: 2 of 8 tracked file(s) resolve to unowned" in result.output
+
+
+ "args,message",
+ [
+ (["lint"], "not inside a git worktree"),
+ (["codeowners", "--repo-root", "."], "no GitHub organization"),
+ (["lint", "--live", "--repo-root", "."], "no GitHub organization"),
+ ],
+ ids=["no-repo-root", "codeowners-without-org", "live-lint-without-org"],
+)
+def test_cli_reports_missing_context_without_a_traceback(tmp_path: Path, args: list[str], message: str) -> None:
+ _write(tmp_path, "owners.yaml", "version: 1\nowners: [team-a]\n")
+ runner = CliRunner()
+ with runner.isolated_filesystem(temp_dir=tmp_path) as cwd:
+ _write(Path(cwd), "owners.yaml", "version: 1\nowners: [team-a]\n")
+ result = runner.invoke(main, args)
+
+ assert result.exit_code == 1
+ assert message in result.output
+ assert result.exception is None or isinstance(result.exception, SystemExit)
diff --git a/packages/owners-yaml/turbo.json b/packages/owners-yaml/turbo.json
new file mode 100644
index 000000000000..96e14b53a7ba
--- /dev/null
+++ b/packages/owners-yaml/turbo.json
@@ -0,0 +1,8 @@
+{
+ "extends": ["//"],
+ "tasks": {
+ "backend:test": {
+ "inputs": ["owners_yaml/**/*.py", "tests/**/*.py", "conformance/**", "pyproject.toml"]
+ }
+ }
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 688810f9bc80..ea3e6a36dd4e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1920,6 +1920,8 @@ importers:
specifier: 'catalog:'
version: 2.9.0
+ packages/owners-yaml: {}
+
packages/quill:
devDependencies:
tailwindcss-scroll-mask:
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 73322eb3b233..28d914a8b475 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -8,6 +8,7 @@ packages:
- common/replay-headless
- common/tailwind
- packages/llm-normalizer
+ - packages/owners-yaml
- packages/quill
- packages/quill/apps/*
- packages/quill/packages/*
diff --git a/posthog/test/repo_invariants/test_pytest_module_collisions.py b/posthog/test/repo_invariants/test_pytest_module_collisions.py
index 154b074a1c03..9cc5cd5f2ab0 100644
--- a/posthog/test/repo_invariants/test_pytest_module_collisions.py
+++ b/posthog/test/repo_invariants/test_pytest_module_collisions.py
@@ -72,7 +72,7 @@ CI_SESSIONS: dict[str, tuple[tuple[str, ...], tuple[str, ...]]] = {
"repo-invariants": (("posthog/test/repo_invariants",), ()),
"tool:hogli": (("tools/hogli/tests",), ()),
"tool:hogli-commands": (("tools/hogli-commands",), ()),
- "tool:owners": (("tools/owners/tests",), ()),
+ "package:owners": (("packages/owners-yaml/tests",), ()),
"tool:query-performance-ai": (("tools/query-performance-ai",), ()),
"tool:pr-approval-agent": (("tools/pr-approval-agent",), ()),
"tool:dependency-detection": (("bin/test",), ()),
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 7ead4423cb5f..155a5452d08e 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -161,9 +161,9 @@ Engineering-specific decisions. Product-level decisions live in README → Locke
- **Bot detection, defined once:** `handle.endswith("[bot]") OR handle in KNOWN_BOT_HANDLES`. Hardcoded allowlist; per-team config deferred.
- **Bots and drafts excluded by default** in throughput / cycle-time reads; first-class in bot-impact analysis, so never strip them at the substrate.
- **Time to merge** = `open_to_merge_seconds` = `merged_at - created_at`, coarse (draft + ready combined). The precise companion is `ready_to_merge_seconds` = `merged_at` minus the last observed `ready_for_review` issue event (only the last draft/ready switch counts; a draft can't merge), falling back to `created_at` for a merged PR verifiably never drafted (no transition rows and its whole open-to-merge span inside the observed issue-event window, so the transitions can't merely be unsynced). NULL means "not observed", never zero: GitHub caps the issue-events history walk, so coverage grows forward from the first sync.
-- **Flake ownership is stamped at CI emission time, never mirrored server-side.** The CI emitter stamps `test.owner_team` through `posthog_owners` (the repo's distributed `owners.yaml` files, with `products/*/product.yaml` as an alias; first listed team owner, individual `@handle` owners skipped); unstamped spans aggregate as the first-class team `unowned`. Capture-time truth is intentional: a test belongs to whoever owned it when it flaked.
+- **Flake ownership is stamped at CI emission time, never mirrored server-side.** The CI emitter stamps `test.owner_team` through `owners_yaml` (the repo's distributed `owners.yaml` files, with `products/*/product.yaml` as an alias; first listed team owner, individual `@handle` owners skipped); unstamped spans aggregate as the first-class team `unowned`. Capture-time truth is intentional: a test belongs to whoever owned it when it flaked.
- **Quarantine debt ownership is resolved from the repository as it stands**, by the same resolver over the ownership files fetched from the default branch. A deliberate split from the rule above: a quarantine outlives the CI signal that would name a team, so reading standing debt off the stamps attributes most of it to nobody. A test the repository cannot place, or whose path no team claims, is `unowned`; a failed read leaves the whole board `unowned` and says so through `owners_resolved`, rather than attributing part of it. Trunk's own `codeowners` field is not the shortcut it looks like: it is empty for all but a handful of tests, because this repo keeps CODEOWNERS deliberately sparse. Team surfaces stay team-level: author→team joins (via the `team_members` snapshot) produce aggregates only, never per-member figures or cross-team rankings; a slug mismatch yields an empty series, never another team's data.
-- **The test-count denominator is a daily census event, never derived from spans.** Spans are signal-only (sub-threshold passes are not emitted), so a Celery task fetches each connected repo's tarball once a day, resolves every test file through `posthog_owners`, and captures one `eng_analytics_test_census` event per owning team into the team's own project. The roster joins census and merged-PR context by slug and adds census-only rows (zero signal, null `last_seen_at`) so an all-green team stays visible.
+- **The test-count denominator is a daily census event, never derived from spans.** Spans are signal-only (sub-threshold passes are not emitted), so a Celery task fetches each connected repo's tarball once a day, resolves every test file through `owners_yaml`, and captures one `eng_analytics_test_census` event per owning team into the team's own project. The roster joins census and merged-PR context by slug and adds census-only rows (zero signal, null `last_seen_at`) so an all-green team stays visible.
- **No provider abstraction until a second code host lands.** GitHub-isms stay below the builder boundary, canonical types above it; that seam makes extracting a `CodeHostProvider` Protocol mechanical.
## 7. Data sources
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index d272f73d591f..bdcb1d74de62 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -26,7 +26,7 @@ from dataclasses import field
from datetime import date, datetime
from enum import StrEnum
-from posthog_owners.schema import TeamEntry
+from owners_yaml.schema import TeamEntry
from pydantic.dataclasses import dataclass
from posthog.hogql.database.models import FieldOrTable
diff --git a/products/engineering_analytics/backend/logic/census.py b/products/engineering_analytics/backend/logic/census.py
index 1dba964aa14b..97177d39fe88 100644
--- a/products/engineering_analytics/backend/logic/census.py
+++ b/products/engineering_analytics/backend/logic/census.py
@@ -12,7 +12,7 @@ import posixpath
from contextlib import closing
from pathlib import Path
-from posthog_owners import TeamTestCensus, census, runner_for_path
+from owners_yaml import TeamTestCensus, census, runner_for_path
from posthog.api.capture import capture_batch_internal
from posthog.egress.github.transport import github_request, raise_if_github_rate_limited
diff --git a/products/engineering_analytics/backend/logic/ownership.py b/products/engineering_analytics/backend/logic/ownership.py
index 8e53f5eb300e..9c1b491592a2 100644
--- a/products/engineering_analytics/backend/logic/ownership.py
+++ b/products/engineering_analytics/backend/logic/ownership.py
@@ -16,9 +16,9 @@ from django.core.cache import cache
import requests
import structlog
-from posthog_owners import OwnershipSource, OwnersResolver
-from posthog_owners.matcher import normalize_path
-from posthog_owners.resolver import teams_registry
+from owners_yaml import OwnershipSource, OwnersResolver
+from owners_yaml.matcher import normalize_path
+from owners_yaml.resolver import teams_registry
from requests.adapters import HTTPAdapter
from posthog.dataclasses import frozen
diff --git a/products/engineering_analytics/backend/logic/queries/team_ci_health.py b/products/engineering_analytics/backend/logic/queries/team_ci_health.py
index 12b2a08e8606..3ad02dc169bc 100644
--- a/products/engineering_analytics/backend/logic/queries/team_ci_health.py
+++ b/products/engineering_analytics/backend/logic/queries/team_ci_health.py
@@ -1,7 +1,7 @@
"""HogQL rollups of per-test CI spans by owning team.
Ownership is stamped on the spans at emission time: the CI reporter resolves each test's
-file path through ``posthog_owners`` (the repo's distributed ``owners.yaml`` files, with
+file path through ``owners_yaml`` (the repo's distributed ``owners.yaml`` files, with
``products/*/product.yaml`` as an alias) and sets ``test.owner_team``, so no server-side
ownership map exists. Spans without a stamp
aggregate under the literal team ``'unowned'``, an honest first-class bucket that surfaces
diff --git a/products/engineering_analytics/backend/tests/test_census.py b/products/engineering_analytics/backend/tests/test_census.py
index ece87d16ec4a..6d7b0f236056 100644
--- a/products/engineering_analytics/backend/tests/test_census.py
+++ b/products/engineering_analytics/backend/tests/test_census.py
@@ -4,7 +4,7 @@ from types import SimpleNamespace
from unittest.mock import patch
-from posthog_owners import TeamTestCensus
+from owners_yaml import TeamTestCensus
from products.engineering_analytics.backend.logic.census import CENSUS_EVENT, collect_repo_census, emit_census_events
diff --git a/products/stamphog/backend/logic/channel_resolution.py b/products/stamphog/backend/logic/channel_resolution.py
index 8e1271c95822..9aa9c9b2edf1 100644
--- a/products/stamphog/backend/logic/channel_resolution.py
+++ b/products/stamphog/backend/logic/channel_resolution.py
@@ -7,7 +7,7 @@ morning's digest follows it.
The order is proximity, not alphabet. For an audience's merges that came from repository R:
1. A ``repo:`` audience takes the channel R declared under ``digest:`` in ``.stamphog/policy.yml``.
-2. A team slug takes R's own root ``owners.yaml`` registry, read through ``posthog_owners``. A
+2. A team slug takes R's own root ``owners.yaml`` registry, read through ``owners_yaml``. A
repository that carries a registry answers for its own pull requests completely, including by
omission: a registry lists the teams whose derived name is wrong, so a slug missing from it
means "the derived name is right" rather than "no opinion".
@@ -32,8 +32,8 @@ from django.db import router
from django.db.models import Q
import structlog
-from posthog_owners.resolver import Purpose, TeamChannel, team_channel, teams_registry
-from posthog_owners.schema import Producer, TeamEntry
+from owners_yaml.resolver import Purpose, TeamChannel, team_channel, teams_registry
+from owners_yaml.schema import Producer, TeamEntry
from posthog.dataclasses import frozen
from posthog.models.integration import Integration
@@ -47,7 +47,7 @@ from .github_client import StamphogGitHubClient
logger = structlog.get_logger(__name__)
-# The distributed-ownership registry lives only in the repo-root file (posthog_owners.schema).
+# The distributed-ownership registry lives only in the repo-root file (owners_yaml.schema).
_OWNERS_FILE_PATH = "owners.yaml"
# The digest is automation, so it asks the registry where automation posts rather than where the
@@ -232,7 +232,7 @@ def resolve_destination(context: RoutingContext, audience_key: str, repository:
if _silenced(answer):
logger.info("stamphog_routing_silenced_by_config", audience_key=audience_key, repository=repository)
return None
- if answer.declared:
+ if answer.declared and answer.channel is not None:
# A registry entry can name a channel for a team the declaring repo does not own, so the
# shared-channel guard stays on: an externally shared match here leaves the workspace.
return _match(context, answer.channel, ChannelResolutionSource.OWNERS_CONTACT, allow_shared=False)
diff --git a/products/stamphog/backend/temporal/activities.py b/products/stamphog/backend/temporal/activities.py
index e96a3fda79b3..1ed9831ebfc4 100644
--- a/products/stamphog/backend/temporal/activities.py
+++ b/products/stamphog/backend/temporal/activities.py
@@ -1612,20 +1612,20 @@ def _ship_engine(sandbox: SandboxBase) -> None:
def _ship_owners_package(sandbox: SandboxBase) -> None:
- """Ship the posthog-owners resolver package the engine's ownership format imports.
+ """Ship the owners-yaml resolver package the engine's ownership format imports.
The default policy declares a ``hogli-resolver`` ownership source, and gates.py imports
- ``posthog_owners`` from ``tools/owners`` next to the engine dir in the sandbox. Same trust
+ ``owners_yaml`` from ``tools/owners`` next to the engine dir in the sandbox. Same trust
posture as the engine: always our copy, which overwrites whatever the PR head carried at that
path. Repos without
owners.yaml/product.yaml files simply resolve to "no ownership-source match".
"""
- # Repo root rather than a sibling of the engine. posthog_owners is a shared tool, so it stays
- # under tools/ while the engine lives in the product.
- package_dir = Path(__file__).resolve().parents[4] / "tools" / "owners" / "posthog_owners"
+ # Repo root rather than a sibling of the engine. owners_yaml is a distribution the production
+ # venv installs, so it lives under packages/ while the engine lives in the product.
+ package_dir = Path(__file__).resolve().parents[4] / "packages" / "owners-yaml" / "owners_yaml"
if not package_dir.is_dir():
raise RuntimeError(f"owners package source dir not found: {package_dir}")
- target = f"{STAMPHOG_SANDBOX_OWNERS_DIR}/posthog_owners"
+ target = f"{STAMPHOG_SANDBOX_OWNERS_DIR}/owners_yaml"
quoted = shlex.quote(STAMPHOG_SANDBOX_OWNERS_DIR)
sandbox.execute(f"rm -rf {quoted} && mkdir -p {shlex.quote(target)}", timeout_seconds=30)
for path in sorted(package_dir.glob("*.py")):
diff --git a/products/stamphog/backend/temporal/constants.py b/products/stamphog/backend/temporal/constants.py
index 6a77dce914e9..2e42228ed41a 100644
--- a/products/stamphog/backend/temporal/constants.py
+++ b/products/stamphog/backend/temporal/constants.py
@@ -43,8 +43,10 @@ STAMPHOG_BOT_REVIEW_MAX_POLLS = 10 # ~300s budget at 30s per poll, matching the
# bot-labeler-skip) to the ReviewHog trigger endpoint. Kept here so the activity references the same
# scalar the workflow gates on.
STAMPHOG_REVIEWHOG_LABEL = "reviewhog"
-# The posthog-owners resolver package, expected by the engine as a sibling of its own dir
-# (gates.py resolves `../owners` for the hogli-resolver ownership format).
+# The owners-yaml resolver package, expected by the engine as a sibling of its own dir
+# (gates.py resolves `../owners` for the hogli-resolver ownership format). This stays a sibling of
+# the engine dir although the monorepo source moved to packages/owners-yaml, because downstream repos
+# vendor the engine with the resolver beside it and the engine resolves the two layouts by offset.
STAMPHOG_SANDBOX_OWNERS_DIR = f"{STAMPHOG_SANDBOX_REPO_DIR}/tools/owners"
STAMPHOG_SANDBOX_CONTEXT_PATH = f"{STAMPHOG_SANDBOX_REPO_DIR}/.stamphog_review_context.json"
diff --git a/products/stamphog/backend/tests/test_digest.py b/products/stamphog/backend/tests/test_digest.py
index 237050348b27..31227cbc7ec3 100644
--- a/products/stamphog/backend/tests/test_digest.py
+++ b/products/stamphog/backend/tests/test_digest.py
@@ -12,8 +12,8 @@ from django.db.models import QuerySet
from django.test import override_settings
from django.utils import timezone
+from owners_yaml.schema import TeamEntry
from parameterized import parameterized
-from posthog_owners.schema import TeamEntry
from slack_sdk.errors import SlackApiError
from structlog.testing import capture_logs
diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.py
index fac6df90154c..56edc8fee251 100644
--- a/products/stamphog/backend/tests/test_integration.py
+++ b/products/stamphog/backend/tests/test_integration.py
@@ -1712,7 +1712,7 @@ def test_unreadable_owners_registry_posts_nothing(team, stamphog_chain: Stamphog
assert fakes.FakeSlackIntegration.posted_messages == []
-# posthog_owners validates the whole document, so the registry has to arrive inside a real one.
+# owners_yaml validates the whole document, so the registry has to arrive inside a real one.
_OWNERS_YAML_HEAD = "version: 1\nowners: []\n"
diff --git a/products/stamphog/packages/pr-approval-agent/README.md b/products/stamphog/packages/pr-approval-agent/README.md
index d516289220f0..f3e1d9d2b2a4 100644
--- a/products/stamphog/packages/pr-approval-agent/README.md
+++ b/products/stamphog/packages/pr-approval-agent/README.md
@@ -349,6 +349,9 @@ A retry against the now-classified head commit reviews it properly.
Ownership context for the LLM, not a hard gate.
The sources are declared in `policy.yml` under `ownership:` and read from the checked-out tree: a `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.
+A repo that vendors this directory does not need to vendor the resolver as well: add a pinned `owners-yaml` from PyPI to the script dependencies of `review_pr.py`.
+Pin the version, because a new release can change how paths resolve.
+In this monorepo and in the review sandbox, the engine uses the resolver that ships beside it, so the two always match.
Cross-team typo, test and 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.
diff --git a/products/stamphog/packages/pr-approval-agent/gates.py b/products/stamphog/packages/pr-approval-agent/gates.py
index 95830d35d6b8..cc7c94892711 100644
--- a/products/stamphog/packages/pr-approval-agent/gates.py
+++ b/products/stamphog/packages/pr-approval-agent/gates.py
@@ -20,30 +20,38 @@ from typing import TYPE_CHECKING, Protocol
from policy import OwnershipSource, load_policy
if TYPE_CHECKING:
- from posthog_owners.resolver import OwnersResolver
+ from owners_yaml.resolver import OwnersResolver
-# The resolver lives in the posthog-owners package. This script's uv env does not install it, so the
+
+# The resolver lives in the owners-yaml package. This script's uv env does not install it, so the
# code puts it on the path and imports it as a library. It needs only pyyaml, which review_pr.py
# declares. _build_hogli_resolver defers the import, because downstream repos vendor this directory
-# (plus .stamphog/) without tools/owners. A module-level import would disable their stamphog copy
+# without the resolver package. A module-level import would disable their stamphog copy
# before any gate runs. The package is only necessary once a policy declares a hogli-resolver
# ownership source.
#
# There are two candidate locations, and the code puts only the FIRST one that exists on the path.
-# The sibling `owners/` covers two cases: the vendored layout that downstream repos copy, and the
-# review sandbox, which receives this directory at <checkout>/tools/pr-approval-agent with
-# tools/owners beside it. The sandbox therefore never reaches the second entry. The second entry
-# covers a run from this repo, where the engine's own home is under products/stamphog/packages/.
+# The first entry covers a run from this repo, where the resolver is at packages/owners-yaml and the
+# engine's own home is under products/stamphog/packages/. The sibling `owners/` covers two cases:
+# the vendored layout that downstream repos copy, and the review sandbox, which receives this
+# directory at <checkout>/tools/pr-approval-agent with the resolver beside it at
+# <checkout>/tools/owners. Neither of those layouts has a first entry to find, so they fall through
+# to the sibling.
#
# Both entries are fixed offsets from this file, and not a discovered repo root.
# `policy.repo_root()` walks up to find a `.stamphog/` directory, and the PR head is untrusted. A PR
# that adds `tools/.stamphog/` would move that root and point this code at a directory that the PR
# controls. The sandbox would then import that directory, and the sandbox holds the run's LLM
# credentials.
-_OWNERS_PKG_CANDIDATES = (
- Path(__file__).resolve().parents[1] / "owners",
- Path(__file__).resolve().parents[4] / "tools" / "owners",
-)
+def _owners_pkg_candidates(engine_file: Path) -> tuple[Path, ...]:
+ engine_dir = engine_file.resolve().parent
+ # engine_dir is products/stamphog/packages/pr-approval-agent in this repo, so the repo root is
+ # four levels up. In the sandbox and in a vendored copy that offset points outside the tree and
+ # finds nothing, which is what makes the sibling the answer there.
+ return (engine_dir.parents[3] / "packages" / "owners-yaml", engine_dir.parent / "owners")
+
+
+_OWNERS_PKG_CANDIDATES = _owners_pkg_candidates(Path(__file__))
# ── Dependency ecosystems ────────────────────────────────────────
#
@@ -209,11 +217,11 @@ def _build_hogli_resolver(repo_root: Path, source: OwnershipSource) -> _HogliRes
try:
# Deferred (PLC0415) because the package is absent in vendored copies and is needed only
# once a policy declares this ownership format.
- from posthog_owners.resolver import OwnersResolver # noqa: PLC0415
+ from owners_yaml.resolver import OwnersResolver # noqa: PLC0415
except ImportError as exc:
raise RuntimeError(
- "ownership format 'hogli-resolver' requires the posthog-owners package: "
- "vendor tools/owners alongside this directory, or drop the "
+ "ownership format 'hogli-resolver' requires the owners-yaml package: "
+ "add a pinned owners-yaml from PyPI to this script's dependencies, 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`)
@@ -259,7 +267,7 @@ TEAM_FILE_SAMPLE = 10
# rather than whether code is safe to approve. A bare `generated/` match would also catch
# hand-editable directories elsewhere in the tree, which is the case AGENTS.md warns about.
#
-# The ownership registry has a `status: generated` value (posthog_owners.schema) that would be the
+# The ownership registry has a `status: generated` value (owners_yaml.schema) that would be the
# right home for this, but no owners.yaml or product.yaml declares it today, so reading it would
# exclude nothing.
_GENERATED_PATH_RE = re.compile(r"^products/[^/]+/frontend/generated/")
diff --git a/products/stamphog/packages/pr-approval-agent/test_gates.py b/products/stamphog/packages/pr-approval-agent/test_gates.py
index 0725840e1326..4a057832643b 100644
--- a/products/stamphog/packages/pr-approval-agent/test_gates.py
+++ b/products/stamphog/packages/pr-approval-agent/test_gates.py
@@ -527,6 +527,7 @@ def test_resolver_owner_normalization(
expected_individuals: list[str],
expected_owned: int,
) -> None:
+ (tmp_path / "owners.yaml").write_text("version: 1\nowners: []\nalias_files: [product.yaml]\n")
product_dir = tmp_path / "products" / "foo"
product_dir.mkdir(parents=True)
(product_dir / "product.yaml").write_text(owners_yaml)
@@ -541,6 +542,7 @@ def test_resolver_owner_normalization(
def test_ownership_cross_team_and_unowned(tmp_path: Path) -> None:
+ (tmp_path / "owners.yaml").write_text("version: 1\nowners: []\nalias_files: [product.yaml]\n")
product_dir = tmp_path / "products" / "foo"
product_dir.mkdir(parents=True)
(product_dir / "product.yaml").write_text("owners:\n - team-a\n - team-b\n")
@@ -561,6 +563,7 @@ def test_ownership_counts_a_products_generated_directory_and_nothing_wider(tmp_p
# changes anywhere in the repo, so a team owning only those was not touched by the change. The
# match names one directory shape on purpose: AGENTS.md rules out a general harmless-file rule,
# and a bare `generated/` match would catch hand-editable code elsewhere in the tree.
+ (tmp_path / "owners.yaml").write_text("version: 1\nowners: []\nalias_files: [product.yaml]\n")
product_dir = tmp_path / "products" / "foo"
product_dir.mkdir(parents=True)
(product_dir / "product.yaml").write_text("owners:\n - team-a\n")
@@ -590,5 +593,30 @@ def test_owners_candidates_are_fixed_offsets_from_this_file() -> None:
# controls. The sandbox would then import that directory, and the sandbox holds the run's LLM
# credentials. Both candidates must stay fixed offsets from the engine's own file.
engine_dir = Path(gates.__file__).resolve().parent
- assert gates._OWNERS_PKG_CANDIDATES[0] == engine_dir.parent / "owners"
- assert gates._OWNERS_PKG_CANDIDATES[1] == engine_dir.parents[3] / "tools" / "owners"
+ assert gates._OWNERS_PKG_CANDIDATES[0] == engine_dir.parents[3] / "packages" / "owners-yaml"
+ assert gates._OWNERS_PKG_CANDIDATES[1] == engine_dir.parent / "owners"
+
+
+ "engine_file, resolver_dir",
+ [
+ pytest.param(
+ "root/products/stamphog/packages/pr-approval-agent/gates.py",
+ "root/packages/owners-yaml",
+ id="monorepo",
+ ),
+ pytest.param("root/tools/pr-approval-agent/gates.py", "root/tools/owners", id="sandbox-and-vendored"),
+ ],
+)
+def test_the_owners_package_is_found_in_both_engine_layouts(
+ tmp_path: Path, engine_file: str, resolver_dir: str
+) -> None:
+ expected = tmp_path / resolver_dir
+ (expected / "owners_yaml").mkdir(parents=True)
+ engine_path = tmp_path / engine_file
+ engine_path.parent.mkdir(parents=True)
+ engine_path.touch()
+
+ found = [candidate for candidate in gates._owners_pkg_candidates(engine_path) if candidate.is_dir()]
+
+ assert found == [expected.resolve()]
diff --git a/products/visual_review/backend/logic/debt_digest.py b/products/visual_review/backend/logic/debt_digest.py
index 2bade52746f5..b3aa6804fba6 100644
--- a/products/visual_review/backend/logic/debt_digest.py
+++ b/products/visual_review/backend/logic/debt_digest.py
@@ -46,8 +46,8 @@ from django.conf import settings
from django.utils import timezone
import structlog
-from posthog_owners.resolver import Purpose, team_channel
-from posthog_owners.schema import Producer, TeamEntry
+from owners_yaml.resolver import Purpose, team_channel
+from owners_yaml.schema import Producer, TeamEntry
from posthog.comment.formatting import escape_slack_mrkdwn
from posthog.dataclasses import frozen
diff --git a/products/visual_review/backend/tests/logic/test_debt_digest.py b/products/visual_review/backend/tests/logic/test_debt_digest.py
index 03c0507c428d..2b1692bf7ee9 100644
--- a/products/visual_review/backend/tests/logic/test_debt_digest.py
+++ b/products/visual_review/backend/tests/logic/test_debt_digest.py
@@ -8,7 +8,7 @@ from unittest.mock import MagicMock, patch
from django.conf import settings
from django.utils import timezone
-from posthog_owners.schema import TeamEntry
+from owners_yaml.schema import TeamEntry
from posthog.models.team.team import Team
from posthog.team_notifications.slack import (
diff --git a/pyproject.toml b/pyproject.toml
index 3121ba459fce..dc97d29780cf 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -150,7 +150,7 @@ dependencies = [
# Distributed owners.yaml resolver. A runtime dependency, not just tooling: stamphog's digest
# reads a repo's team -> Slack channel registry through it (products/stamphog/backend/logic/
# channel_resolution.py). Adds no third-party code — its own deps, pyyaml and click, are here.
- "posthog-owners",
+ "owners-yaml",
"umap-learn~=0.5.0",
"tbb==2022.3.1; sys_platform == 'linux' and platform_machine == 'x86_64'",
"whitenoise~=6.10.0",
@@ -311,11 +311,11 @@ exclude-newer = "7 days"
exclude-newer-package = { granian = false, hogql-parser = false, hogql-parser-rs = false, deltalite = false, posthoganalytics = false, pixelhog = false, django = false, modal = false, posthog-hogland = false, google-ads = false }
[tool.uv.workspace]
-members = ["tools/hogli", "tools/owners"]
+members = ["tools/hogli", "packages/owners-yaml"]
[tool.uv.sources]
hogli = { workspace = true }
-posthog-owners = { workspace = true }
+owners-yaml = { 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).
@@ -495,7 +495,10 @@ exclude_gitignore = true
# (both resolve to top-level module "conftest")
# rust/deltalite/python: pytest suite for the maturin-built extension; nothing Django
# imports it and it has its own CI (ci-deltalite-python.yml).
-exclude = ["^(bin/.*|tools/.*|rust/deltalite/python/.*|products/desktop/.*|products/stamphog/packages/.*|products/[^/]+/skills/[^/]+/scripts/.*|gunicorn\\.config\\.py|manage\\.py|conftest\\.py)$"]
+# packages/owners-yaml: a standalone distribution that must build and run with no Django. This config
+# loads the Django and DRF plugins and the app's settings, so it is the wrong checker for it. ty
+# covers it repo-wide instead, and ci-python builds and exercises the wheel in an empty venv.
+exclude = ["^(bin/.*|tools/.*|packages/owners-yaml/.*|rust/deltalite/python/.*|products/desktop/.*|products/stamphog/packages/.*|products/[^/]+/skills/[^/]+/scripts/.*|gunicorn\\.config\\.py|manage\\.py|conftest\\.py)$"]
[[tool.mypy.overrides]]
module = "bin.*"
@@ -552,9 +555,19 @@ exclude = [
# Complements tach (inter-module boundaries) with intra-product enforcement.
[tool.importlinter]
-root_packages = ["products"]
+root_packages = ["products", "owners_yaml"]
include_external_packages = true
+# A Python distribution under packages/ is a leaf: it must install and run outside the
+# monorepo venv, so it can import nothing from the app. tach resolves a uv distribution as
+# third-party and cannot police that boundary. import-linter resolves by installed import
+# name, so it can.
+[[tool.importlinter.contracts]]
+name = "packages/owners-yaml is a leaf"
+type = "forbidden"
+source_modules = ["owners_yaml"]
+forbidden_modules = ["posthog", "ee", "products", "common", "django", "rest_framework"]
+
# Presentation must only reach product internals through the facade.
# Forbid all backend imports, then allowlist facade + self-imports.
# This catches any new internal modules (cache.py, helpers.py, etc.)
diff --git a/pytest.ini b/pytest.ini
index a44e5465bf09..4a0a0de20eaf 100644
--- a/pytest.ini
+++ b/pytest.ini
@@ -1,5 +1,5 @@
[pytest]
-pythonpath = . common tools/hogli-commands tools/owners tools/query-performance-ai
+pythonpath = . common tools/hogli-commands tools/query-performance-ai
env =
DEBUG=1
TEST=1
@@ -22,7 +22,7 @@ junit_family = xunit1
# (several full gc.collect passes over the whole heap, seconds per session at our heap sizes)
# during cleanup to surface __del__/thread exceptions as warnings - but with -p no:warnings
# those warnings can never escalate to failures here, so the collections are pure teardown cost
-addopts = -p no:warnings -p no:tach -p no:langsmith_plugin -p no:faker -p no:unraisableexception -p no:threadexception -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-ai --ignore=products/desktop --ignore=products/stamphog/packages
+addopts = -p no:warnings -p no:tach -p no:langsmith_plugin -p no:faker -p no:unraisableexception -p no:threadexception -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=packages/owners-yaml --ignore=tools/traffic-sim --ignore=tools/query-performance-ai --ignore=products/desktop --ignore=products/stamphog/packages
markers =
ee
diff --git a/tools/hogli-commands/hogli_commands/product/gh.py b/tools/hogli-commands/hogli_commands/product/gh.py
index 5743c4fbaf7c..bd59268dbdaf 100644
--- a/tools/hogli-commands/hogli_commands/product/gh.py
+++ b/tools/hogli-commands/hogli_commands/product/gh.py
@@ -2,53 +2,21 @@
from __future__ import annotations
-import shutil
-import subprocess
+from owners_yaml.github import GitHubLookupError, GitHubOrg
-_team_slugs: set[str] | None = None
-_fetch_err: str = ""
-_fetch_attempted: bool = False
-
-
-_ORG = "PostHog"
+_ORG = GitHubOrg("PostHog")
def get_team_slugs() -> tuple[set[str] | None, str]:
"""Fetch GitHub team slugs visible in the PostHog org. Cached after the first call.
- Uses ``/orgs/{org}/teams`` (requires ``members: read``) rather than the
- repo-collaborator endpoint ``/repos/{repo}/teams``. The repo endpoint would
- be the tighter check semantically (the reviewer assignment API only accepts
- repo collaborator teams), but the assign-reviewers GitHub App doesn't have
- the scope for it. The "team exists in org but lacks repo access" gap is
- covered defensively by assign-reviewers.js's 422 fallback, which retries
- each team individually and logs the bad slugs.
+ The org lookup is broader than repo access. assign-reviewers.js covers a team that exists
+ in the org but lacks repo access with its 422 fallback, which retries each team individually
+ and logs the bad slugs.
Returns ``(slugs, error_message)``. ``slugs`` is ``None`` when the fetch failed.
"""
- global _team_slugs, _fetch_err, _fetch_attempted
-
- if _fetch_attempted:
- return _team_slugs, _fetch_err
-
- _fetch_attempted = True
-
- if not shutil.which("gh"):
- _fetch_err = "gh CLI not found — install it to validate owner team slugs"
- return None, _fetch_err
-
try:
- result = subprocess.run(
- ["gh", "api", f"orgs/{_ORG}/teams", "--paginate", "--jq", ".[].slug"],
- capture_output=True,
- text=True,
- timeout=15,
- )
- if result.returncode == 0 and result.stdout.strip():
- _team_slugs = set(result.stdout.strip().split("\n"))
- return _team_slugs, ""
- _fetch_err = f"gh api failed (rc={result.returncode}): {result.stderr.strip()}"
- return None, _fetch_err
- except subprocess.TimeoutExpired:
- _fetch_err = "gh api timed out after 15s"
- return None, _fetch_err
+ return _ORG.team_slugs(), ""
+ except GitHubLookupError as exc:
+ return None, str(exc)
diff --git a/tools/hogli-commands/hogli_commands/tests/test_checks.py b/tools/hogli-commands/hogli_commands/tests/test_checks.py
index a785580d0172..e35d69a99455 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_checks.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_checks.py
@@ -1104,25 +1104,19 @@ class TestProductYamlOwnersCheck:
def test_invalid_slug_reported(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
ctx = _make_yaml_ctx(tmp_path, "name: My product\nowners:\n - team-nonexistent\n")
- monkeypatch.setattr(gh_module, "_fetch_attempted", True)
- monkeypatch.setattr(gh_module, "_team_slugs", {"team-real"})
- monkeypatch.setattr(gh_module, "_fetch_err", "")
+ monkeypatch.setattr(gh_module, "get_team_slugs", lambda: ({"team-real"}, ""))
result = owners_check.run(ctx)
assert any("team-nonexistent" in i for i in result.issues)
def test_valid_slug_passes(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
ctx = _make_yaml_ctx(tmp_path, "name: My product\nowners:\n - team-real\n")
- monkeypatch.setattr(gh_module, "_fetch_attempted", True)
- monkeypatch.setattr(gh_module, "_team_slugs", {"team-real"})
- monkeypatch.setattr(gh_module, "_fetch_err", "")
+ monkeypatch.setattr(gh_module, "get_team_slugs", lambda: ({"team-real"}, ""))
result = owners_check.run(ctx)
assert not result.issues
def test_gh_unavailable_is_error(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
ctx = _make_yaml_ctx(tmp_path, "name: My product\nowners:\n - team-foo\n")
- monkeypatch.setattr(gh_module, "_fetch_attempted", True)
- monkeypatch.setattr(gh_module, "_team_slugs", None)
- monkeypatch.setattr(gh_module, "_fetch_err", "gh CLI not found")
+ monkeypatch.setattr(gh_module, "get_team_slugs", lambda: (None, "gh CLI not found"))
result = owners_check.run(ctx)
assert result.issues
assert any("gh CLI" in i for i in result.issues)
diff --git a/tools/owners/README.md b/tools/owners/README.md
deleted file mode 100644
index 26d9c8e13970..000000000000
--- a/tools/owners/README.md
+++ /dev/null
@@ -1,64 +0,0 @@
-# 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.
-
-## CODEOWNERS projection
-
-Some tools read CODEOWNERS and nothing else. `owners:codeowners` projects the map into that format
-so they can attribute a file to a team:
-
-```bash
-hogli owners:codeowners # to stdout
-hogli owners:codeowners -o /tmp/x/CODEOWNERS
-```
-
-It covers test files only, because the consumer this exists for (Trunk Flaky Tests) looks up nothing
-else. A test file is spelled the way the runner that ran it writes the JUnit `file` attribute, which
-is relative to that runner's working directory, so a file can appear under more than one rule. A
-spelling two teams would both claim is dropped rather than guessed. An unowned file gets a rule with
-no owner after the pattern, which keeps an ancestor rule from claiming it.
-
-This never writes `.github/CODEOWNERS`. That file carries GitHub's blocking-approval semantics, is
-hand-maintained, and is not part of the resolver's walk.
-
-CI regenerates the projection per upload in `.github/scripts/trunk-codeowners.sh`, so the consumer
-never reads a stale map.
-
-## 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`).
-
-### From a consumer that is not Python
-
-`python -m posthog_owners` answers the same question as JSON, with no click and no project sync. Stdlib plus pyyaml is enough.
-It reads repo-relative paths from stdin or argv and writes a single JSON object keyed by path:
-
-```bash
-echo "posthog/models/team.py" | PYTHONPATH=/fetched/tools/owners python3 -m posthog_owners --repo-root /fetched
-```
-
-`PYTHONPATH` names the directory holding the `posthog_owners` package. `--repo-root` names the tree holding the ownership files; the example fetched both into one scratch directory, but they are independent.
-Any Python 3.10+ interpreter with pyyaml works, so `uv run --no-project --with pyyaml python` is enough if you would rather not install it.
-
-```json
-{
- "posthog/models/team.py": {
- "owners": ["team-x"],
- "status": "active",
- "slack": "#team-x",
- "source": "posthog/owners.yaml"
- }
-}
-```
-
-Without `--repo-root` the resolver locates the repo with `git rev-parse`, so it needs a real worktree.
-Pass the flag when the ownership files sit in a directory that is not one: a sparse fetch, an export, or a scratch copy of just the `owners.yaml` / `product.yaml` files.
-Add `--purpose notifications` to resolve `slack` to each team's automation channel instead of its people channel.
diff --git a/tools/owners/posthog_owners/__init__.py b/tools/owners/posthog_owners/__init__.py
deleted file mode 100644
index ffc0ccf4f75e..000000000000
--- a/tools/owners/posthog_owners/__init__.py
+++ /dev/null
@@ -1,24 +0,0 @@
-"""Distributed ownership: owners.yaml matcher, schema, resolver, and CLI."""
-
-from .census import TeamTestCensus, census, first_team_owner, runner_for_path
-from .codeowners import CodeownersProjection, owner_handle, package_dirs_from, project, spellings
-from .matcher import compile_pattern, path_matches_pattern
-from .resolver import DiskSource, OwnershipSource, OwnersResolver, Resolution
-
-__all__ = [
- "CodeownersProjection",
- "DiskSource",
- "OwnersResolver",
- "OwnershipSource",
- "Resolution",
- "TeamTestCensus",
- "census",
- "compile_pattern",
- "first_team_owner",
- "owner_handle",
- "package_dirs_from",
- "path_matches_pattern",
- "project",
- "runner_for_path",
- "spellings",
-]
diff --git a/uv.lock b/uv.lock
index 57ea1b9daac1..20078527909e 100644
--- a/uv.lock
+++ b/uv.lock
@@ -29,8 +29,8 @@ posthoganalytics = false
[manifest]
members = [
"hogli",
+ "owners-yaml",
"posthog",
- "posthog-owners",
]
[[manifest.dependency-metadata]]
@@ -5236,6 +5236,28 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/55/8b/5ab7257531a5d830fc8000c476e63c935488d74609b50f9384a643ec0a62/outcome-1.3.0.post0-py2.py3-none-any.whl", hash = "sha256:e771c5ce06d1415e356078d3bdd68523f284b4ce5419828922b6871e65eda82b", size = 10692, upload-time = "2023-10-26T04:26:02.532Z" },
]
+[[package]]
+name = "owners-yaml"
+version = "0.2.0"
+source = { editable = "packages/owners-yaml" }
+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 = "packaging"
version = "24.1"
@@ -5651,6 +5673,7 @@ dependencies = [
{ name = "opentelemetry-sdk" },
{ name = "orjson" },
{ name = "ormsgpack" },
+ { name = "owners-yaml" },
{ name = "pandas" },
{ name = "paramiko" },
{ name = "pillow" },
@@ -5658,7 +5681,6 @@ dependencies = [
{ name = "playwright" },
{ name = "polars" },
{ name = "posthog-hogland" },
- { name = "posthog-owners" },
{ name = "posthoganalytics" },
{ name = "protobuf" },
{ name = "psycopg", extra = ["binary"] },
@@ -5934,6 +5956,7 @@ requires-dist = [
{ name = "opentelemetry-sdk", specifier = "==1.33.1" },
{ name = "orjson", specifier = "==3.11.9" },
{ name = "ormsgpack", specifier = "~=1.12" },
+ { name = "owners-yaml", editable = "packages/owners-yaml" },
{ name = "pandas", specifier = "~=2.2.2" },
{ name = "paramiko", specifier = "~=3.5.0" },
{ name = "pillow", specifier = "==12.3.0" },
@@ -5941,7 +5964,6 @@ requires-dist = [
{ name = "playwright", specifier = "~=1.60.0" },
{ name = "polars", specifier = "==1.37.1" },
{ name = "posthog-hogland", specifier = "==0.4.1" },
- { name = "posthog-owners", editable = "tools/owners" },
{ name = "posthoganalytics", specifier = "==7.54.1" },
{ name = "protobuf", specifier = "~=5.29.6" },
{ name = "psycopg", extras = ["binary"], specifier = "==3.2.4" },
@@ -6098,28 +6120,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/35/2a/527ef6d0c3eee98b676bf5c9878c3010e749601210eb1b32dd99548b51b4/posthog_hogland-0.4.1-py3-none-any.whl", hash = "sha256:2bc2fd6bf4a710df8eaf4e5bfa1a4ffd8d29751eb13edc650b89bdcba045eaf2", size = 38357, upload-time = "2026-09-01T14:21:01.536Z" },
]
-[[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.54.1"