:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ci): match CODEOWNERS-soft glob handling to GitHub's own semantics (#64228)
Robbieffc1107cb222
diff --git a/.agents/skills/establishing-code-ownership/SKILL.md b/.agents/skills/establishing-code-ownership/SKILL.mdindex 740362fd67a3..e4cd9426d83d 100644--- a/.agents/skills/establishing-code-ownership/SKILL.md+++ b/.agents/skills/establishing-code-ownership/SKILL.md@@ -21,7 +21,7 @@ node $S team team-surveys # every tracked file the team owns (slugnode $S unowned # every tracked file with no owner (append path prefixes to scope, e.g. `unowned products/ frontend/`)```-For glob matching it reuses `fileMatchesPattern` from [`.github/scripts/assign-reviewers.js`](../../../.github/scripts/assign-reviewers.js), the same matcher the reviewer auto-assigner runs in CI, so answers track what CI assigns rather than a separate reimplementation. That matcher is stricter than GitHub's docs: patterns are anchored, a slash-free pattern matches only at the repo root, and a directory needs a trailing slash (or `/**`) to match its contents. A side effect is that the script exposes dead `CODEOWNERS-soft` entries (a missing trailing slash, or escaped `\*\*` wildcards) as unowned, the same way CI silently skips them.+For glob matching it uses the vendored, GitHub-faithful matcher [`.github/scripts/codeowners.js`](../../../.github/scripts/codeowners.js) (a zero-dependency JS port of [hmarr/codeowners](https://github.com/hmarr/codeowners)), the same matcher the reviewer auto-assigner runs in CI, so answers track what CI assigns rather than a separate reimplementation. That matcher reproduces GitHub's own CODEOWNERS rules: a slash-free pattern matches at any depth, a trailing slash matches a directory and its contents, and `dir/*` matches only direct children. So a `CODEOWNERS-soft` entry the script shows as unowned is genuinely dead — both CI and GitHub skip it too, not a quirk of a stricter local matcher.Precedence: `product.yaml` for `products/<name>/**`; else a blocking `CODEOWNERS` owner; else the last-matching `CODEOWNERS-soft` rule. A blocking `CODEOWNERS` glob with **no owner** (a reset, e.g. `posthog/hogql/database/schema/**`) only clears the blocking owner, it does not erase a soft mapping. `file` prints the source line behind each answer.diff --git a/.agents/skills/establishing-code-ownership/ownership.js b/.agents/skills/establishing-code-ownership/ownership.jsindex 3257abbe8281..59f598e2668d 100755--- a/.agents/skills/establishing-code-ownership/ownership.js+++ b/.agents/skills/establishing-code-ownership/ownership.js@@ -12,12 +12,13 @@// only the blocking owner; it does not erase a soft mapping.// 3. No owner from either file means unowned.//-// Glob matching is NOT reimplemented here: it reuses fileMatchesPattern from-// .github/scripts/assign-reviewers.js, the same matcher PostHog's reviewer-// auto-assigner runs in CI, so answers stay in lockstep with what CI assigns.-// That matcher is intentionally stricter than GitHub's docs: patterns are-// anchored, a slash-free pattern matches only at the root, and a directory must-// carry a trailing slash (or /**) to match its contents.+// Glob matching is NOT reimplemented here: it uses the vendored, GitHub-faithful+// matcher in .github/scripts/codeowners.js (a JS port of hmarr/codeowners), the+// same matcher PostHog's reviewer auto-assigner runs in CI, so answers stay in+// lockstep with what CI assigns. It reproduces GitHub's own CODEOWNERS rules (a+// slash-free pattern matches at any depth, a trailing slash matches a directory+// and its contents, `dir/*` matches only direct children), so a dead entry here+// is dead for GitHub too — not a quirk of a stricter local matcher.//// Usage:// ownership.js file <path>... [--all] who owns these files@@ -45,10 +46,7 @@ function findRepoRoot(start) {}const REPO_ROOT = findRepoRoot(__dirname)-const { fileMatchesPattern } = require(path.join(REPO_ROOT, '.github', 'scripts', 'assign-reviewers.js'))-if (typeof fileMatchesPattern !== 'function') {- throw new Error('.github/scripts/assign-reviewers.js no longer exports fileMatchesPattern; ownership resolver is out of sync with CI')-}+const { CodeOwners, pathMatchesPattern } = require(path.join(REPO_ROOT, '.github', 'scripts', 'codeowners.js'))// Bare product.yaml slug -> @PostHog/<slug>; an explicit @handle is left as-is.function toHandle(owner) {@@ -62,17 +60,6 @@ function toSlug(owner) {return owner}-// Literal prefix before the first glob wildcard. The matcher anchors `^`, so a-// file can only match a rule if it starts with this; checking it first skips the-// regex build for non-candidates and keeps a full-repo sweep fast.-function literalPrefix(pattern) {- const i = pattern.search(/[*?]/)- if (i === -1) return pattern- // The matcher leaves `?` as a regex quantifier (it makes the preceding char- // optional), so the guaranteed literal prefix ends one char earlier there.- return pattern[i] === '?' ? pattern.slice(0, Math.max(0, i - 1)) : pattern.slice(0, i)-}-function parseCodeowners(file, label) {if (!fs.existsSync(file)) return []const rules = []@@ -87,7 +74,6 @@ function parseCodeowners(file, label) {owners: tokens.slice(1),source: label,lineno: idx + 1,- prefix: literalPrefix(tokens[0]),})})return rules@@ -156,15 +142,11 @@ class Resolver {this.softRules = parseCodeowners(path.join(root, '.github', 'CODEOWNERS-soft'), 'CODEOWNERS-soft')this.hardRules = parseCodeowners(path.join(root, '.github', 'CODEOWNERS'), 'CODEOWNERS')this.rules = this.softRules.concat(this.hardRules)- }-- lastMatch(rules, file) {- for (let i = rules.length - 1; i >= 0; i--) {- const rule = rules[i]- if (!file.startsWith(rule.prefix)) continue- if (fileMatchesPattern(file, rule.pattern)) return rule- }- return null+ // CodeOwners precompiles a matcher per rule, so the full-repo passes+ // (team/unowned) test thousands of files without recompiling. matchingRule+ // returns the same rich rule objects parsed above (with source + lineno).+ this.softMatcher = new CodeOwners(this.softRules)+ this.hardMatcher = new CodeOwners(this.hardRules)}resolve(file) {@@ -174,9 +156,9 @@ class Resolver {return { owners: this.productOwners.get(name), source: `products/${name}/product.yaml`, reset: false }}}- const hard = this.lastMatch(this.hardRules, file)+ const hard = this.hardMatcher.matchingRule(file)if (hard && hard.owners.length) return { owners: hard.owners, source: src(hard), reset: false }- const soft = this.lastMatch(this.softRules, file)+ const soft = this.softMatcher.matchingRule(file)if (soft && soft.owners.length) return { owners: soft.owners, source: src(soft), reset: false }const reset = hard || softif (reset) return { owners: [], source: src(reset), reset: true }@@ -184,7 +166,7 @@ class Resolver {}allMatches(file) {- return this.rules.filter((rule) => file.startsWith(rule.prefix) && fileMatchesPattern(file, rule.pattern))+ return this.rules.filter((rule) => pathMatchesPattern(rule.pattern, file))}}diff --git a/.github/CODEOWNERS b/.github/CODEOWNERSindex 92898f4d9a9f..e5f48582a059 100644--- a/.github/CODEOWNERS+++ b/.github/CODEOWNERS@@ -31,6 +31,8 @@ posthog/hogql/database/test/__snapshots__/test_database.ambr# We must be careful to only execute code from this repo's default branch, and never execute code from the PR's branch..github/workflows/auto-assign-reviewers.yml @PostHog/team-security.github/scripts/assign-reviewers.js @PostHog/team-security+# The vendored CODEOWNERS matcher the auto-assigner (and the ownership skill) depend on.+.github/scripts/codeowners.js @PostHog/team-security# And of course modifying this file can bring us problems so let's have the security team own it.# This does not affect CODEOWNERS-soft which is used for assigning non-required reviewers and it's much safer to change.diff --git a/.github/scripts/assign-reviewers.js b/.github/scripts/assign-reviewers.jsindex 04a13bae04c2..e81f28ab6c6e 100644--- a/.github/scripts/assign-reviewers.js+++ b/.github/scripts/assign-reviewers.js@@ -1,6 +1,7 @@#!/usr/bin/env nodeconst fs = require('fs')+const { parse, pathMatchesPattern } = require('./codeowners')// Tunable knobs for how aggressively we trim the reviewer list. Kept in one// place so adjusting noise levels doesn't require re-reading the logic. All@@ -38,29 +39,9 @@ function parseCodeowners(codeownersPath) {if (!fs.existsSync(codeownersPath)) {throw new Error(`No CODEOWNERS file found at "${codeownersPath}"`)}-- const content = fs.readFileSync(codeownersPath, 'utf8')- const rules = []-- for (const line of content.split('\n')) {- const trimmed = line.trim()-- if (!trimmed || trimmed.startsWith('#')) {- continue- }-- const tokens = trimmed.split(/\s+/)- if (tokens.length < 2) {- continue- }-- const pattern = tokens[0]- const owners = tokens.slice(1)-- rules.push({ pattern, owners })- }-- return rules+ // Rules with no owner are reset directives that only matter for hard/soft+ // precedence (see ownership.js); the assigner only cares about owned rules.+ return parse(fs.readFileSync(codeownersPath, 'utf8')).rules.filter((rule) => rule.owners.length > 0)}// Minimal parser for the `owners:` list in products/<name>/product.yaml.@@ -147,27 +128,17 @@ function loadProductYamlRules(productsDir = 'products') {return rules}-function globToRegex(pattern) {- let regex = pattern- .replace(/[.+^${}()|[\]\\]/g, '\\$&')- .replace(/\*\*/g, '__DOUBLESTAR__')- .replace(/\*/g, '[^/]*')- .replace(/__DOUBLESTAR__/g, '.*')-- // A trailing-slash pattern is a directory: keep the slash so it matches only- // files inside the directory, not sibling paths sharing the name as a prefix- // (e.g. `models/ai/` must not match `models/ai_events/`). Mirrors GitHub's- // own CODEOWNERS semantics, where `dir/` is a directory boundary.- if (pattern.endsWith('/')) {- regex = regex + '.*'- }-- return new RegExp(`^${regex}$`)-}-+// Glob matching lives in the vendored, GitHub-faithful matcher (./codeowners.js,+// a JS port of hmarr/codeowners). Thin wrapper so the rest of the assigner reads+// naturally and the (filePath, pattern) argument order is stable. A malformed+// pattern (e.g. a `***` typo) degrades to "no match" rather than aborting the+// whole run, matching how the vendored CodeOwners class treats batch rules.function fileMatchesPattern(filePath, pattern) {- const regex = globToRegex(pattern)- return regex.test(filePath)+ try {+ return pathMatchesPattern(pattern, filePath)+ } catch {+ return false+ }}function isExcludedFile(filePath, excludedPatterns = CONFIG.excludedPatterns) {diff --git a/.github/scripts/codeowners.js b/.github/scripts/codeowners.jsnew file mode 100644index 000000000000..f37ecf074b16--- /dev/null+++ b/.github/scripts/codeowners.js@@ -0,0 +1,383 @@+// GitHub-faithful CODEOWNERS parser and matcher.+// From https://github.com/posthog/codeowners, a JS port of https://github.com/hmarr/codeowners+// Matching algorithm tracks hmarr/codeowners@b0f609d (pinned in testdata/.hmarr-sha).+// This is a standalone JS file with no dependencies, for easy vendoring.++'use strict'++/**+ * A single parsed CODEOWNERS rule.+ * @typedef {Object} CodeOwnerRule+ * @property {string} pattern The raw pattern, e.g. `docs/*` or `/build/logs/`.+ * @property {string[]} owners Owners as written, e.g. `@org/team`, `@user`, `[email protected]`.+ * @property {number} lineNumber 1-based line number in the source text.+ */++/**+ * @typedef {Object} CompiledMatcher+ * @property {(testPath: string) => boolean} test+ */++const SEP = '/'++/** @param {string} ch */+function quoteMeta(ch) {+ return /[.*+?^${}()|[\]\\]/.test(ch) ? '\\' + ch : ch+}++/**+ * Normalize a pattern into its GitHub-semantics path segments, applying the+ * leading-slash (root-anchor), slash-free (`**` prefix), and trailing-slash+ * (`**` suffix) rules. Shared by {@link patternToRegExp} and the runtime+ * matcher so the two cannot drift. Throws on the invalid patterns GitHub+ * rejects; `/` is handled by callers (it matches nothing) and not passed here.+ * @param {string} pattern+ * @returns {string[]}+ */+function patternToSegments(pattern) {+ if (pattern.includes('***')) {+ throw new Error('pattern cannot contain three consecutive asterisks')+ }+ if (pattern === '') {+ throw new Error('empty pattern')+ }++ let segs = pattern.split(SEP)++ if (segs[0] === '') {+ // Leading slash anchors to the repo root: drop the empty first segment.+ segs = segs.slice(1)+ } else if (segs.length === 1 || (segs.length === 2 && segs[1] === '')) {+ // A slash-free name (`foo`, `foo/`, `*.js`) matches at any depth, so it+ // behaves as if prefixed with `**/`.+ if (segs[0] !== '**') {+ segs = ['**', ...segs]+ }+ }++ if (segs.length > 1 && segs[segs.length - 1] === '') {+ // A trailing slash means "this directory and everything under it".+ segs[segs.length - 1] = '**'+ }++ // Collapse runs of consecutive `**` (from `a/**/**/b`, or a `foo/**/` whose+ // trailing slash became a second `**`) into one. They are semantically+ // identical to a single `**`, and two adjacent `**` would otherwise compile+ // to a degenerate, never-matching regex.+ const collapsed = []+ for (const seg of segs) {+ if (seg === '**' && collapsed[collapsed.length - 1] === '**') continue+ collapsed.push(seg)+ }+ return collapsed+}++/**+ * Translate a CODEOWNERS pattern into an anchored RegExp, mirroring GitHub's+ * segment semantics (and hmarr/codeowners' regex construction verbatim).+ *+ * This faithfully reproduces hmarr's `.+`-based `**` expansion, which is linear+ * under Go's RE2 but can backtrack super-linearly under JS's engine on adversarial+ * inputs (multiple non-terminal `**` segments against a deep non-matching path).+ * It is therefore kept for inspection, testing, and as the semantic reference;+ * the runtime matcher ({@link compilePattern}) uses an equivalent linear+ * segment-matcher instead. Most callers want {@link parse}.+ * @param {string} pattern+ * @returns {RegExp}+ */+function patternToRegExp(pattern) {+ if (pattern === '/') {+ // Matches the empty string only, i.e. nothing. (gitignore parity.)+ return /^$/+ }++ const segs = patternToSegments(pattern)+ const lastSegIndex = segs.length - 1+ let needSlash = false+ let re = '^'++ for (let i = 0; i < segs.length; i++) {+ const seg = segs[i]+ if (seg === '**') {+ if (i === 0 && i === lastSegIndex) {+ re += '.+'+ } else if (i === 0) {+ re += '(?:.+' + SEP + ')?'+ needSlash = false+ } else if (i === lastSegIndex) {+ re += SEP + '.*'+ } else {+ re += '(?:' + SEP + '.+)?'+ needSlash = true+ }+ continue+ }++ if (seg === '*') {+ if (needSlash) re += SEP+ re += '[^' + SEP + ']+'+ needSlash = true+ continue+ }++ // Literal segment, which may still contain `*`, `?`, or `\` escapes.+ if (needSlash) re += SEP+ let escape = false+ for (const ch of seg) {+ if (escape) {+ escape = false+ re += quoteMeta(ch)+ } else if (ch === '\\') {+ escape = true+ } else if (ch === '*') {+ re += '[^' + SEP + ']*'+ } else if (ch === '?') {+ re += '[^' + SEP + ']'+ } else {+ re += quoteMeta(ch)+ }+ }+ if (i === lastSegIndex) {+ // A literal final segment matches the path itself or anything under+ // it, so `/apps/github` owns `apps/github` and `apps/github/x`.+ re += '(?:' + SEP + '.*)?'+ }+ needSlash = true+ }++ re += '$'+ return new RegExp(re)+}++/**+ * Compile a single pattern segment (a literal that may contain `*`, `?`, or+ * `\` escapes) into an anchored RegExp matching exactly one path segment. The+ * segment never contains a `/`, so this regex cannot backtrack across segments.+ * @param {string} seg+ * @returns {RegExp}+ */+function segToRegExp(seg) {+ let re = '^'+ let escape = false+ for (const ch of seg) {+ if (escape) {+ escape = false+ re += quoteMeta(ch)+ } else if (ch === '\\') {+ escape = true+ } else if (ch === '*') {+ re += '[^' + SEP + ']*'+ } else if (ch === '?') {+ re += '[^' + SEP + ']'+ } else {+ re += quoteMeta(ch)+ }+ }+ re += '$'+ return new RegExp(re)+}++/**+ * One token of a compiled pattern: `**` (zero or more whole segments), `*`+ * (exactly one segment), or a literal segment with its single-segment test.+ * @typedef {Object} GlobToken+ * @property {'star' | 'one' | 'lit'} type+ * @property {(seg: string) => boolean} test Unused for `star`.+ */++/**+ * Match a tokenized pattern against a path's segments, with no backtracking+ * across segments: a bottom-up scan of `dp[ti][pi]` ("can tokens[ti..] match+ * segs[pi..]"), O(tokens × segments). This is the linear equivalent of the+ * {@link patternToRegExp} regex — it encodes the same `**`/`*`/literal rules,+ * including that a `**` tail (and `**` alone) requires at least one remaining+ * segment and that a literal final segment also owns its subtree — but cannot+ * blow up on adversarial multi-`**` patterns the way a backtracking regex does.+ * @param {GlobToken[]} tokens+ * @param {string[]} pathSegs+ * @returns {boolean}+ */+function globMatch(tokens, pathSegs) {+ const m = tokens.length+ const n = pathSegs.length+ // next holds dp[ti + 1][*]; seed it with dp[m][pi] = (no tokens left, so the+ // path must be exhausted).+ let next = new Array(n + 1)+ for (let pi = 0; pi <= n; pi++) next[pi] = pi === n+ for (let ti = m - 1; ti >= 0; ti--) {+ const tok = tokens[ti]+ const isLast = ti === m - 1+ const cur = new Array(n + 1).fill(false)+ if (tok.type === 'star') {+ if (isLast) {+ // A trailing `**` (`/.*`) consumes every remaining segment but+ // needs at least one; this also covers `**` as the whole pattern.+ for (let pi = 0; pi <= n; pi++) cur[pi] = n - pi >= 1+ } else {+ // `**` matches zero or more whole segments.+ cur[n] = next[n]+ for (let pi = n - 1; pi >= 0; pi--) cur[pi] = next[pi] || cur[pi + 1]+ }+ } else {+ // `*` and literal tokens each match exactly one segment.+ for (let pi = 0; pi < n; pi++) {+ if (!tok.test(pathSegs[pi])) continue+ // A literal final segment owns the matched path and its subtree,+ // so trailing segments are fine; everything else must line up.+ cur[pi] = isLast && tok.type === 'lit' ? true : next[pi + 1]+ }+ }+ next = cur+ }+ return next[0]+}++/**+ * Compile a wildcard pattern into a linear, backtrack-free matcher equivalent+ * to {@link patternToRegExp}. Throws on the same invalid patterns.+ * @param {string} pattern+ * @returns {CompiledMatcher}+ */+function compileGlob(pattern) {+ if (pattern === '/') {+ // Matches the empty string only, i.e. nothing. (gitignore parity.)+ return { test: (testPath) => testPath === '' }+ }+ /** @type {GlobToken[]} */+ const tokens = patternToSegments(pattern).map((seg) => {+ if (seg === '**') return { type: 'star', test: () => false }+ if (seg === '*') return { type: 'one', test: (s) => s.length >= 1 }+ const re = segToRegExp(seg)+ return { type: 'lit', test: (s) => re.test(s) }+ })+ return {+ test(testPath) {+ return globMatch(tokens, testPath === '' ? [] : testPath.split(SEP))+ },+ }+}++/**+ * Compile a pattern to a matcher, using a fast literal path for left-anchored+ * patterns with no wildcards (the common case in real CODEOWNERS files), and a+ * linear segment-matcher otherwise (see {@link globMatch}).+ * @param {string} pattern+ * @returns {CompiledMatcher}+ */+function compilePattern(pattern) {+ if (!/[*?\\]/.test(pattern) && pattern.startsWith('/')) {+ let prefix = pattern.slice(1)+ return {+ test(testPath) {+ if (prefix === '') return false+ if (prefix.endsWith(SEP)) return testPath.startsWith(prefix)+ if (testPath.length === prefix.length) return testPath === prefix+ if (testPath.length > prefix.length && testPath[prefix.length] === SEP) {+ return testPath.slice(0, prefix.length) === prefix+ }+ return false+ },+ }+ }+ return compileGlob(pattern)+}++/** A matcher that owns nothing; used as the fallback for an invalid pattern. */+const NEVER_MATCH = { test: () => false }++/**+ * Like {@link compilePattern} but never throws: an invalid pattern (e.g. one+ * containing `***`) compiles to a never-match rule instead. Used for batch+ * compilation of a whole file, where one malformed line must not take the rest+ * of the rules down with it. Callers validating a single pattern want the+ * throwing {@link compilePattern} / {@link patternToRegExp} instead.+ * @param {string} pattern+ * @returns {CompiledMatcher}+ */+function compilePatternSafe(pattern) {+ try {+ return compilePattern(pattern)+ } catch {+ return NEVER_MATCH+ }+}++/**+ * Test whether a single CODEOWNERS pattern matches a repo-relative path. A+ * convenience for one-off checks and for validating patterns; most callers want+ * {@link parse} so that last-match-wins precedence is applied.+ * @param {string} pattern+ * @param {string} filePath A repo-relative path (a leading `/` is tolerated).+ * @returns {boolean}+ */+function pathMatchesPattern(pattern, filePath) {+ return compilePattern(pattern).test(normalizePath(filePath))+}++/** @param {string} filePath */+function normalizePath(filePath) {+ let p = filePath.replace(/\\/g, SEP)+ while (p.startsWith('./')) p = p.slice(2)+ while (p.startsWith(SEP)) p = p.slice(1)+ return p+}++class CodeOwners {+ /**+ * @param {CodeOwnerRule[]} rules+ */+ constructor(rules) {+ /** @type {CodeOwnerRule[]} */+ this.rules = rules+ // Compile defensively: a single malformed pattern becomes a never-match+ // rule rather than throwing, so one bad CODEOWNERS line cannot abort+ // owner resolution for every other rule (and every other PR).+ /** @type {CompiledMatcher[]} */+ this._matchers = rules.map((rule) => compilePatternSafe(rule.pattern))+ }++ /**+ * The last rule that matches `filePath`, or null if none. Last-match-wins is+ * GitHub's precedence rule.+ * @param {string} filePath A repo-relative path (a leading `/` is tolerated).+ * @returns {CodeOwnerRule | null}+ */+ matchingRule(filePath) {+ const p = normalizePath(filePath)+ for (let i = this.rules.length - 1; i >= 0; i--) {+ if (this._matchers[i].test(p)) return this.rules[i]+ }+ return null+ }++ /**+ * Owners of `filePath`, or an empty array if unowned.+ * @param {string} filePath+ * @returns {string[]}+ */+ ownersOf(filePath) {+ const rule = this.matchingRule(filePath)+ return rule ? rule.owners : []+ }+}++/**+ * Parse CODEOWNERS file contents into a {@link CodeOwners} matcher.+ * @param {string} text+ * @returns {CodeOwners}+ */+function parse(text) {+ /** @type {CodeOwnerRule[]} */+ const rules = []+ const lines = text.split(/\r?\n/)+ for (let i = 0; i < lines.length; i++) {+ const trimmed = lines[i].trim()+ // Only whole-line comments; GitHub does not support escaping a leading #.+ if (trimmed === '' || trimmed.startsWith('#')) continue+ const tokens = trimmed.split(/\s+/)+ rules.push({ pattern: tokens[0], owners: tokens.slice(1), lineNumber: i + 1 })+ }+ return new CodeOwners(rules)+}++module.exports = { parse, CodeOwners, patternToRegExp, pathMatchesPattern }