:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(devex): request owners of additions when a pr adds a new path (#107556)
Julian Bez21f7afedb2dd
diff --git a/.github/scripts/assign-reviewers.js b/.github/scripts/assign-reviewers.jsindex 4e814338b340..344ad4cb3213 100644--- a/.github/scripts/assign-reviewers.js+++ b/.github/scripts/assign-reviewers.js@@ -143,6 +143,7 @@ async function getChangedFiles() {// Binary files and pure renames report null counts; treat as 0.additions: file.additions || 0,deletions: file.deletions || 0,+ status: file.status,})}@@ -183,6 +184,21 @@ function classifyOwner(owner) {return null}+// status: generated/vendored is the structured form of the excluded+// patterns above — such trees have owners for lookup, but shouldn't+// pull reviewers in or count toward substantive thresholds. Ownership+// metadata files are exempt: an owners.yaml edit inside a generated+// tree still changes future routing and must reach a reviewer.+function isGeneratedOrVendored(filename, resolution) {+ const basename = filename.split('/').pop()+ const isOwnershipFile = basename === 'owners.yaml' || basename === 'product.yaml'+ return (+ !isOwnershipFile &&+ Boolean(resolution) &&+ (resolution.status === 'generated' || resolution.status === 'vendored')+ )+}+// Build a footprint per owner from the resolver's per-file result: which// owners.yaml/product.yaml sources pulled them in, which (non-excluded) files// they own in this diff, and the total lines changed across those files. Pure@@ -194,18 +210,7 @@ function computeOwnerFootprints(resolutionByPath, changedFiles, config = CONFIG)for (const file of relevantFiles) {const resolution = resolutionByPath[file.filename]- // status: generated/vendored is the structured form of the excluded- // patterns above — such trees have owners for lookup, but shouldn't- // pull reviewers in or count toward substantive thresholds. Ownership- // metadata files are exempt: an owners.yaml edit inside a generated- // tree still changes future routing and must reach a reviewer.- const basename = file.filename.split('/').pop()- const isOwnershipFile = basename === 'owners.yaml' || basename === 'product.yaml'- if (- !isOwnershipFile &&- resolution &&- (resolution.status === 'generated' || resolution.status === 'vendored')- ) {+ if (isGeneratedOrVendored(file.filename, resolution)) {continue}const owners = (resolution && resolution.owners) || []@@ -250,6 +255,45 @@ function computeOwnerFootprints(resolutionByPath, changedFiles, config = CONFIG)}))}+// GitHub reports a moved file as `renamed`, and a move into a new directory adds+// that directory as much as a new file does.+const ADDED_FILE_STATUSES = new Set(['added', 'renamed', 'copied'])++// The resolver reads the master checkout, which does not hold the files a PR+// adds. For such a file it reports `added`: the new directory above it (or the+// file itself in an existing directory) and the owners of additions there. The+// change status filter matters on a PR that is behind master: a file it edits+// that master deleted since is also missing from the checkout.+// Returns one entry per owner with the new paths that pulled it in.+function computeAdditionOwners(resolutionByPath, changedFiles, config = CONFIG) {+ const owners = new Map()+ for (const file of changedFiles) {+ const resolution = resolutionByPath[file.filename]+ const added = resolution && resolution.added+ if (!added || !ADDED_FILE_STATUSES.has(file.status) || isExcludedFile(file.filename, config.excludedPatterns)) {+ continue+ }+ if (isGeneratedOrVendored(file.filename, resolution)) {+ continue+ }+ for (const rawOwner of added.additions || []) {+ const resolved = mapResolvedOwner(rawOwner)+ if (!resolved) {+ continue+ }+ let entry = owners.get(resolved.owner)+ if (!entry) {+ entry = { ...resolved, additionPaths: [] }+ owners.set(resolved.owner, entry)+ }+ if (!entry.additionPaths.includes(added.path)) {+ entry.additionPaths.push(added.path)+ }+ }+ }+ return Array.from(owners.values())+}+function isSubstantive(footprint, config = CONFIG) {return footprint.lines >= config.substantiveLines || footprint.fileCount >= config.substantiveFiles}@@ -306,6 +350,19 @@ function classifyOwners(footprints, config = CONFIG) {return { requested, demoted }}+// Owners of additions decide whether a new directory belongs where the PR puts it,+// whatever the size of the change. So they are always requested, and the footprint+// rules and the team cap apply only to the other owners. An owner of additions that+// also owns changed files must not take one of the capped places.+function classifyOwnersWithAdditions(footprints, additionOwners, config = CONFIG) {+ const additionOwnerSet = new Set(additionOwners.map((entry) => entry.owner))+ const { requested, demoted } = classifyOwners(+ footprints.filter((footprint) => !additionOwnerSet.has(footprint.owner)),+ config+ )+ return { requested: [...requested, ...additionOwners], demoted }+}+function formatPatterns(patterns, max = 3) {const shown = patterns.slice(0, max).map((p) => `\`${p}\``)if (patterns.length > max) {@@ -323,31 +380,57 @@ function formatSkippedOwner(footprint) {return `- \`${footprint.owner}\` (${formatPatterns(footprint.patterns, 2)})`}-// Produce the explanation comment body, or null if no owner was dropped. We-// only post when we actually skipped someone GitHub's "Reviewers" sidebar would-// otherwise have hidden, so the comment carries signal, not noise.-function buildReviewerComment(requested, demoted, config = CONFIG) {- if (demoted.length === 0) {+// An addition path comes from the PR, so a fork chooses it. A backtick or a line+// break in it would end the code span and let the PR author write markdown and+// live mentions into a comment that the app posts.+function sanitizePathForComment(path) {+ return path.replace(/[`\u0000-\u001f\u007f]/g, '?')+}++function formatAdditionOwner(entry) {+ return `- \`${entry.owner}\` (${formatPatterns(entry.additionPaths.map(sanitizePathForComment), 2)})`+}++// Produce the explanation comment body, or null if no owner was dropped and no+// owner of additions was requested. We only post when a reviewer would otherwise+// wonder why a team is (or is not) in GitHub's "Reviewers" sidebar, so the+// comment carries signal, not noise.+function buildReviewerComment(requested, demoted, additionOwners = [], config = CONFIG) {+ if (demoted.length === 0 && additionOwners.length === 0) {return null}- const allMinor = demoted.every((f) => f.reason === 'minor')- const reason = allMinor- ? 'they only have minor changes here'- : 'their changes are minor, or the reviewer list was getting long'+ const lines = [config.commentMarker, '### 👀 Auto-assigned reviewers', '']++ if (additionOwners.length > 0) {+ lines.push(+ 'These owners were selected because this PR adds a new path where `owners.yaml` names owners of additions. ' ++ 'The path after each owner is the new path:',+ '',+ ...additionOwners.map(formatAdditionOwner),+ ''+ )+ }- return [- config.commentMarker,- '### 👀 Auto-assigned reviewers',- '',- `These soft owners were skipped because ${reason}. Nothing blocks merge, so self-assign if you'd like a look:`,- '',- ...demoted.map(formatSkippedOwner),- '',+ if (demoted.length > 0) {+ const allMinor = demoted.every((f) => f.reason === 'minor')+ const reason = allMinor+ ? 'they only have minor changes here'+ : 'their changes are minor, or the reviewer list was getting long'+ lines.push(+ `These soft owners were skipped because ${reason}. Nothing blocks merge, so self-assign if you'd like a look:`,+ '',+ ...demoted.map(formatSkippedOwner),+ ''+ )+ }++ lines.push("Soft owners come from each directory's `owners.yaml` and each product's `product.yaml` " +- '(resolved nearest-file-wins). The locator after each owner is the file that decided it. ' +- 'Generated files and lockfiles are ignored when deciding ownership.',- ].join('\n')+ '(resolved nearest-file-wins). For a skipped owner, the locator is the file that decided it. ' ++ 'Generated files and lockfiles are ignored when deciding ownership.'+ )+ return lines.join('\n')}async function assignReviewers(teams, users) {@@ -398,7 +481,9 @@ async function assignReviewers(teams, users) {if (r.status === 422) {dropped.push(`@${user}`)} else if (!r.ok) {- throw new Error(`GitHub API error assigning user '${user}': ${r.status} ${r.statusText}\n${await r.text()}`)+ throw new Error(+ `GitHub API error assigning user '${user}': ${r.status} ${r.statusText}\n${await r.text()}`+ )}}@@ -566,7 +651,8 @@ async function main() {const resolutionByPath = resolveOwners(relevantFilenames)const footprints = computeOwnerFootprints(resolutionByPath, changedFiles)- const { requested, demoted } = classifyOwners(footprints)+ const additionOwners = computeAdditionOwners(resolutionByPath, changedFiles)+ const { requested, demoted } = classifyOwnersWithAdditions(footprints, additionOwners)const teams = requested.filter((f) => f.type === 'team').map((f) => f.name)const users = requested.filter((f) => f.type === 'user').map((f) => f.name)@@ -578,6 +664,7 @@ async function main() {console.info(`Teams matched: ${teams.join(', ') || 'none'}`)console.info(`Users to request: ${users.join(', ') || 'none'}`)console.info(`Demoted to comment: ${demoted.map((f) => f.owner).join(', ') || 'none'}`)+ console.info(`Owners of additions: ${additionOwners.map((entry) => entry.owner).join(', ') || 'none'}`)console.info()if (!isExternal) {@@ -588,7 +675,7 @@ async function main() {await assignReviewers(toRequest, users)}- const commentBody = buildReviewerComment(requested, demoted)+ const commentBody = buildReviewerComment(requested, demoted, additionOwners)if (commentBody) {await upsertReviewerComment(commentBody)}@@ -609,8 +696,10 @@ module.exports = {teamSlugToLabel,partitionExternalTeams,computeOwnerFootprints,+ computeAdditionOwners,isSubstantive,classifyOwners,+ classifyOwnersWithAdditions,buildReviewerComment,fileMatchesPattern,}diff --git a/.github/scripts/assign-reviewers.test.js b/.github/scripts/assign-reviewers.test.jsindex 3f9911c41341..ce8e5ad81298 100644--- a/.github/scripts/assign-reviewers.test.js+++ b/.github/scripts/assign-reviewers.test.js@@ -10,8 +10,10 @@ const {teamSlugToLabel,partitionExternalTeams,computeOwnerFootprints,+ computeAdditionOwners,isSubstantive,classifyOwners,+ classifyOwnersWithAdditions,buildReviewerComment,fileMatchesPattern,} = require('./assign-reviewers')@@ -145,7 +147,10 @@ test('computeOwnerFootprints: ignores generated/excluded files and maps bare slutest('computeOwnerFootprints: skips resolutions with generated/vendored status', () => {const resolution = {'posthog/api/survey.py': resolved(['team-surveys'], 'products/surveys/product.yaml'),- 'some/generated/tree/file.ts': { ...resolved(['team-devex'], 'some/generated/owners.yaml'), status: 'generated' },+ 'some/generated/tree/file.ts': {+ ...resolved(['team-devex'], 'some/generated/owners.yaml'),+ status: 'generated',+ },'vendor/lib/thing.js': { ...resolved(['team-devex'], 'vendor/owners.yaml'), status: 'vendored' },}// An ownership file inside a generated tree resolves with that status too,@@ -244,9 +249,7 @@ test('classifyOwners: promotes the largest owner when all are below the bar', ()})test('classifyOwners: caps requested teams at maxTeamsRequested, demoting the smallest', () => {- const footprints = Array.from({ length: CONFIG.maxTeamsRequested + 3 }, (_, i) =>- fp(`@PostHog/team-${i}`, 50 + i)- )+ const footprints = Array.from({ length: CONFIG.maxTeamsRequested + 3 }, (_, i) => fp(`@PostHog/team-${i}`, 50 + i))const { requested, demoted } = classifyOwners(footprints)assert.equal(requested.filter((f) => f.type === 'team').length, CONFIG.maxTeamsRequested)@@ -267,9 +270,7 @@ test('classifyOwners: caps requested teams at maxTeamsRequested, demoting the smtest('classifyOwners: never caps explicit users even when teams overflow the cap', () => {// All substantive, so the cap (teams-only) is the only thing that can demote.- const teams = Array.from({ length: CONFIG.maxTeamsRequested + 2 }, (_, i) =>- fp(`@PostHog/team-${i}`, 50 + i)- )+ const teams = Array.from({ length: CONFIG.maxTeamsRequested + 2 }, (_, i) => fp(`@PostHog/team-${i}`, 50 + i))const users = [fp('@user-a', 20, 1, 'user'), fp('@user-b', 20, 1, 'user')]const { requested, demoted } = classifyOwners([...teams, ...users])@@ -292,6 +293,57 @@ test('classifyOwners: never caps explicit users even when teams overflow the cap)})+test('computeAdditionOwners: collects owners of additions per new path, skipping edits and excluded, generated or vendored files', () => {+ const added = (path, additions) => ({ ...resolved([], null), added: { path, additions } })+ const resolution = {+ 'products/new/a.py': added('products/new', ['team-devex']),+ 'products/new/b.py': added('products/new', ['team-devex']),+ 'tools/new.py': added('tools/new.py', ['team-devex', '@someone']),+ 'posthog/api/survey.py': resolved(['team-surveys'], 'posthog/owners.yaml'),+ 'products/new/frontend/generated/api.ts': added('products/new', ['team-generated']),+ 'vendor/new/lib.js': { ...added('vendor/new', ['team-vendored']), status: 'vendored' },+ }+ // A PR behind master edits a file that master deleted since, so the checkout lacks it too.+ resolution['products/gone/old.py'] = added('products/gone', ['team-stale'])+ const files = Object.keys(resolution).map((filename) => ({+ ...file(filename),+ status: filename === 'products/gone/old.py' ? 'modified' : 'added',+ }))++ const owners = computeAdditionOwners(resolution, files)++ assert.equal(owners.length, 2)+ assertMatchObject(owners[0], {+ owner: '@PostHog/team-devex',+ type: 'team',+ additionPaths: ['products/new', 'tools/new.py'],+ })+ assertMatchObject(owners[1], { owner: '@someone', type: 'user', additionPaths: ['tools/new.py'] })+})++test('classifyOwnersWithAdditions: requests owners of additions on top of a full team cap', () => {+ const teams = Array.from({ length: CONFIG.maxTeamsRequested }, (_, i) => fp(`@PostHog/team-${i}`, 50 + i))+ const footprints = [...teams, fp('@PostHog/team-devex', 200), fp('@PostHog/team-small', 1)]+ const additionOwners = computeAdditionOwners(+ {+ 'products/new/a.py': { ...resolved([], null), added: { path: 'products/new', additions: ['team-devex'] } },+ },+ [{ ...file('products/new/a.py'), status: 'added' }]+ )++ const { requested, demoted } = classifyOwnersWithAdditions(footprints, additionOwners)++ assert.equal(requested.length, CONFIG.maxTeamsRequested + 1)+ assert.equal(requested.filter((f) => f.owner === '@PostHog/team-devex').length, 1)+ for (const team of teams) {+ assert.ok(requested.some((f) => f.owner === team.owner))+ }+ assert.deepEqual(+ demoted.map((f) => f.owner),+ ['@PostHog/team-small']+ )+})+const requested = [{owner: '@PostHog/team-surveys',@@ -315,6 +367,20 @@ test('buildReviewerComment: returns null when no owner was dropped', () => {assert.equal(buildReviewerComment([...requested, requested[0]], []), null)})+test('buildReviewerComment: names each owner of additions with its addition, even when nobody was skipped', () => {+ const additionOwners = [{ owner: '@PostHog/team-devex', additionPaths: ['products/new'] }]+ const body = buildReviewerComment(requested, [], additionOwners)+ assert.ok(body.includes(CONFIG.commentMarker))+ assert.ok(body.includes('- `@PostHog/team-devex` (`products/new`)'))+ assert.ok(!body.includes('soft owners were skipped'))+})++test('buildReviewerComment: keeps a PR-chosen addition path inside its code span', () => {+ const additionOwners = [{ owner: '@PostHog/team-devex', additionPaths: ['products/x` @someone\n\n# hi'] }]+ const body = buildReviewerComment(requested, [], additionOwners)+ assert.ok(body.includes('- `@PostHog/team-devex` (`products/x? @someone??# hi`)'))+})+test('buildReviewerComment: lists each skipped owner as a bullet with its matched rule, not raw counts', () => {const body = buildReviewerComment(requested, demoted)assert.ok(body.includes(CONFIG.commentMarker))diff --git a/packages/owners-yaml/CHANGELOG.md b/packages/owners-yaml/CHANGELOG.mdindex af08b6d16ede..e735d0f24c61 100644--- a/packages/owners-yaml/CHANGELOG.md+++ b/packages/owners-yaml/CHANGELOG.md@@ -7,6 +7,12 @@ Notable changes to the `owners-yaml` package. The format follows`publish-owners-yaml.yml` reads the section matching the tagged version and uses it asthe GitHub Release body, so add the entry here before you cut the tag.+## Unreleased++### Added++- The resolution of a path that the resolver's tree does not hold carries `added`: the first part of the path, from the root, that the tree does not hold as a directory, and the owners of additions there. Resolved against the tree before a change, this names the new directory for every file a change adds, so a consumer can use `additions` without its own tree walk. `null` when the tree holds the path, or when the resolver reads only ownership files. SPEC sections 4 and 7.2 define it.+## 0.3.0### Addeddiff --git a/packages/owners-yaml/README.md b/packages/owners-yaml/README.mdindex a46a65f75dfd..ab4fa3a1b56a 100644--- a/packages/owners-yaml/README.md+++ b/packages/owners-yaml/README.md@@ -112,6 +112,7 @@ rules: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.+Point the resolver at the tree before the change, and it names the new part for you: a path the tree does not hold carries `added`, for example `"added": {"path": "products/new-thing", "additions": ["team-architecture"]}` for `products/new-thing/app.py`. That also covers a new file in an existing directory, and a file that a change replaces with a directory.The root file can also hold repository settings:diff --git a/packages/owners-yaml/SPEC.md b/packages/owners-yaml/SPEC.mdindex f5f79eeb38e7..9d3ea575b140 100644--- a/packages/owners-yaml/SPEC.md+++ b/packages/owners-yaml/SPEC.md@@ -117,16 +117,18 @@ 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 resolver that can see the repository helps with the first: resolved against the version before a change, each path that the change adds carries `added`, the new part of that path (section 4, step 6).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.+6. A consumer that asks about a new directory SHOULD use the owners of additions of the directory itself, not of 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.+ `added` (section 4, step 6) gives the new directory and its owners of additions for any path below it.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@@ -157,6 +159,7 @@ To resolve a path `P`:- `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.+ - `added`: only when the resolver can see which paths the repository holds, and the repository does not hold `P`. Take the ancestors of `P` from the root down. `N` is the first ancestor that the repository does not hold as a directory, or `P` itself when it holds all of them as directories. `added` is `N` and the `additions` of the resolution of `N`. Otherwise, `added` is none.A path is unowned when `owners` is empty and `unowned_by_design` is `false`.@@ -197,7 +200,7 @@ flowchart TDreset --> 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, additions])+ more -- no --> done([Return owners, unowned_by_design, status, source, slack, additions, added])```### 4.3 Conformance@@ -292,7 +295,7 @@ In `owners-yaml`, both `owners resolve --json` and `python -m owners_yaml` imple1. 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 the members `owners`, `status`, `slack`, and `source`. It SHOULD also have the member `additions`. The members are:+3. Each value MUST be an object with the members `owners`, `status`, `slack`, and `source`. It SHOULD also have the members `additions` and `added`. The members are:| Member | Type | Value || ----------- | ---------------- | ---------------------------------------------------------------------------------- |@@ -301,6 +304,7 @@ In `owners-yaml`, both `owners resolve --json` and `python -m owners_yaml` imple| `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. |+ | `added` | object or `null` | `{"path": N, "additions": [...]}` from section 4, step 6, or `null`. |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.@@ -317,7 +321,7 @@ In `owners-yaml`, both `owners resolve --json` and `python -m owners_yaml` imple1. A consumer MUST ignore members that it does not know.2. A resolver MAY add members to a value.3. Removing a member, renaming it, or changing its meaning requires a new version of this specification.-4. A consumer MUST treat a missing `additions` member as an empty array. A resolver that predates the member leaves it out.+4. A consumer MUST treat a missing `additions` member as an empty array, and a missing `added` member as `null`. A resolver that predates a 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@@ -327,6 +331,7 @@ This section describes the reference implementation. It is not part of the forma- 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` and `additions` list. Section 4 allows this removal.- 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.+- It reports `added` when its source can tell whether the repository holds a path, as its disk source does (`TreeSource`). A source that reads only the ownership files reports none. It treats a symbolic link as a file, as git does.- 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 |@@ -473,3 +478,4 @@ rules:- **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 (2026-09): Section 7.1 adds the producer to the resolver request, so a consumer can reach a team's per-producer `notifications` mapping through an entrypoint. No ownership file changes meaning.- **1**, amended (unreleased): Section 3.4 applies every matching rule, field by field. Before, the last matching rule replaced the earlier ones. Section 3.6 adds the optional `additions` field. Section 7.2 adds the `additions` member, and a consumer treats a missing member as empty (section 7.4). Section 4 step 1 removes a trailing `/`, so a request for `docs/` resolves the same as `docs`.+- **1**, amended (unreleased): Section 4, step 6 adds `added`: for a path that the repository does not hold, the first part of it that the repository does not hold as a directory, with its owners of additions. Section 7.2 adds the `added` member, and a consumer treats a missing member as `null` (section 7.4). No ownership file changes meaning.diff --git a/packages/owners-yaml/owners_yaml/__init__.py b/packages/owners-yaml/owners_yaml/__init__.pyindex 3baa08e1db7d..f4f10f70d362 100644--- a/packages/owners-yaml/owners_yaml/__init__.py+++ b/packages/owners-yaml/owners_yaml/__init__.py@@ -5,26 +5,31 @@ from .codeowners import CodeownersProjection, owner_handle, package_dirs_from, pfrom .github import GitHubLookupError, GitHubOrgfrom .matcher import compile_pattern, normalize_path, path_matches_patternfrom .resolver import (+ Addition,BatchOwnershipSource,DiskSource,OwnershipSource,OwnersResolver,+ PathKind,Purpose,RepoRootNotFound,Resolution,TeamChannel,+ TreeSource,team_channel,teams_registry,)from .schema import Producer, RepoSettings, TeamEntry__all__ = [+ "Addition","BatchOwnershipSource","CodeownersProjection","DiskSource","GitHubLookupError","GitHubOrg","OwnersResolver",+ "PathKind","OwnershipSource","Producer","Purpose",@@ -34,6 +39,7 @@ __all__ = ["TeamChannel","TeamEntry","TeamTestCensus",+ "TreeSource","census","compile_pattern","first_team_owner",diff --git a/packages/owners-yaml/owners_yaml/resolver.py b/packages/owners-yaml/owners_yaml/resolver.pyindex 27f1a0c1697e..2e7699b0596f 100644--- a/packages/owners-yaml/owners_yaml/resolver.py+++ b/packages/owners-yaml/owners_yaml/resolver.py@@ -8,13 +8,14 @@ per field. SPEC.md in this package defines the format.from __future__ import annotationsimport sys+import statimport subprocess-from collections.abc import Iterable, Mapping+from collections.abc import Callable, Iterable, Mappingfrom dataclasses import dataclass, fieldfrom pathlib import Path-from typing import Literal, Protocol, TypedDict, runtime_checkable+from typing import Literal, Protocol, TypedDict, cast, runtime_checkable-from .matcher import compile_pattern, normalize_path+from .matcher import SEP, compile_pattern, normalize_pathfrom .schema import (OWNERS_FILENAME,UNSET,@@ -92,6 +93,18 @@ def teams_registry(text: str) -> dict[str, TeamEntry]:return dict(parsed.teams) if parsed is not None else {}+PathKind = Literal["dir", "file"]+++@dataclass(frozen=True)+class Addition:+ """The new part of a path that the resolver's tree does not hold: the path nearest the root that+ the tree lacks, and the owners of additions at that part (SPEC section 3.6)."""++ path: str+ additions: list[str]++@dataclassclass Resolution:"""The resolved ownership of a single path."""@@ -106,6 +119,9 @@ class Resolution:# 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)+ # Set only when the resolver reads a tree and the path is not in it, such as a file that a change+ # adds when the tree is the version before the change.+ added: Addition | None = None@propertydef is_owned(self) -> bool:@@ -127,6 +143,12 @@ class WireResolution(TypedDict):slack: str | Nonesource: str | Noneadditions: list[str]+ added: WireAddition | None+++class WireAddition(TypedDict):+ path: str+ additions: list[str]def resolution_to_wire(r: Resolution) -> WireResolution:@@ -136,6 +158,7 @@ def resolution_to_wire(r: Resolution) -> WireResolution:"slack": r.slack,"source": r.source,"additions": r.additions,+ "added": {"path": r.added.path, "additions": r.added.additions} if r.added is not None else None,}@@ -221,6 +244,14 @@ class BatchOwnershipSource(OwnershipSource, Protocol):def read_all(self, paths: list[str]) -> None: ...+@runtime_checkable+class TreeSource(OwnershipSource, Protocol):+ """A source that can also tell whether the tree holds a path, and as what. The resolver needs+ this to report a path that the tree does not hold (``Resolution.added``)."""++ def path_kind(self, path: str) -> PathKind | None: ...++@dataclass(frozen=True)class DiskSource:"""Ownership files read from a worktree."""@@ -231,6 +262,31 @@ class DiskSource:file = self.repo_root / pathreturn file.read_text() if file.is_file() else None+ def path_kind(self, path: str) -> PathKind | None:+ # lstat does not follow a symlink: git stores a symlink as a file, so a symlink to a+ # directory is a leaf of the tree, and a dangling link still counts as present.+ try:+ mode = (self.repo_root / path).lstat().st_mode+ except (FileNotFoundError, NotADirectoryError):+ return None+ return "dir" if stat.S_ISDIR(mode) else "file"+++def first_new_path(path: str, path_kind: Callable[[str], PathKind | None]) -> str | None:+ """The part of ``path`` nearest the root that the tree does not hold, or None when the tree+ holds ``path``. An ancestor counts as new unless the tree holds it as a directory, so a change+ that replaces the file or symlink ``products/new`` with a directory adds ``products/new``. The+ walk checks the ancestors before the path, because a filesystem check of the full path follows+ a symlinked ancestor and would find a file that the tree does not hold."""+ if not path:+ return None+ parts = path.split(SEP)+ for depth in range(1, len(parts)):+ prefix = SEP.join(parts[:depth])+ if path_kind(prefix) != "dir":+ return prefix+ return None if path_kind(path) is not None else path+# Names a sourceless resolver's files, so a Resolution still reports the path that decided ownership.VIRTUAL_ROOT = Path("/")@@ -263,6 +319,9 @@ class OwnersResolver:self._tracked_cache: dict[str | None, list[str]] = {}self._parsed_ownership: list[ParsedOwnershipFile] | None = Noneself._teams_cache: dict[str, TeamEntry] | None = None+ # Files in one directory share every ancestor, so a full-tree run asks about each+ # directory thousands of times.+ self._path_kind_cache: dict[str, PathKind | None] = {}def alias_files(self) -> tuple[str, ...]:"""The alias file names the root file declares, in the order that decides a tie."""@@ -361,8 +420,7 @@ class OwnersResolver:{OWNERS_FILENAME} | {f"{directory}/{name}" for directory in directories if directory for name in filenames})- def resolve(self, path: str) -> Resolution:- norm = normalize_path(path)+ def _merge(self, norm: str) -> _Merged:merged = _Merged()for f in self._collect_files(norm):@@ -390,7 +448,24 @@ class OwnersResolver:if contrib.additions:merged.additions = _union(merged.additions, contrib.additions)- return self._build_resolution(norm, merged)+ return merged++ def _path_kind(self, path: str) -> PathKind | None:+ if path not in self._path_kind_cache:+ self._path_kind_cache[path] = cast(TreeSource, self.source).path_kind(path)+ return self._path_kind_cache[path]++ def _added(self, path: str) -> Addition | None:+ if not isinstance(self.source, TreeSource):+ return None+ new_path = first_new_path(path, self._path_kind)+ if new_path is None:+ return None+ return Addition(path=new_path, additions=self._merge(new_path).additions)++ def resolve(self, path: str) -> Resolution:+ norm = normalize_path(path)+ return self._build_resolution(norm, self._merge(norm), self._added(norm))def _teams_registry(self) -> dict[str, TeamEntry]:"""The root file's ``teams:`` Slack registry (team slug -> its declared channels),@@ -430,7 +505,7 @@ class OwnersResolver:return team_channel(owners[0], self._teams_registry(), self.purpose, self.producer).channelreturn None- def _build_resolution(self, path: str, merged: _Merged) -> Resolution:+ def _build_resolution(self, path: str, merged: _Merged, added: Addition | None) -> Resolution:unowned_by_design = merged.owners is Noneowners: list[str] | None = None if isinstance(merged.owners, _Unset) else merged.owners@@ -446,6 +521,7 @@ class OwnersResolver:source=merged.source,unowned_by_design=unowned_by_design,additions=merged.additions,+ added=added,)def _rel(self, path: Path) -> str:diff --git a/packages/owners-yaml/resolution.schema.json b/packages/owners-yaml/resolution.schema.jsonindex 1a4fccdb03e7..e758f5a8fa36 100644--- a/packages/owners-yaml/resolution.schema.json+++ b/packages/owners-yaml/resolution.schema.json@@ -28,6 +28,16 @@"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."+ },+ "added": {+ "type": ["object", "null"],+ "required": ["path", "additions"],+ "additionalProperties": false,+ "properties": {+ "path": { "type": "string", "minLength": 1 },+ "additions": { "type": "array", "items": { "type": "string", "minLength": 1 } }+ },+ "description": "When the resolver reads a tree that does not hold the path: the part of the path nearest the root that the tree lacks, and the owners of additions at that part. Null when the tree holds the path or the resolver reads no tree. A consumer treats a missing member as null."}}}diff --git a/packages/owners-yaml/tests/test_owners.py b/packages/owners-yaml/tests/test_owners.pyindex 6efe0743f8a7..3a14aab63181 100644--- a/packages/owners-yaml/tests/test_owners.py+++ b/packages/owners-yaml/tests/test_owners.py@@ -21,7 +21,7 @@ from owners_yaml import ()from owners_yaml.cli import _consolidation_suggestions, _live_scope, _reserved_location_error, mainfrom owners_yaml.fmt import CanonicalPlacer, CanonicalPlan-from owners_yaml.resolver import OwnersResolver, team_channel+from owners_yaml.resolver import DiskSource, OwnersResolver, PathKind, first_new_path, team_channelfrom owners_yaml.schema import (_RULE_KEYS,DEFAULT_ALIAS_FILES,@@ -849,6 +849,7 @@ def test_json_entrypoint_resolves_against_an_explicit_repo_root(registry_repo: P"slack": "#registry-chan","source": "reg/owners.yaml","additions": [],+ "added": {"path": "reg/x.py", "additions": []},}}jsonschema = pytest.importorskip("jsonschema")@@ -909,6 +910,71 @@ def test_both_front_doors_pass_the_producer_to_the_channel_lookup(assert json.loads(output)["mapped/x.py"]["slack"] == channel+ "path,expected",+ [+ ("products/new/sub/a.py", "products/new"),+ ("products/old/c.py", "products/old/c.py"),+ ("products/old/existing.py", None),+ ("products/old", None),+ ("products/was-a-file/a.py", "products/was-a-file"),+ ("products/linked/a.py", "products/linked"),+ ],+ ids=[+ "new-directory",+ "new-file-in-existing-directory",+ "existing-file",+ "existing-directory",+ "file-to-directory",+ "symlink-to-directory",+ ],+)+def test_first_new_path_names_the_part_nearest_the_root_that_the_tree_lacks(path: str, expected: str | None) -> None:+ tree: dict[str, PathKind] = {+ "products": "dir",+ "products/old": "dir",+ "products/old/existing.py": "file",+ "products/was-a-file": "file",+ "products/linked": "file",+ "products/linked/a.py": "file",+ }++ assert first_new_path(path, tree.get) == expected+++def test_disk_source_reports_a_symlink_to_a_directory_as_a_file(tmp_path: Path) -> None:+ _write(tmp_path, "real/a.py", "")+ (tmp_path / "linked").symlink_to(tmp_path / "real", target_is_directory=True)++ source = DiskSource(tmp_path)++ assert source.path_kind("linked") == "file"+ assert source.path_kind("real") == "dir"+ assert first_new_path("linked/a.py", source.path_kind) == "linked"++[email protected]("front_door", ["cli", "module"])+def test_both_front_doors_report_the_new_part_of_a_path_the_tree_lacks(tmp_path: Path, front_door: str) -> None:+ _write(+ tmp_path,+ "owners.yaml",+ "version: 1\nowners: team-root\nrules:\n - match: '/products/*'\n additions: team-arch\n",+ )+ _write(tmp_path, "products/old/owners.yaml", "version: 1\nowners: team-old\n")+ _write(tmp_path, "products/old/x.py", "")++ exit_code, output = _resolve_json(+ front_door, tmp_path, ["products/new/a.py", "products/old/x.py", "products/old/y.py"]+ )++ assert exit_code == 0, output+ wire = json.loads(output)+ assert wire["products/new/a.py"]["added"] == {"path": "products/new", "additions": ["team-arch"]}+ assert wire["products/new/a.py"]["additions"] == []+ assert wire["products/old/x.py"]["added"] is None+ assert wire["products/old/y.py"]["added"] == {"path": "products/old/y.py", "additions": []}++@pytest.mark.parametrize("root", ["nope", ""], ids=["missing", "empty"])def test_json_entrypoint_rejects_a_repo_root_that_is_not_a_directory(registry_repo: Path, root: str) -> None:# An empty root is the unset "$VAR" case: Path("") is Path("."), which would