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): let owners.yaml name the owners of additions to a directory (#103848)

Julian Bez35d2f2034853
diff --git a/.agents/skills/establishing-code-ownership/SKILL.md b/.agents/skills/establishing-code-ownership/SKILL.md
index 80de31c5b8c4..2fd5993a81c7 100644
--- a/.agents/skills/establishing-code-ownership/SKILL.md
+++ b/.agents/skills/establishing-code-ownership/SKILL.md
@@ -27,7 +27,7 @@ No hogli/flox available? The dependency-light fallback needs only pyyaml: `git l
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).
+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, every matching rule applies in order, and each replaces only the fields it sets. `owners: null` means **unowned by design** (exempt from the coverage check), distinct from a directory with no file at all (genuinely unowned). `additions:` names the owners of _additions_ below a directory rather than the owners of the files in it (the consumer decides what counts as an addition); it never changes `owners`, and it adds up across the walk so a nested file cannot drop an ancestor's entry.
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 [packages/owners-yaml/README.md](../../../packages/owners-yaml/README.md)); that projection covers test files and is never `.github/CODEOWNERS`.
diff --git a/docs/internal/ownership-model-proposal.md b/docs/internal/ownership-model-proposal.md
index 298d9bc05931..3710b55bd3a0 100644
--- a/docs/internal/ownership-model-proposal.md
+++ b/docs/internal/ownership-model-proposal.md
@@ -90,9 +90,16 @@ status: active
# ancestor owners.yaml. false = Gerrit's `set noparent`.
inherit: true
-# Per-path overrides inside this directory, evaluated last-match-wins
-# *within this file only*. owners, status, and inherit can be overridden
-# per rule. `match` is one glob or a list of globs (each is its own
+# The owners of ADDITIONS below this directory, as opposed to the owners
+# of the files already in it. Names people only; what counts as an
+# addition, and whether a consumer asks them for review or blocks on
+# them, is that consumer's policy. Unlike every other field this one
+# adds up across the walk (see below).
+additions: [team-devex]
+
+# Per-path overrides inside this directory, *within this file only*.
+# Every matching rule applies in order, and each replaces only the fields
+# it sets: owners, status, or inherit. `match` is one glob or a list of globs (each is its own
# boundary — the list is just shorthand for repeating owners/status).
rules:
- match: 'generated/**'
@@ -112,6 +119,33 @@ version: 1
owners: team-ingestion
```
+### `additions:` — ownership of the namespace, not the file
+
+`owners:` answers "whose is this file".
+`additions:` answers a different question about the same path: "who owns what gets added here".
+The two are independent: each product under `products/` is owned by its team, while the owners of additions to `products/` can be one team.
+Much of the architecture guidance already has this shape as prose that nothing checks, such as reserving top-level `tools/`, `services/` and `packages/` for cross-product things.
+
+- **It adds up across the walk.** Every declaration on the walk applies, so a nested directory cannot drop the owners of additions that an ancestor names.
+ `owners:` stays nearest-wins, and `inherit: false` still cuts everything, additions included.
+- **Ask about the directory, not a file inside it.** The walk stops at the parent of the path it resolves, so resolving `products/newthing` matches a `match: '/*'` rule on `products/`, while resolving `products/newthing/product.yaml` does not.
+ `/*` therefore means "a direct child", and `/**` reaches any descendant.
+ A directory query also skips that directory's own ownership file, so a new product cannot remove itself from what its parent names.
+- **Newness and enforcement belong to the consumer.** The file only names the owners and where they apply. A consumer works out from the diff that a directory is new, treats a rename into the directory as an addition (git reports it as `R`, not `A`), and decides whether the answer is a review request or a blocking check.
+
+**Why not `owners:` on the parent directory.**
+An owner on `products/` would also claim every file below it that has no nearer owner.
+That misattributes those files, and it satisfies the coverage check for them, which turns real gaps into permanent false coverage.
+Over a hundred files under `products/` are unowned today and would flip.
+`additions:` contributes nothing to `owners`, so the coverage signal survives.
+
+**A consumer can combine `owners` and `additions`.**
+The owners are already responsible for everything in their tree.
+An empty `additions` means that the file names no separate owners of additions, not that nobody owns them.
+That is also why the key does not default to `owners`: a reader could no longer tell a directory with its own owners of additions from one that merely has an owner.
+
+The normative definition is section 3.6 of [`packages/owners-yaml/SPEC.md`](../../packages/owners-yaml/SPEC.md).
+
### `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, 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:
@@ -202,7 +236,7 @@ For a path `P`:
1. Walk from the repo root toward `P`, collecting every `owners.yaml` (or aliased `product.yaml`) on the way. If a file sets `inherit: false`, drop everything collected above it.
2. Effective config = shallow merge, nearest file winning per field (lists replace, never merge — predictability over cleverness).
-3. Within the nearest file that has `rules:`, apply the last rule whose `match` glob (gitignore-style semantics, documented with the schema) matches `P` relative to that file's directory. Rule fields override the merged config.
+3. Within each file, apply every rule whose `match` glob (gitignore-style semantics, documented with the schema) matches `P` relative to that file's directory, in file order. Each rule replaces only the fields it sets, before the file's fields merge into the result.
4. Review tagging = resolved `owners`. Primary owner = its first entry.
5. No ownership file on the walk and no rule match → **unowned**, which fails the coverage check unless the path is under an `owners: null` rule.
@@ -277,4 +311,4 @@ Safety properties of the atomic switch:
1. **Oncall routing**: resolved — dropped from v1. The Slack channel costs nothing (derived from the team slug by convention, with the root `teams:` registry overriding or setting `slack: false` where needed), but nothing consumes an oncall reference, so it is not carried. Re-adding it is additive once a consumer exists.
2. **Resolver ownership**: resolved — the resolver package is covered by the hard `CODEOWNERS` (see §5).
3. **Coverage gating cadence**: how soon after the PR to flip `owners:lint` coverage from warn to fail — immediately for _new_ directories (ratchet), or only once the whole tree is clean?
-4. **Hard-CODEOWNERS future** (explicitly out of scope now): if blocking gates ever move into the schema, approver inheritance should probably union up the tree rather than nearest-wins — parked until `team-security` wants to revisit.
+4. **Hard-CODEOWNERS future** (explicitly out of scope now): if blocking gates ever move into the schema, approver inheritance should probably union up the tree rather than nearest-wins — parked until `team-security` wants to revisit. `additions:` set the precedent for the union half; it is advisory, so it did not settle the blocking half.
diff --git a/owners.yaml b/owners.yaml
index 237ca80f04e2..c87e14d3d058 100644
--- a/owners.yaml
+++ b/owners.yaml
@@ -143,3 +143,14 @@ rules:
owners: team-devex
- match: '/tools/query-performance-ai/'
owners: team-analytics-platform
+ # A new product, provider, domain, or top-level package shapes the monorepo layout.
+ # The rule names who owns that decision and claims none of the files inside.
+ - match:
+ - '/products/*'
+ - '/posthog/ingress/*'
+ - '/posthog/egress/*'
+ - '/tools/*'
+ - '/services/*'
+ - '/packages/*'
+ - '/cli/*'
+ additions: team-devex
diff --git a/packages/owners-yaml/CHANGELOG.md b/packages/owners-yaml/CHANGELOG.md
index cca063921159..599acf24d786 100644
--- a/packages/owners-yaml/CHANGELOG.md
+++ b/packages/owners-yaml/CHANGELOG.md
@@ -7,6 +7,20 @@ Notable changes to the `owners-yaml` package. The format follows
`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.
+## Unreleased
+
+### Added
+
+- An optional `additions` field, at file level and in rules, names the owners of additions below a directory, separate from the owners of the files in it. The format only names them; a consumer decides what counts as an addition and what to do with the list. Unlike `owners`, the owners of additions from every file on the walk and every matching rule add up, and `inherit: false` still cuts them. `SPEC.md` section 3.6 defines it.
+- The resolver response carries an `additions` member, and `Resolution` an `additions` field. Consumers that ignore unknown members, as SPEC section 7.4 requires, are unaffected. SPEC section 7.4 requires a consumer to treat a missing member as an empty array.
+- `lint` fails on a rule that names a tracked directory without the trailing `/`, such as `docs` for `docs/`. A literal last segment also matches a file of that name, so the slash says which one is meant.
+- Conformance cases may state `additions`. A case that leaves it out expects an empty list, so existing cases need no edit.
+
+### Changed
+
+- Path normalization removes a trailing `/`. `products/new/` and `products/new` now resolve alike; before, the slash put the directory's own ownership file on the walk.
+- Every matching rule in a file now applies, and each replaces only the fields it sets. Before, the last matching rule replaced the earlier ones entirely, so a rule that set only `status` dropped the `owners` an earlier rule had set. `SPEC.md` section 3.4 records the amendment.
+
## 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.
diff --git a/packages/owners-yaml/README.md b/packages/owners-yaml/README.md
index 45721015caa8..5243691f3f70 100644
--- a/packages/owners-yaml/README.md
+++ b/packages/owners-yaml/README.md
@@ -82,7 +82,7 @@ version: 1
owners: team-billing
```
-A file can override its own subtree with `rules:`. Within one file, the last matching rule wins:
+A file can override its own subtree with `rules:`. Every rule that matches a path applies in file order, and each one replaces only the fields it sets:
```yaml
version: 1
@@ -94,6 +94,22 @@ rules:
owners: null
```
+`additions` names the owners of additions below a directory, separate from the owners of the files already in it.
+It never changes `owners`, so a directory can name owners of additions while the unowned files below it still show up as unowned:
+
+```yaml
+# products/owners.yaml
+version: 1
+owners: []
+rules:
+ - match: '/*'
+ additions: team-architecture
+```
+
+Resolve the new directory itself, not a file inside it: `owners resolve --json products/new-thing` returns `"additions": ["team-architecture"]`, and a deeper path does not.
+The owners of additions from every file on the walk add up, so a nested file cannot drop what an ancestor declared.
+The format only names these owners. A review bot or CI check decides from the change set what counts as an addition and what to do with the list.
+
The root file can also hold repository settings:
```yaml
@@ -124,12 +140,14 @@ For editor completion, point your YAML language server at [`owners.schema.json`]
$ owners resolve --json billing/vendor/stripe.py web/app.ts
{
"billing/vendor/stripe.py": {
+ "additions": [],
"owners": [],
"slack": null,
"source": "billing/owners.yaml",
"status": "active"
},
"web/app.ts": {
+ "additions": [],
"owners": [
"team-platform"
],
@@ -153,7 +171,8 @@ $ uvx owners-yaml==0.2.0 lint
✓ 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.
+`lint` fails on schema errors, a directory with two ownership files, `owners.yaml` files in reserved locations, and a rule that names a directory without the trailing `/`.
+Write `docs/` for a directory, because `docs` also matches a file called `docs`.
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.
diff --git a/packages/owners-yaml/SPEC.md b/packages/owners-yaml/SPEC.md
index 51ab1e3c4313..40b7080ad3e5 100644
--- a/packages/owners-yaml/SPEC.md
+++ b/packages/owners-yaml/SPEC.md
@@ -16,10 +16,12 @@ The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "S
- **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.
+- **Rule**: an entry of `rules:` that replaces fields, or appends to `additions`, 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`.
+- **Addition**: a path that a change adds to the repository, such as a new file or directory. A consumer decides which paths count as additions (section 3.6).
+- **Owners of additions**: the owners that the `additions` field names for a path. They are separate from the owners of the path (section 3.6).
## 2. File placement
@@ -32,13 +34,14 @@ The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "S
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. |
+| 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. |
+| `additions` | no | string or list of strings | The owners of additions below the directory. |
The root file MAY also carry the repository settings in section 5.
Any other top-level field is an error.
@@ -72,15 +75,16 @@ A rule MAY set `inherit` to change this for the paths it matches.
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. |
+| 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. |
+| `additions` | no | as in 3.6 | Appends to the file-level `additions` 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.
+2. Within one file, every rule whose pattern matches a path applies, in file order. Each rule replaces only the fields it sets, so a later rule that sets only `status` keeps the `owners` of an earlier rule. `additions` is the exception: each matching rule appends to it (section 3.6).
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.
@@ -91,53 +95,79 @@ Patterns use the GitHub CODEOWNERS syntax, applied to paths relative to the dire
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.
+4. A trailing `/` matches everything below the directory. It does not match the path of the directory itself.
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 `***`.
+### 3.6 `additions`
+
+`owners` names the owners of the paths below a directory.
+`additions` names the owners of additions below the directory, such as a new product in a directory of products.
+The format only names these owners.
+It does not define when a path is an addition.
+It does not define what a consumer does with the owners of additions.
+A consumer decides both, for example from the change set of a pull request.
+A consumer also chooses which version of the ownership files it reads.
+For example, it can read the version before a change, so that the change cannot alter the owners that apply to it.
+
+1. A string is a list with one entry. Each entry MUST be a non-empty string, as in 3.1.
+2. An empty list means that the file or the rule names no owners of additions. A file or a rule with no owners of additions MAY leave the key out.
+3. Any other value, including `null`, is an error. The file or the rule then names no owners of additions, as with an empty list, and its other fields still apply.
+4. `additions` does not change `owners`. A path with owners of additions and no owners is still unowned.
+5. For the other fields, the nearest file wins. `additions` is different: the entries of every file in section 4, step 3 and of every matching rule stay in the result. Only `inherit: false` removes the entries of ancestor files (section 3.3), at file level or through a rule.
+6. A consumer that asks about a new directory SHOULD resolve the path of the directory itself, not a path below it.
+ Section 4, step 2 stops at the parent of that path.
+ So the ownership file of the new directory does not apply.
+ A rule `match: '/*'` in the parent matches each direct child.
+7. A rule `match: '/docs/'` matches each path below `docs`, at any depth. It does not match `docs` itself (section 3.5, rule 4). The owners of additions for `docs` come from the other fields and rules on the walk to `docs`, as for any other path.
+
## 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 `/`.
+1. Normalize `P`: replace `\` with `/`, then remove any leading `./` and `/`, and any trailing `/`.
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.
+4. Start with an empty result: owners unset, status unset, source unset, additions empty.
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.
+ 1. Take the file-level `owners`, `status`, `inherit`, and `additions`.
+ 2. For each rule in the file that matches `P`, in file order, replace each of `owners`, `status`, and `inherit` that the rule sets. Append each entry of the rule's `additions` to the file-level `additions` (section 3.4).
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.
+ 7. Append each entry of `additions` to the result additions, unless the result additions already contain 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.
+ - `additions`: the result additions, in the order they were appended.
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. |
+The value is the file-level value after step 5.2 applied every matching rule.
+
+| 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. |
+| `additions` | non-empty list | The result additions gain each entry that they do not contain yet, at the end. |
+| `additions` | absent or `[]` | No effect. |
### 4.2 Flow (non-normative)
@@ -145,20 +175,21 @@ 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]
+ start([Path P]) --> norm[Normalize P]
+ norm --> 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]
+ has -- yes --> take[Take the file's owners, status, inherit, and additions]
+ take --> rule{Does a rule match P?}
+ rule -- yes --> apply[For each matching rule in file order,<br/>replace the owners, status, and inherit that it sets,<br/>and append its additions]
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]
+ reset --> merge[Merge owners, status, and additions as in 4.1]
merge --> more{More directories?}
more -- yes --> walk
- more -- no --> done([Return owners, unowned_by_design, status, source, slack])
+ more -- no --> done([Return owners, unowned_by_design, status, source, slack, additions])
```
### 4.3 Conformance
@@ -249,14 +280,15 @@ In `owners-yaml`, both `owners resolve --json` and `python -m owners_yaml` imple
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:
+3. Each value MUST be an object with the members `owners`, `status`, `slack`, and `source`. It SHOULD also have the member `additions`. The members are:
- | 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. |
+ | 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. |
+ | `additions` | array of strings | The resolved owners of additions (section 3.6), in the order of section 4, step 6. |
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.
@@ -273,15 +305,16 @@ In `owners-yaml`, both `owners resolve --json` and `python -m owners_yaml` imple
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.
+4. A consumer MUST treat a missing `additions` member as an empty array. A resolver that predates the member leaves it out.
+5. 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.
+- It removes the placeholder owner `team-CHANGEME` from every `owners` and `additions` list.
+- Its linter reports schema errors, reserved locations, directories with both an `owners.yaml` and an alias file, rules that name a tracked directory without the trailing `/`, 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 |
@@ -413,13 +446,16 @@ rules:
## 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.
+- **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 in one file merge the same way, so a rule that marks generated files does not undo a rule that names their owners.
- **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.
+- **Owners of additions add up.** Owners are nearest-file-wins because the union tags too many teams. `additions` answers a different question: who owns additions below a directory. If a nested file could drop the owners of additions that an ancestor file names, the answer of the ancestor would not be reliable. A separate field keeps the coverage check correct: `owners` on the parent directory would claim every file below it that has no nearer owner.
+- **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. `additions` is routing too: it names owners, and it does not approve or block a change.
## 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.
+- **1**, amended (unreleased): Section 3.4 applies every matching rule, field by field. Before, the last matching rule replaced the earlier ones entirely, so a file with two matching rules that set different fields now resolves differently.
+- **1**, amended (unreleased): Section 3.6 adds the optional `additions` field, section 7.2 adds the `additions` member, and section 7.4 says that a consumer treats a missing member as an empty array. A file without the field resolves as before. Section 4 step 1 also removes a trailing `/`, so a directory path resolves the same with or without it. Section 3.5 rule 4 now states that a trailing `/` does not match the directory path itself. Because of the step 1 change, a request for `docs/` no longer matches a rule `docs/`, and it no longer reads the ownership file in `docs`.
diff --git a/packages/owners-yaml/conformance/README.md b/packages/owners-yaml/conformance/README.md
index 5525c464a72d..df9f4f4b8d75 100644
--- a/packages/owners-yaml/conformance/README.md
+++ b/packages/owners-yaml/conformance/README.md
@@ -32,7 +32,7 @@ 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:
+Each resolution is a mapping with these keys:
| Key | Type | Meaning |
| ------------------- | ---------------- | -------------------------------------------------------------------------- |
@@ -41,8 +41,10 @@ Each resolution is a mapping with all five keys:
| `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`. |
+| `additions` | list of strings | Optional, default empty. The owners of additions at the path (SPEC 3.6). |
-A case never leaves a key out, so no value is implied.
+A case never leaves out one of the first five keys, so no value is implied.
+A case that leaves out `additions` expects an empty list, so the cases that predate the field stay as they are.
An example case:
@@ -73,7 +75,7 @@ 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.
+4. Compare all six keys of the result with the expected resolution. An expected resolution without `additions` expects an empty list. The order of `owners` and of `additions` 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`.
diff --git a/packages/owners-yaml/conformance/case.schema.json b/packages/owners-yaml/conformance/case.schema.json
index 22043f910045..3a284f082d1a 100644
--- a/packages/owners-yaml/conformance/case.schema.json
+++ b/packages/owners-yaml/conformance/case.schema.json
@@ -61,6 +61,10 @@
"source": { "type": ["string", "null"] },
"slack": {
"oneOf": [{ "type": "string", "pattern": "^#" }, { "type": "null" }]
+ },
+ "additions": {
+ "type": "array",
+ "items": { "type": "string", "minLength": 1 }
}
}
}
diff --git a/packages/owners-yaml/conformance/cases/additions.yaml b/packages/owners-yaml/conformance/cases/additions.yaml
new file mode 100644
index 000000000000..7b8f7174359a
--- /dev/null
+++ b/packages/owners-yaml/conformance/cases/additions.yaml
@@ -0,0 +1,156 @@
+cases:
+ - name: additions from every file on the walk add up, root first
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ additions: team-arch
+ a/owners.yaml: |
+ version: 1
+ owners: team-a
+ additions: [team-a, team-arch]
+ expect:
+ a/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: a/owners.yaml
+ slack: '#team-a'
+ additions: [team-arch, team-a]
+ x.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+ additions: [team-arch]
+
+ - name: inherit false drops the additions of ancestor files
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ additions: team-arch
+ a/owners.yaml: |
+ version: 1
+ owners: team-a
+ inherit: false
+ additions: team-a
+ expect:
+ a/x.py:
+ owners: [team-a]
+ unowned_by_design: false
+ status: active
+ source: a/owners.yaml
+ slack: '#team-a'
+ additions: [team-a]
+
+ - name: additions do not make a path owned
+ files:
+ owners.yaml: |
+ version: 1
+ owners: []
+ additions: team-arch
+ expect:
+ a/x.py:
+ owners: []
+ unowned_by_design: false
+ status: active
+ source: null
+ slack: null
+ additions: [team-arch]
+
+ - name: the additions of every matching rule append to the file-level additions
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ additions: team-arch
+ rules:
+ - match: '/a/'
+ additions: team-a
+ - match: '*.py'
+ additions: team-py
+ expect:
+ a/x.py:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+ additions: [team-arch, team-a, team-py]
+ b/x.txt:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+ additions: [team-arch]
+
+ - name: a slash-star rule applies to a direct child directory and not to what is inside it
+ files:
+ owners.yaml: |
+ version: 1
+ owners: []
+ products/owners.yaml: |
+ version: 1
+ owners: []
+ rules:
+ - match: '/*'
+ additions: team-arch
+ products/new/product.yaml: |
+ name: New
+ owners: [team-new]
+ expect:
+ products/new:
+ owners: []
+ unowned_by_design: false
+ status: active
+ source: null
+ slack: null
+ additions: [team-arch]
+ products/new/:
+ owners: []
+ unowned_by_design: false
+ status: active
+ source: null
+ slack: null
+ additions: [team-arch]
+ products/new/backend:
+ owners: [team-new]
+ unowned_by_design: false
+ status: active
+ source: products/new/product.yaml
+ slack: '#team-new'
+ additions: []
+ products/new/product.yaml:
+ owners: [team-new]
+ unowned_by_design: false
+ status: active
+ source: products/new/product.yaml
+ slack: '#team-new'
+ additions: []
+
+ - name: a trailing-slash rule applies below the directory and not to the directory itself
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-root
+ rules:
+ - match: '/docs/'
+ additions: team-docs
+ expect:
+ docs/new:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+ additions: [team-docs]
+ docs:
+ owners: [team-root]
+ unowned_by_design: false
+ status: active
+ source: owners.yaml
+ slack: '#team-root'
+ additions: []
diff --git a/packages/owners-yaml/conformance/cases/rules.yaml b/packages/owners-yaml/conformance/cases/rules.yaml
index 274a3ee83fc5..a31e6e3affbc 100644
--- a/packages/owners-yaml/conformance/cases/rules.yaml
+++ b/packages/owners-yaml/conformance/cases/rules.yaml
@@ -111,7 +111,7 @@ cases:
source: owners.yaml
slack: '#team-a'
- - name: an earlier matching rule has no effect even for fields the last rule does not set
+ - name: every matching rule applies and replaces only the fields it sets
files:
owners.yaml: |
version: 1
@@ -125,7 +125,7 @@ cases:
special.py:
owners: [team-b]
unowned_by_design: false
- status: active
+ status: generated
source: owners.yaml
slack: '#team-b'
other.py:
@@ -135,6 +135,24 @@ cases:
source: owners.yaml
slack: '#team-a'
+ - name: a later rule that sets only status keeps an earlier rule's null owners
+ files:
+ owners.yaml: |
+ version: 1
+ owners: team-a
+ rules:
+ - match: 'vendor/'
+ owners: null
+ - match: '*.gen.py'
+ status: generated
+ expect:
+ vendor/x.gen.py:
+ owners: []
+ unowned_by_design: true
+ status: generated
+ source: owners.yaml
+ slack: null
+
- name: a rule with a list of patterns acts as one rule per pattern in list order
files:
owners.yaml: |
diff --git a/packages/owners-yaml/owners.schema.json b/packages/owners-yaml/owners.schema.json
index bff034fa847f..35153e0935b7 100644
--- a/packages/owners-yaml/owners.schema.json
+++ b/packages/owners-yaml/owners.schema.json
@@ -16,9 +16,10 @@
},
"rules": {
"type": "array",
- "description": "Per-path overrides inside this directory. The last matching rule applies.",
+ "description": "Per-path overrides inside this directory. Every matching rule applies in order, and each replaces only the fields it sets.",
"items": { "$ref": "#/$defs/rule" }
},
+ "additions": { "$ref": "#/$defs/additions" },
"teams": {
"type": "object",
"description": "Repository settings: team slug to its channels.",
@@ -69,6 +70,13 @@
{ "type": "null" }
]
},
+ "additions": {
+ "description": "Team slugs or @handles who own additions, separate from the owners. Appends to the file-level value and to what ancestor files declare. A consumer decides what counts as an addition.",
+ "oneOf": [
+ { "type": "string", "minLength": 1 },
+ { "type": "array", "items": { "type": "string", "minLength": 1 } }
+ ]
+ },
"status": {
"enum": ["active", "deprecated", "generated", "vendored"],
"description": "The lifecycle of the code. Default active."
@@ -92,7 +100,8 @@
},
"owners": { "$ref": "#/$defs/owners" },
"status": { "$ref": "#/$defs/status" },
- "inherit": { "type": "boolean" }
+ "inherit": { "type": "boolean" },
+ "additions": { "$ref": "#/$defs/additions" }
}
},
"channel": {
diff --git a/packages/owners-yaml/owners_yaml/cli.py b/packages/owners-yaml/owners_yaml/cli.py
index 98432706fb67..3359465427fc 100644
--- a/packages/owners-yaml/owners_yaml/cli.py
+++ b/packages/owners-yaml/owners_yaml/cli.py
@@ -6,6 +6,7 @@ directly. The ``owners`` console script groups the same commands without the pre
from __future__ import annotations
+import re
import sys
import json
from collections import defaultdict
@@ -19,7 +20,7 @@ from .codeowners import project_repo
from .github import GitHubLookupError, GitHubOrg
from .matcher import compile_pattern, normalize_path
from .resolver import OWNERS_FILENAME, OwnersResolver, Purpose, RepoRootNotFound, read_stdin_paths, resolution_to_wire
-from .schema import RepoSettings, is_simple_owners_file, normalize_owners
+from .schema import RepoSettings, is_simple_owners_file, match_is_glob, normalize_owners
# GitHub Actions parses every YAML file under this directory as a workflow, in any repo.
BUILTIN_RESERVED_DIRS = (".github/workflows/**",)
@@ -250,6 +251,23 @@ def _live_scope(owners_by_file: dict[str, set[str]], paths: tuple[str, ...]) ->
return {owner for rel, owners in owners_by_file.items() if rel in wanted for owner in owners}
+def _bare_directory_match(match: str, directory: str, dirs_by_name: dict[str, list[str]]) -> bool:
+ """Whether a rule spells a tracked directory without the trailing ``/``.
+
+ A literal last segment matches a file of that name and everything below a directory of that
+ name, so ``docs`` can quietly claim a file called ``docs`` too. ``docs/`` says which one is
+ meant. Only the last segment has to be literal, so ``packages/*/src`` counts as well.
+ """
+ last = match.rsplit("/", 1)[-1]
+ if not last or match_is_glob(re.sub(r"\\.", "", last)):
+ return False
+ matcher = compile_pattern(match)
+ prefix = f"{directory}/" if directory else ""
+ # A directory the pattern matches by its full path has the literal last segment as its name.
+ candidates = dirs_by_name.get(re.sub(r"\\(.)", r"\1", last), ())
+ return any(d.startswith(prefix) and matcher.test(d[len(prefix) :]) for d in candidates)
+
+
@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
@@ -269,6 +287,10 @@ def cmd_lint(live: bool, org: str | None, repo_root: Path | None, paths: tuple[s
for path in tracked:
directory = path.rsplit("/", 1)[0] if "/" in path else ""
tracked_by_dir.setdefault(directory, []).append(path)
+ tracked_dirs = {"/".join(d.split("/")[: i + 1]) for d in tracked_by_dir if d for i in range(d.count("/") + 1)}
+ dirs_by_name: dict[str, list[str]] = {}
+ for d in tracked_dirs:
+ dirs_by_name.setdefault(d.rsplit("/", 1)[-1], []).append(d)
entries = resolver.parsed_ownership_files() # the single parse pass
owners_yaml_dirs = {e.rel_dir for e in entries if e.name == OWNERS_FILENAME}
@@ -305,6 +327,7 @@ def cmd_lint(live: bool, org: str | None, repo_root: Path | None, paths: tuple[s
continue
if parsed.owners:
owners_by_file[rel].update(parsed.owners)
+ owners_by_file[rel].update(parsed.additions)
if not parsed.rules:
continue
@@ -319,9 +342,12 @@ def cmd_lint(live: bool, org: str | None, repo_root: Path | None, paths: tuple[s
rel_paths = [p[len(directory) + 1 :] for p in under_dir] if directory else under_dir
for rule in parsed.rules:
owners_by_file[rel].update(rule.owners if isinstance(rule.owners, list) else [])
+ owners_by_file[rel].update(rule.additions)
matcher = compile_pattern(rule.match)
if not any(matcher.test(rp) for rp in rel_paths):
warnings.append(f"{rel}: rule '{rule.match}' matches zero tracked files (dead glob)")
+ elif _bare_directory_match(rule.match, directory, dirs_by_name):
+ errors.append(f"{rel}: rule '{rule.match}' names a directory; write '{rule.match}/'")
if live:
github = GitHubOrg(_github_org(org, settings))
@@ -376,10 +402,10 @@ def cmd_fmt(repo_root: Path | None) -> None:
click.echo(f"Delete ({len(plan.deletions)}) — statements fold into an ancestor:")
for path in plan.deletions:
click.echo(f" - {path}")
- if plan.additions:
+ if plan.rule_edits:
click.echo("Add rules:")
- for path in sorted(plan.additions):
- for line in plan.additions[path]:
+ for path in sorted(plan.rule_edits):
+ for line in plan.rule_edits[path]:
click.echo(f" {path}: {line}")
click.echo(f"\ncost: current {plan.current_cost} → canonical {plan.canonical_cost}")
diff --git a/packages/owners-yaml/owners_yaml/fmt.py b/packages/owners-yaml/owners_yaml/fmt.py
index 8d100af3799f..ed1be3292858 100644
--- a/packages/owners-yaml/owners_yaml/fmt.py
+++ b/packages/owners-yaml/owners_yaml/fmt.py
@@ -125,11 +125,11 @@ class CanonicalPlan:
canonical_cost: int
creations: list[str]
deletions: list[str]
- additions: dict[str, list[str]] # file -> human-readable rule lines added
+ rule_edits: dict[str, list[str]] # file -> human-readable rule lines changed
@property
def is_canonical(self) -> bool:
- return not self.creations and not self.deletions and not self.additions
+ return not self.creations and not self.deletions and not self.rule_edits
class CanonicalPlacer:
@@ -434,13 +434,13 @@ class CanonicalPlacer:
proposed = self._proposed_files(entries, placements, open_dirs)
self._prove(proposed, all_owners) # raises on any resolution mismatch
- creations, deletions, additions = self._diff(entries, proposed, open_dirs, pinned_dirs, code_files)
+ creations, deletions, rule_edits = self._diff(entries, proposed, open_dirs, pinned_dirs, code_files)
return CanonicalPlan(
current_cost=self._current_cost(entries),
canonical_cost=self._layout_cost(open_dirs, placements, pinned_dirs),
creations=creations,
deletions=deletions,
- additions=additions,
+ rule_edits=rule_edits,
)
def _layout_cost(self, open_dirs: set[str], placements: list[_Placement], pinned_dirs: set[str]) -> int:
@@ -508,24 +508,26 @@ class CanonicalPlacer:
code_files: list[str],
) -> tuple[list[str], list[str], dict[str, list[str]]]:
current_simple_dirs: set[str] = set() # dirs whose file fmt may delete
- # dir -> {match: owners as written} — last occurrence wins, mirroring the
- # resolver's last-match-wins so the diff compares against what decides.
- current_rules: dict[str, dict[str, list[str] | None | _Unset]] = {}
+ # dir -> {match: owners as written}. The last rule that sets owners wins, as in
+ # the resolver, so the diff compares against what decides.
+ current_rules: dict[str, dict[str, list[str] | None]] = {}
current_owners: dict[str, list[str] | None] = {} # dir -> top-level owners as written
for entry in entries:
if entry.name != OWNERS_FILENAME or entry.parsed is None:
continue
- current_rules[entry.rel_dir] = {r.match: r.owners for r in entry.parsed.rules}
+ current_rules[entry.rel_dir] = {
+ r.match: r.owners for r in entry.parsed.rules if not isinstance(r.owners, _Unset)
+ }
current_owners[entry.rel_dir] = entry.parsed.owners
if _is_simple_file(entry.parsed):
current_simple_dirs.add(entry.rel_dir)
creations, deletions = [], []
- additions: dict[str, list[str]] = {}
+ rule_edits: dict[str, list[str]] = {}
for carrier in sorted(open_dirs):
proposed_file = proposed[carrier]
- proposed_rules = {r.match: r.owners for r in proposed_file.rules}
+ proposed_rules = {r.match: r.owners for r in proposed_file.rules if not isinstance(r.owners, _Unset)}
cur_rules = current_rules.get(carrier, {})
path = f"{carrier}/{OWNERS_FILENAME}" if carrier else OWNERS_FILENAME
file_exists = carrier in current_rules or carrier in pinned_dirs
@@ -565,13 +567,13 @@ class CanonicalPlacer:
removed.append(f"drop {m} (was {_fmt_owners(cur_rules[m])})")
edits += sorted(changed) + sorted(added) + sorted(removed)
if edits:
- additions[path] = edits
+ rule_edits[path] = edits
for carrier in current_simple_dirs:
if carrier not in open_dirs:
deletions.append(f"{carrier}/{OWNERS_FILENAME}" if carrier else OWNERS_FILENAME)
- return sorted(creations), sorted(deletions), additions
+ return sorted(creations), sorted(deletions), rule_edits
# --- equivalence proof ----------------------------------------------
diff --git a/packages/owners-yaml/owners_yaml/matcher.py b/packages/owners-yaml/owners_yaml/matcher.py
index 2d6e3b53a61e..7d43b5cc09f1 100644
--- a/packages/owners-yaml/owners_yaml/matcher.py
+++ b/packages/owners-yaml/owners_yaml/matcher.py
@@ -25,13 +25,13 @@ SEP = "/"
def normalize_path(file_path: str) -> str:
- """Repo-relative, forward-slash path with any leading ``./`` or ``/`` stripped."""
+ """Repo-relative, forward-slash path with any leading ``./`` or ``/`` and any trailing ``/``
+ stripped. ``dir/`` and ``dir`` must resolve alike: with the slash kept, the walk would read the
+ directory's own ownership file, and a new directory could opt out of its parent's additions."""
p = file_path.replace("\\", SEP)
while p.startswith("./"):
p = p[2:]
- while p.startswith(SEP):
- p = p[1:]
- return p
+ return p.strip(SEP)
def pattern_to_segments(pattern: str) -> list[str]:
diff --git a/packages/owners-yaml/owners_yaml/resolver.py b/packages/owners-yaml/owners_yaml/resolver.py
index 5059e910e0d1..033aab0f0262 100644
--- a/packages/owners-yaml/owners_yaml/resolver.py
+++ b/packages/owners-yaml/owners_yaml/resolver.py
@@ -9,7 +9,7 @@ from __future__ import annotations
import sys
import subprocess
-from collections.abc import Mapping
+from collections.abc import Iterable, Mapping
from dataclasses import dataclass, field
from pathlib import Path
from typing import Literal, Protocol, TypedDict, runtime_checkable
@@ -102,6 +102,10 @@ class Resolution:
slack: str | None
source: str | None # repo-relative path of the file that decided owners
unowned_by_design: bool # explicit `owners: null` exemption
+ # The owners of additions at the path, separate from its owners. Every other field is nearest-
+ # file-wins; this one collects every declaration on the walk, so a nested file cannot drop what
+ # an ancestor set. `inherit: false` still cuts it like everything else.
+ additions: list[str] = field(default_factory=list)
@property
def is_owned(self) -> bool:
@@ -122,10 +126,17 @@ class WireResolution(TypedDict):
status: str
slack: str | None
source: str | None
+ additions: list[str]
def resolution_to_wire(r: Resolution) -> WireResolution:
- return {"owners": r.owners or [], "status": r.status, "slack": r.slack, "source": r.source}
+ return {
+ "owners": r.owners or [],
+ "status": r.status,
+ "slack": r.slack,
+ "source": r.source,
+ "additions": r.additions,
+ }
def read_stdin_paths() -> list[str]:
@@ -153,6 +164,12 @@ class _Merged:
owners: list[str] | None | _Unset = UNSET
status: str | _Unset = UNSET
source: str | None = None
+ additions: list[str] = field(default_factory=list)
+
+
+def _union(*groups: Iterable[str]) -> list[str]:
+ """Every entry across ``groups``, first occurrence first, without duplicates."""
+ return list(dict.fromkeys(item for group in groups for item in group))
class RepoRootNotFound(Exception):
@@ -302,16 +319,13 @@ class OwnersResolver:
collected.append(f)
return collected
- def _file_contribution(self, f: OwnersFile, path: str) -> OwnersFile | None:
- """A shallow copy of the file's fields with its own last-matching rule
- applied. Returns an OwnersFile whose top-level fields hold the effective
- contribution (rules already merged in). Returns the file itself if no rule."""
+ def _file_contribution(self, f: OwnersFile, path: str) -> OwnersFile:
+ """A shallow copy of the file's fields with every matching rule applied in order.
+ Each rule replaces only the fields it sets, so a later rule that sets only ``status``
+ keeps the ``owners`` an earlier rule set. Returns the file itself if no rule matches."""
rel = path[len(f.directory) + 1 :] if f.directory else path
- matched = None
- for rule in f.rules: # last-match-wins within the file
- if compile_pattern(rule.match).test(rel):
- matched = rule
- if matched is None:
+ matched = [rule for rule in f.rules if compile_pattern(rule.match).test(rel)]
+ if not matched:
return f
contrib = OwnersFile(
@@ -321,13 +335,15 @@ class OwnersResolver:
status=f.status,
inherit=f.inherit,
is_alias=f.is_alias,
+ additions=_union(f.additions, *(rule.additions for rule in matched)),
)
- if not isinstance(matched.owners, _Unset):
- contrib.owners = matched.owners
- if not isinstance(matched.status, _Unset):
- contrib.status = matched.status
- if not isinstance(matched.inherit, _Unset):
- contrib.inherit = matched.inherit
+ for rule in matched:
+ if not isinstance(rule.owners, _Unset):
+ contrib.owners = rule.owners
+ if not isinstance(rule.status, _Unset):
+ contrib.status = rule.status
+ if not isinstance(rule.inherit, _Unset):
+ contrib.inherit = rule.inherit
return contrib
def ownership_file_paths(self, paths: list[str]) -> list[str]:
@@ -346,7 +362,6 @@ class OwnersResolver:
for f in self._collect_files(norm):
contrib = self._file_contribution(f, norm)
- assert contrib is not None
# The single `set noparent` site: contrib.inherit is the file-level
# flag with any matched rule's override folded in, so a file-level
@@ -367,6 +382,9 @@ class OwnersResolver:
if not isinstance(contrib.status, _Unset):
merged.status = contrib.status
+ if contrib.additions:
+ merged.additions = _union(merged.additions, contrib.additions)
+
return self._build_resolution(norm, merged)
def _teams_registry(self) -> dict[str, TeamEntry]:
@@ -406,6 +424,7 @@ class OwnersResolver:
slack=slack,
source=merged.source,
unowned_by_design=unowned_by_design,
+ additions=merged.additions,
)
def _rel(self, path: Path) -> str:
diff --git a/packages/owners-yaml/owners_yaml/schema.py b/packages/owners-yaml/owners_yaml/schema.py
index b5c31104b4f6..9dabc486df68 100644
--- a/packages/owners-yaml/owners_yaml/schema.py
+++ b/packages/owners-yaml/owners_yaml/schema.py
@@ -24,8 +24,8 @@ OWNERS_FILENAME = "owners.yaml"
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`.
-TOP_LEVEL_KEYS = {"version", "owners", "status", "inherit", "rules"} | ROOT_ONLY_KEYS
-_RULE_KEYS = {"match", "owners", "status", "inherit"}
+TOP_LEVEL_KEYS = {"version", "owners", "status", "inherit", "rules", "additions"} | ROOT_ONLY_KEYS
+_RULE_KEYS = {"match", "owners", "status", "inherit", "additions"}
# 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
@@ -117,12 +117,15 @@ class RepoSettings:
@dataclass
class OwnersRule:
- """A per-path override inside a file, evaluated last-match-wins within the file."""
+ """A per-path override inside a file. Every matching rule applies in file order, and each
+ replaces only the fields it sets. ``additions`` is the exception: it adds to the file's
+ list instead of replacing it, so it needs no UNSET form."""
match: str
owners: list[str] | None | _Unset = UNSET
status: str | _Unset = UNSET
inherit: bool | _Unset = UNSET
+ additions: list[str] = field(default_factory=list)
@dataclass
@@ -137,6 +140,10 @@ class OwnersFile:
inherit: bool = True
rules: list[OwnersRule] = field(default_factory=list)
is_alias: bool = False
+ # The owners of additions below this directory, separate from the owners of its files.
+ # Names people only; what counts as an addition, and what a consumer does with them, is the
+ # consumer's policy.
+ additions: list[str] = field(default_factory=list)
# 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)
@@ -150,17 +157,37 @@ def normalize_owners(owners: list[str]) -> list[str]:
return [o for o in owners if o != CHANGEME_SLUG]
-def _validate_owners_value(value: object, where: str, errors: list[str]) -> list[str] | None | _Unset:
- if value is None:
- return None
+def _as_owner_list(value: object) -> list[str] | None:
+ """A non-empty string or a list of non-empty strings, as a normalized list; None otherwise.
+
+ Empty-string entries are rejected, not filtered: `owners: ['']` would count as covered while
+ the assigner drops the falsy owner and requests nobody.
+ """
if isinstance(value, str) and value:
value = [value]
- # Empty-string entries are rejected, not filtered: `owners: ['']` would count
- # as covered while the assigner drops the falsy owner and requests nobody.
if not isinstance(value, list) or not all(isinstance(x, str) and x for x in value):
+ return None
+ return normalize_owners([str(x) for x in value])
+
+
+def _validate_owners_value(value: object, where: str, errors: list[str]) -> list[str] | None | _Unset:
+ if value is None:
+ return None
+ owners = _as_owner_list(value)
+ if owners is None:
errors.append(f"{where}: 'owners' must be a non-empty string, a list of non-empty strings, or null")
return UNSET
- return normalize_owners([str(x) for x in value])
+ return owners
+
+
+def _validate_additions(value: object, where: str, errors: list[str]) -> list[str]:
+ """``additions`` takes one slug or a list of them. It has no null form: leaving the key out,
+ or an empty list, already means that the file names no owners of additions."""
+ additions = _as_owner_list(value)
+ if additions is None:
+ errors.append(f"{where}: 'additions' must be a non-empty string or a list of non-empty strings")
+ return []
+ return additions
def _is_valid_slack(raw: object) -> TypeGuard[str | bool]:
@@ -392,7 +419,11 @@ def _parse_rule(raw: object, index: int, errors: list[str]) -> list[OwnersRule]:
owners = _validate_owners_value(raw["owners"], where, errors) if "owners" in raw else UNSET
status = _validate_status(raw["status"], where, errors) if "status" in raw else UNSET
inherit = _validate_inherit(raw["inherit"], where, errors) if "inherit" in raw else UNSET
- return [OwnersRule(match=pattern, owners=owners, status=status, inherit=inherit) for pattern in patterns]
+ additions = _validate_additions(raw["additions"], where, errors) if "additions" in raw else []
+ return [
+ OwnersRule(match=pattern, owners=owners, status=status, inherit=inherit, additions=additions)
+ for pattern in patterns
+ ]
def _is_version_one(value: object) -> bool:
@@ -436,6 +467,8 @@ def parse_owners_file(text: str, *, path: Path, directory: str) -> tuple[OwnersF
if "inherit" in data:
inherit = _validate_inherit(data["inherit"], "inherit", errors)
file.inherit = True if isinstance(inherit, _Unset) else inherit
+ if "additions" in data:
+ file.additions = _validate_additions(data["additions"], "additions", 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.
@@ -486,11 +519,11 @@ 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 an
+ Both callers agree that status/``inherit: false``/``additions`` (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:
+ ``status``/``inherit``/``additions`` must pin the file. They differ on rules:
- lint's consolidation suggestions (``allow_anchored_rules=False``) only fold
files whose entire content is one non-empty ``owners:`` list;
@@ -499,9 +532,9 @@ def is_simple_owners_file(parsed: OwnersFile | None, *, allow_anchored_rules: bo
"""
if parsed is None or parsed.is_alias:
return False
- if parsed.inherit is False or parsed.status is not UNSET or parsed.teams:
+ if parsed.inherit is False or parsed.status is not UNSET or parsed.teams or parsed.additions:
return False
- if any(r.status is not UNSET or r.inherit is not UNSET for r in parsed.rules):
+ if any(r.status is not UNSET or r.inherit is not UNSET or r.additions for r in parsed.rules):
return False
if allow_anchored_rules:
return not any(match_is_glob(r.match) for r in parsed.rules)
diff --git a/packages/owners-yaml/resolution.schema.json b/packages/owners-yaml/resolution.schema.json
index c2161ea02cc0..1a4fccdb03e7 100644
--- a/packages/owners-yaml/resolution.schema.json
+++ b/packages/owners-yaml/resolution.schema.json
@@ -23,6 +23,11 @@
"type": ["string", "null"],
"minLength": 1,
"description": "The repository-relative path of the file that set the owners."
+ },
+ "additions": {
+ "type": "array",
+ "items": { "type": "string", "minLength": 1 },
+ "description": "The owners of additions at the path, separate from its owners. A resolver that predates the member leaves it out, and a consumer treats that as an empty array."
}
}
}
diff --git a/packages/owners-yaml/tests/test_conformance.py b/packages/owners-yaml/tests/test_conformance.py
index 17c9117e1705..6a58cc5a3f81 100644
--- a/packages/owners-yaml/tests/test_conformance.py
+++ b/packages/owners-yaml/tests/test_conformance.py
@@ -64,9 +64,13 @@ def test_conformance_case(tmp_path: Path, case: ConformanceCase) -> None:
"status": resolution.status,
"source": resolution.source,
"slack": resolve_channel(case, owners, resolution.slack),
+ "additions": resolution.additions,
}
+ # A case that leaves `additions` out expects none, so the cases written before the field
+ # existed also check that nothing leaks into it.
+ expected = {path: {"additions": [], **resolution} for path, resolution in case.expect.items()}
- assert actual == case.expect
+ assert actual == expected
@pytest.mark.parametrize("case_file", CASE_FILES, ids=[f.name for f in CASE_FILES])
diff --git a/packages/owners-yaml/tests/test_owners.py b/packages/owners-yaml/tests/test_owners.py
index 249a25bdd4c2..f5bab389aafb 100644
--- a/packages/owners-yaml/tests/test_owners.py
+++ b/packages/owners-yaml/tests/test_owners.py
@@ -10,6 +10,7 @@ import pytest
from click.testing import CliRunner
from owners_yaml import (
census,
+ cli as cli_module,
first_team_owner,
fmt as fmt_module,
owner_handle,
@@ -22,6 +23,7 @@ from owners_yaml.cli import _consolidation_suggestions, _live_scope, _reserved_l
from owners_yaml.fmt import CanonicalPlacer, CanonicalPlan
from owners_yaml.resolver import OwnersResolver, team_channel
from owners_yaml.schema import (
+ _RULE_KEYS,
DEFAULT_ALIAS_FILES,
TOP_LEVEL_KEYS,
CodeownersSettings,
@@ -160,9 +162,27 @@ def test_teams_registry_and_settings_are_root_only(tmp_path: Path) -> None:
assert root.settings.codeowners == CodeownersSettings(jest_root="web")
-def test_json_schema_accepts_the_same_top_level_keys_as_the_parser() -> None:
+def test_json_schema_accepts_the_same_keys_as_the_parser() -> None:
schema = json.loads((Path(__file__).parent.parent / "owners.schema.json").read_text())
assert set(schema["properties"]) == TOP_LEVEL_KEYS
+ assert set(schema["$defs"]["rule"]["properties"]) == _RULE_KEYS
+
+
+ "fragment",
+ [
+ "additions: 5\n",
+ "additions: [team-a, '']\n",
+ "additions: {}\n",
+ "rules:\n - match: '/*'\n additions: [team-a, '']\n",
+ ],
+)
+def test_malformed_additions_is_a_schema_error_and_adds_nobody(tmp_path: Path, fragment: str) -> None:
+ file, errors = parse_owners_file(
+ "version: 1\nowners: [team-a]\n" + fragment, path=tmp_path / "owners.yaml", directory=""
+ )
+ assert any("'additions' must be" in e for e in errors), errors
+ assert file is not None and file.additions == [] and all(r.additions == [] for r in file.rules)
@pytest.mark.parametrize(
@@ -360,14 +380,23 @@ def _fmt_plan(tmp_path: Path, files: dict[str, str]) -> CanonicalPlan:
return CanonicalPlacer(OwnersResolver(repo_root=tmp_path)).build()
-def test_fmt_folds_dedicated_child_into_pinned_parent(tmp_path: Path) -> None:
+ "parent_yaml",
+ [
+ "version: 1\nowners: [team-a]\nstatus: deprecated\n",
+ "version: 1\nowners: [team-a]\nstatus: deprecated\nrules:\n - match: '/gen/'\n status: generated\n",
+ ],
+)
+def test_fmt_folds_dedicated_child_into_pinned_parent(tmp_path: Path, parent_yaml: str) -> None:
# `a` is a pinned carrier (non-simple, carries a status); `a/b` is a dedicated
# single-statement file. Canonical folds b's statement into a and drops the file.
+ # A rule on `a` that sets no owners is not an owner statement, so it is not an edit.
plan = _fmt_plan(
tmp_path,
{
- "a/owners.yaml": "version: 1\nowners: [team-a]\nstatus: deprecated\n",
+ "a/owners.yaml": parent_yaml,
"a/f.py": "x",
+ "a/gen/h.py": "x",
"a/b/owners.yaml": "version: 1\nowners: [team-b]\n",
"a/b/g.py": "x",
"r1.py": "x",
@@ -375,7 +404,7 @@ def test_fmt_folds_dedicated_child_into_pinned_parent(tmp_path: Path) -> None:
},
)
assert plan.deletions == ["a/b/owners.yaml"]
- assert plan.additions == {"a/owners.yaml": ["/b/ -> [team-b]"]}
+ assert plan.rule_edits == {"a/owners.yaml": ["/b/ -> [team-b]"]}
assert plan.creations == []
@@ -444,7 +473,7 @@ def test_fmt_never_places_rules_on_a_product_yaml_dir(tmp_path: Path) -> None:
# A product.yaml manifest only exposes its owners list — it cannot physically hold
# rules, and an owners.yaml next to it is a lint error. A differently-owned subtree
# below a product must keep its own file or fold to an ancestor, never produce
- # additions keyed on the product dir.
+ # rule edits keyed on the product dir.
plan = _fmt_plan(
tmp_path,
{
@@ -457,7 +486,7 @@ def test_fmt_never_places_rules_on_a_product_yaml_dir(tmp_path: Path) -> None:
"r2.py": "x",
},
)
- assert "products/foo/owners.yaml" not in plan.additions
+ assert "products/foo/owners.yaml" not in plan.rule_edits
assert "products/foo/owners.yaml" not in plan.creations
@@ -518,7 +547,7 @@ def test_fmt_reports_top_level_owner_edits(tmp_path: Path) -> None:
)
assert not plan.is_canonical
assert sorted(plan.deletions) == ["a/owners.yaml", "b/owners.yaml"]
- assert any("owners: [] -> [team-a]" in line for line in plan.additions.get("owners.yaml", []))
+ assert any("owners: [] -> [team-a]" in line for line in plan.rule_edits.get("owners.yaml", []))
def test_fmt_reports_rule_owner_changes(tmp_path: Path) -> None:
@@ -536,7 +565,7 @@ def test_fmt_reports_rule_owner_changes(tmp_path: Path) -> None:
},
)
assert "a/owners.yaml" in plan.deletions
- assert "/a/: [team-old] -> [team-new]" in plan.additions.get("owners.yaml", [])
+ assert "/a/: [team-old] -> [team-new]" in plan.rule_edits.get("owners.yaml", [])
def test_fmt_preserves_unowned_by_design_exemptions(tmp_path: Path) -> None:
@@ -553,7 +582,7 @@ def test_fmt_preserves_unowned_by_design_exemptions(tmp_path: Path) -> None:
},
)
if "a/owners.yaml" in plan.deletions:
- assert "/a/ -> (unowned)" in plan.additions.get("owners.yaml", [])
+ assert "/a/ -> (unowned)" in plan.rule_edits.get("owners.yaml", [])
def test_fmt_reports_stale_rule_removals(tmp_path: Path) -> None:
@@ -576,7 +605,7 @@ def test_fmt_reports_stale_rule_removals(tmp_path: Path) -> None:
},
)
assert not plan.is_canonical
- assert "drop /b/ (was [team-a])" in plan.additions.get("products/foo/backend/owners.yaml", [])
+ assert "drop /b/ (was [team-a])" in plan.rule_edits.get("products/foo/backend/owners.yaml", [])
assert "products/foo/backend/owners.yaml" not in plan.deletions
@@ -598,36 +627,42 @@ def test_fmt_frozen_file_blocks_carry_up(tmp_path: Path) -> None:
assert "d/sub/owners.yaml" not in plan.deletions
-def test_fmt_proof_rejects_plans_that_drop_status(tmp_path: Path) -> None:
+def test_fmt_folds_a_child_under_a_status_only_rule_without_losing_the_status(tmp_path: Path) -> None:
# Folding the child appends an owner-only '/gen/' rule after the parent's
- # status-only '/gen/' rule; last-match-wins then loses `generated` while
- # owners stay identical. The proof must refuse such a plan, not print it.
- with pytest.raises(AssertionError, match="fmt bug"):
- _fmt_plan(
- tmp_path,
- {
- "owners.yaml": "version: 1\nowners: []\n",
- "a/owners.yaml": ("version: 1\nowners: [team-a]\nrules:\n - match: '/gen/'\n status: generated\n"),
- "a/gen/owners.yaml": "version: 1\nowners: [team-g]\n",
- "a/gen/f.py": "x",
- "a/f.py": "x",
- "r1.py": "x",
- },
- )
+ # status-only '/gen/' rule. Rules merge per field, so `generated` survives and
+ # the proof accepts the plan. Under a whole-rule merge the proof refuses it.
+ plan = _fmt_plan(
+ tmp_path,
+ {
+ "owners.yaml": "version: 1\nowners: []\n",
+ "a/owners.yaml": ("version: 1\nowners: [team-a]\nrules:\n - match: '/gen/'\n status: generated\n"),
+ "a/gen/owners.yaml": "version: 1\nowners: [team-g]\n",
+ "a/gen/f.py": "x",
+ "a/f.py": "x",
+ "r1.py": "x",
+ },
+ )
+ assert plan.deletions == ["a/gen/owners.yaml"]
-def test_fmt_pins_files_with_rule_level_metadata(tmp_path: Path) -> None:
- # Relocation only preserves match+owners, so a rule carrying status/inherit
- # must pin its file exactly like a glob does — otherwise folding this child
- # into the parent would silently drop the generated status.
+ "child_yaml",
+ [
+ "version: 1\nowners: [team-b]\nrules:\n - match: '/gen/'\n owners: [team-b]\n status: generated\n",
+ "version: 1\nowners: [team-b]\nrules:\n - match: '/gen/'\n owners: [team-b]\n additions: team-x\n",
+ "version: 1\nowners: [team-b]\nadditions: team-x\n",
+ ],
+)
+def test_fmt_pins_files_with_rule_level_metadata(tmp_path: Path, child_yaml: str) -> None:
+ # Relocation only preserves match+owners, so a file carrying status or additions
+ # must pin itself exactly like a glob does — otherwise folding this child into the
+ # parent would silently drop the generated status or the additions.
plan = _fmt_plan(
tmp_path,
{
"a/owners.yaml": "version: 1\nowners: [team-a]\nstatus: deprecated\n",
"a/f.py": "x",
- "a/b/owners.yaml": (
- "version: 1\nowners: [team-b]\nrules:\n - match: '/gen/'\n owners: [team-b]\n status: generated\n"
- ),
+ "a/b/owners.yaml": child_yaml,
"a/b/gen/g.py": "x",
"r1.py": "x",
"r2.py": "x",
@@ -811,6 +846,7 @@ def test_json_entrypoint_resolves_against_an_explicit_repo_root(registry_repo: P
"status": "active",
"slack": "#registry-chan",
"source": "reg/owners.yaml",
+ "additions": [],
}
}
jsonschema = pytest.importorskip("jsonschema")
@@ -967,6 +1003,32 @@ def test_cli_lint_reports_no_alias_conflict_the_resolver_does_not_see(tmp_path:
assert "has both" not in result.output
+ "match,error",
+ [
+ ("docs", True),
+ ("/web/docs", True),
+ ("/*/docs", True),
+ ("/web/d\\ocs", True),
+ ("/*/docs/", False),
+ ("docs/", False),
+ ("README.md", False),
+ ("/web/docs/guide.md", False),
+ ],
+)
+def test_cli_lint_rejects_a_directory_rule_without_a_trailing_slash(tmp_path: Path, match: str, error: bool) -> None:
+ _write(
+ tmp_path, "owners.yaml", f"version: 1\nowners: [team-a]\nrules:\n - match: '{match}'\n owners: [team-b]\n"
+ )
+ _write(tmp_path, "web/docs/guide.md", "")
+ _write(tmp_path, "README.md", "")
+
+ result = CliRunner().invoke(main, ["lint", "--repo-root", str(tmp_path)])
+
+ assert ("names a directory" in result.output) is error, result.output
+ assert (result.exit_code != 0) is error
+
+
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")
@@ -989,6 +1051,22 @@ def test_cli_lints_a_tree_that_is_not_a_git_worktree(registry_repo: Path) -> Non
assert "coverage: 2 of 8 tracked file(s) resolve to unowned" in result.output
+def test_cli_live_lint_validates_names_used_only_in_additions(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ validated: set[str] = set()
+ monkeypatch.setattr(cli_module, "_validate_owners_live", lambda owners, github: validated.update(owners) or [])
+ _write(
+ tmp_path,
+ "owners.yaml",
+ "version: 1\nowners: [team-a]\nadditions: team-gate\nrules:\n - match: '/*'\n additions: '@gatekeeper'\n",
+ )
+ _write(tmp_path, "x.py", "")
+
+ result = CliRunner().invoke(main, ["lint", "--live", "--org", "acme", "--repo-root", str(tmp_path)])
+
+ assert result.exit_code == 0, result.output
+ assert {"team-gate", "@gatekeeper"} <= validated
+
+
@pytest.mark.parametrize(
"args,message",
[