Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

feat(owners)!: prioritize CODEOWNERS in owner suggestions (#1519)

jameshiester-oaidd50e6bcefe9
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 92e94d961..067e6e46d 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -542,7 +542,8 @@ checkpointing, and publication behavior.
### Suggest finding owners
Use `suggest-owners` or the SDK's `suggestOwners()` to suggest contributors based
-on source and Git history. Suggestions do not assign tickets. See
+on CODEOWNERS, source, and Git history. Declared owners take priority over Git
+contributors. Suggestions do not assign tickets. See
[owner suggestions](docs/cli.md#suggest-finding-owners) for input and output examples.
### Publish findings to Cloud
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index 0cf040af6..cd7bebcfd 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -1155,7 +1155,7 @@ codex-security suggest-owners findings.json --source-root /path/to/repo --json >
Input is a findings document or `{ "findings": [...] }`. The source root
defaults to the current directory. The command reads committed `HEAD`, relevant
-source, blame, and history; it does not read uncommitted source or assign tickets.
+source, CODEOWNERS, blame, and history; it does not read uncommitted source or assign tickets.
Finding location paths are relative to the Git worktree root, including when
`--source-root` points to a subdirectory. A location for `src/handler.ts` keeps
that prefix; a location of `handler.ts` refers to the root file. Rebase imported
@@ -1165,11 +1165,35 @@ owners.
Linked worktrees and bound separate Git directories are supported; borrowed
external object stores such as `git clone --shared` are rejected.
+CODEOWNERS declarations take priority over Git history, following
+[GitHub's CODEOWNERS rules](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners).
+The last matching rule wins, and the command returns its first declared owner.
+Git history is the fallback when no declared owner applies.
+
Results preserve IDs and report `identified`, `abstained`, or `error`. Identified
-owners include an observed Git name/email, reason, and checked citations.
+owners include a declared GitHub user, team, or email, or an observed Git
+name/email, with a reason and checked citations.
Git identities do not establish current employment or tracker accounts; match
accounts before assigning. Use a checkout matching the findings.
+An owner can be a Git name/email identity, a GitHub user or team handle,
+an email-only identity, or `null`. Example JSON excerpt:
+
+```json
+{
+ "schemaVersion": 2,
+ "results": [
+ {
+ "owner": {
+ "kind": "group",
+ "provider": "github",
+ "handle": "example/maintainers"
+ }
+ }
+ ]
+}
+```
+
The command uses scan-default model/effort; override with `--model` and `--effort`.
The model receives collected evidence with tools/network disabled. Exit `0`
includes abstentions; `2` means invalid input or a failed recommendation, while
@@ -1181,6 +1205,10 @@ import { suggestOwners } from "@openai/codex-security";
const owners = await suggestOwners("/path/to/repo", result.findings.findings, {
reasoningEffort: "high",
});
+for (const { owner } of owners.results) {
+ if (owner === null) continue;
+ console.log("handle" in owner ? owner.handle : owner.email);
+}
```
SDK inputs can include `sourceRevision`. If it differs from `HEAD`, the collector
diff --git a/sdk/typescript/scripts/fixtures/package-consumer.ts b/sdk/typescript/scripts/fixtures/package-consumer.ts
index cb0dccdea..c674612af 100644
--- a/sdk/typescript/scripts/fixtures/package-consumer.ts
+++ b/sdk/typescript/scripts/fixtures/package-consumer.ts
@@ -18,6 +18,9 @@ import {
publishScan,
runComponentScans,
resolveProjectConfig,
+ suggestOwners,
+ type OwnerFinding,
+ type OwnerSuggestion,
type ComponentScanOptions,
type DeduplicateScanResult,
type CustomPublicationResult,
@@ -273,3 +276,28 @@ export async function dedupeRecords(
};
return await deduplicateRecords(input, { reviewRunner, signal });
}
+
+export const ownerVariants: OwnerSuggestion["owner"][] = [
+ { name: "Alex Example", email: "[email protected]" },
+ { kind: "person", provider: "github", handle: "example-user" },
+ { kind: "group", provider: "github", handle: "example/maintainers" },
+ { kind: "person", email: "[email protected]" },
+ null,
+];
+
+export function ownerIdentifier(owner: OwnerSuggestion["owner"]) {
+ if (owner === null) return null;
+ return "handle" in owner ? owner.handle : owner.email;
+}
+
+export async function suggestFindingOwners(
+ repository: string,
+ findings: OwnerFinding[],
+) {
+ const report = await suggestOwners(repository, findings);
+ const schemaVersion: 2 = report.schemaVersion;
+ return {
+ schemaVersion,
+ identifiers: report.results.map(({ owner }) => ownerIdentifier(owner)),
+ };
+}
diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjs
index e9f85a496..516cb2801 100644
--- a/sdk/typescript/scripts/package-dist-files.mjs
+++ b/sdk/typescript/scripts/package-dist-files.mjs
@@ -8,6 +8,7 @@ const distModules = [
"cli-scan-logs-json",
"cli-signals",
"classify-severity",
+ "codeowners",
"classify-scan-severity",
"severity-store",
"cloud-publish",
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index cc54b556f..4b33620f6 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -3813,7 +3813,7 @@ export async function main(
.command(findingFeedback)
.command(publication)
.command("suggest-owners", {
- description: "Suggest finding owners from source and Git history.",
+ description: "Suggest finding owners from CODEOWNERS and Git history.",
destructive: false,
mcp: false,
args: z.object({
diff --git a/sdk/typescript/src/codeowners.ts b/sdk/typescript/src/codeowners.ts
new file mode 100644
index 000000000..4c3f10bc2
--- /dev/null
+++ b/sdk/typescript/src/codeowners.ts
@@ -0,0 +1,142 @@
+export type CodeownerIdentity =
+ | { kind: "person" | "group"; provider: "github"; handle: string }
+ | { kind: "person"; email: string };
+
+export interface CodeownersRule {
+ pattern: string;
+ line: number;
+ rule: string;
+ owners: CodeownerIdentity[];
+ matches: (path: string) => boolean;
+}
+
+/** GitHub CODEOWNERS uses the last matching rule, including ownerless rules. */
+export function parseCodeowners(source: string): CodeownersRule[] {
+ const rules: CodeownersRule[] = [];
+ for (const [index, line] of source.split(/\r?\n/u).entries()) {
+ const value = line.trim();
+ if (!value || value.startsWith("#")) continue;
+ const token = /^(?:\\.|[^\s])+/u.exec(value)![0];
+ const matches = codeownersPattern(token);
+ if (matches === null) continue;
+ const handles = value
+ .slice(token.length)
+ .split("#", 1)[0]!
+ .trim()
+ .split(/\s+/u)
+ .filter(Boolean);
+ const owners: CodeownerIdentity[] = [];
+ let valid = true;
+ for (const handle of handles) {
+ if (/^@[a-z\d](?:[a-z\d_-]*[a-z\d])?(?:\/[a-z\d_.-]+)?$/iu.test(handle)) {
+ owners.push(
+ handle.includes("/")
+ ? { kind: "group", provider: "github", handle: handle.slice(1) }
+ : { kind: "person", provider: "github", handle: handle.slice(1) },
+ );
+ } else if (/^[^@\s]+@[^@\s]+$/u.test(handle)) {
+ owners.push({ kind: "person", email: handle });
+ } else {
+ valid = false;
+ break;
+ }
+ }
+ if (valid)
+ rules.push({
+ pattern: token,
+ line: index + 1,
+ rule: line,
+ owners,
+ matches,
+ });
+ }
+ return rules;
+}
+
+type PatternToken = { literal: string } | "*" | "?" | "**" | "**/";
+
+function codeownersPattern(pattern: string): CodeownersRule["matches"] | null {
+ if (pattern.startsWith("!") || pattern.startsWith("\\#")) return null;
+ const anchored = pattern.startsWith("/");
+ if (anchored) pattern = pattern.slice(1);
+ const directory = pattern.endsWith("/");
+ if (directory) pattern = pattern.slice(0, -1);
+ const rooted = anchored || pattern.includes("/");
+ const immediate = /(?:^|\/)[*?]$/u.test(pattern);
+ const characters = Array.from(pattern);
+ const tokens: PatternToken[] = [];
+ for (let index = 0; index < characters.length; index++) {
+ const character = characters[index]!;
+ if (character === "\\" && index + 1 < characters.length) {
+ tokens.push({ literal: characters[++index]! });
+ } else if (
+ character === "[" ||
+ character === "]" ||
+ (character === "*" &&
+ characters[index + 1] === "*" &&
+ characters[index + 2] === "*")
+ ) {
+ return null;
+ } else if (
+ character === "*" &&
+ characters[index + 1] === "*" &&
+ (index === 0 || characters[index - 1] === "/") &&
+ (index + 2 === characters.length || characters[index + 2] === "/")
+ ) {
+ if (characters[index + 2] === "/") {
+ tokens.push("**/");
+ index += 2;
+ } else {
+ tokens.push("**");
+ index++;
+ }
+ } else if (character === "*" || character === "?") tokens.push(character);
+ else tokens.push({ literal: character });
+ }
+ return (path) => {
+ let active = new Set([0]);
+ let next = new Set<number>();
+ // Deduplicate reachable positions: O(pattern * path) work and O(pattern)
+ // space, including when several wildcards can consume the same character.
+ for (let offset = 0; ;) {
+ const boundary = offset === 0 || path[offset - 1] === "/";
+ if (!rooted && boundary) active.add(0);
+ for (const index of active) {
+ const token = tokens[index];
+ if (token === "*" || token === "**" || (token === "**/" && boundary))
+ active.add(index + 1);
+ }
+ const end = offset === path.length;
+ // docs/* ends at the immediate child; service* may own a directory.
+ if (
+ active.has(tokens.length) &&
+ (directory
+ ? path[offset] === "/"
+ : end || (!immediate && path[offset] === "/"))
+ )
+ return true;
+ if (end) return false;
+ const character = String.fromCodePoint(path.codePointAt(offset)!);
+ next.clear();
+ for (const index of active) {
+ const token = tokens[index];
+ if (token === undefined) continue;
+ if (typeof token === "object") {
+ if (token.literal === character) next.add(index + 1);
+ } else if (token === "?") {
+ if (character !== "/") next.add(index + 1);
+ } else if (token !== "*" || character !== "/") next.add(index);
+ }
+ if (rooted && next.size === 0) return false;
+ [active, next] = [next, active];
+ offset += character.length;
+ }
+ };
+}
+
+export function codeownersForPath(
+ rules: readonly CodeownersRule[],
+ path: string,
+): CodeownersRule | undefined {
+ return rules.findLast(({ matches }) => matches(path));
+}
diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts
index 59c889c26..253402aee 100644
--- a/sdk/typescript/src/index.ts
+++ b/sdk/typescript/src/index.ts
@@ -18,6 +18,7 @@ export { classifySeverity } from "./classify-severity.js";
export { suggestOwners } from "./suggest-owners.js";
export type {
OwnerFinding,
+ CodeownerIdentity,
OwnerIdentity,
OwnerSuggestion,
OwnerSuggestions,
diff --git a/sdk/typescript/src/owner-evidence.ts b/sdk/typescript/src/owner-evidence.ts
index 4beeb1e1d..88e22daf2 100644
--- a/sdk/typescript/src/owner-evidence.ts
+++ b/sdk/typescript/src/owner-evidence.ts
@@ -13,6 +13,11 @@ import {
validatedGitEnvironment,
} from "./targets.js";
import { resolveTrustedExecutable } from "./trusted-executable.js";
+import {
+ codeownersForPath,
+ parseCodeowners,
+ type CodeownerIdentity,
+} from "./codeowners.js";
const execFile = promisify(execFileCallback);
@@ -23,11 +28,13 @@ export interface OwnerIdentity {
export interface OwnerEvidence {
id: string;
- kind: "source" | "blame" | "history";
+ kind: "source" | "blame" | "history" | "codeowners";
path: string;
commit: string;
startLine?: number;
endLine?: number;
+ rule?: string;
+ matchedPath?: string;
content: string;
identityIndex: number | null;
}
@@ -36,6 +43,7 @@ export interface OwnerContext {
identities: OwnerIdentity[];
evidence: OwnerEvidence[];
limitations: string[];
+ codeowner: CodeownerIdentity | null;
}
/** Read committed objects, so dirty files and source symlinks are never followed. */
@@ -113,7 +121,28 @@ export async function ownerRepository(
// Latin-1 keys preserve Git's filename bytes, including unrelated non-UTF-8 names.
const hasFile = (path: string) =>
path.isWellFormed() && files.has(Buffer.from(path).toString("latin1"));
- return { git, revision, hasFile, shallow };
+ const loadCodeowners = async () => {
+ const path = [".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS"].find(
+ hasFile,
+ );
+ if (path === undefined) return null;
+ const source = await git("cat-file", "blob", `${revision}:${path}`);
+ // GitHub requires CODEOWNERS to be under 3 MB.
+ return {
+ path,
+ rules:
+ Buffer.byteLength(source) >= 3_000_000 ? null : parseCodeowners(source),
+ };
+ };
+ let codeowners: ReturnType<typeof loadCodeowners> | undefined;
+ return {
+ git,
+ revision,
+ hasFile,
+ shallow,
+ // Keep the load lazy so failures remain inside per-finding error handling.
+ codeowners: () => (codeowners ??= loadCodeowners()),
+ };
}
/** Neither references nor objects may link into another checkout. */
@@ -163,6 +192,7 @@ export async function collectOwnerEvidence(
const context: OwnerContext = {
identities: [],
evidence: [],
+ codeowner: null,
limitations: [
"Git authors are not verified tracker accounts or proof of current employment.",
],
@@ -189,6 +219,38 @@ export async function collectOwnerEvidence(
const add = (item: Omit<OwnerEvidence, "id">) => {
context.evidence.push({ id: `e${context.evidence.length + 1}`, ...item });
};
+ const codeowners = await repository.codeowners();
+ if (codeowners !== null) {
+ if (codeowners.rules === null) {
+ context.limitations.push(
+ "CODEOWNERS meets or exceeds GitHub's 3 MB file-size limit and was ignored.",
+ );
+ } else {
+ for (const { path } of finding.locations) {
+ if (!hasFile(path)) continue;
+ const rule = codeownersForPath(codeowners.rules, path);
+ if (rule === undefined) continue;
+ const owner = rule.owners[0];
+ if (owner === undefined) continue;
+ context.codeowner = owner;
+ context.limitations.push(
+ "CODEOWNERS identities are declarations; their existence and repository access are not verified.",
+ );
+ add({
+ kind: "codeowners",
+ path: codeowners.path,
+ commit: revision,
+ startLine: rule.line,
+ endLine: rule.line,
+ rule: rule.rule,
+ matchedPath: path,
+ content: rule.rule,
+ identityIndex: null,
+ });
+ return context;
+ }
+ }
+ }
for (const path of new Set(finding.locations.map(({ path }) => path))) {
if (!hasFile(path)) {
context.limitations.push(`Not a regular file at HEAD: ${path}`);
diff --git a/sdk/typescript/src/suggest-owners.ts b/sdk/typescript/src/suggest-owners.ts
index ba2ededb6..a5015f90d 100644
--- a/sdk/typescript/src/suggest-owners.ts
+++ b/sdk/typescript/src/suggest-owners.ts
@@ -17,6 +17,7 @@ import {
type ReadOnlyCodexOptions,
} from "./scan-comparison.js";
import { CODEX_SECURITY_THREAD_SOURCES } from "./thread-source.js";
+import type { CodeownerIdentity } from "./codeowners.js";
const text = z.string().refine((value) => value.trim().length > 0);
const locationSchema = z
@@ -46,19 +47,20 @@ export type SuggestOwnersOptions = Omit<
"auth" | "workingDirectory"
>;
export type { OwnerIdentity } from "./owner-evidence.js";
+export type { CodeownerIdentity } from "./codeowners.js";
export interface OwnerSuggestion {
findingId: string;
occurrenceId: string | null;
status: "identified" | "abstained" | "error";
- owner: OwnerIdentity | null;
+ owner: OwnerIdentity | CodeownerIdentity | null;
reason: string;
evidence: Omit<OwnerEvidence, "identityIndex" | "content">[];
limitations: string[];
}
export interface OwnerSuggestions extends ScanModelConfiguration {
- schemaVersion: 1;
+ schemaVersion: 2;
revision: string;
results: OwnerSuggestion[];
}
@@ -98,7 +100,7 @@ export async function suggestOwnersInternal(
const model = options.model ?? configured.model;
const reasoningEffort = options.reasoningEffort ?? configured.reasoningEffort;
const report: OwnerSuggestions = {
- schemaVersion: 1,
+ schemaVersion: 2,
revision: git.revision,
model,
reasoningEffort,
@@ -119,6 +121,16 @@ export async function suggestOwnersInternal(
try {
const context = await collectOwnerEvidence(finding, git);
result.limitations = context.limitations;
+ if (context.codeowner !== null) {
+ result.owner = context.codeowner;
+ result.status = "identified";
+ result.reason = "Declared owner of an affected file in CODEOWNERS.";
+ result.evidence = context.evidence.map(
+ ({ content: _content, identityIndex: _index, ...citation }) =>
+ citation,
+ );
+ continue;
+ }
if (
context.identities.length === 0 ||
!context.evidence.some(({ kind }) => kind === "source")
diff --git a/sdk/typescript/tests-ts/cli-suggest-owners.test.ts b/sdk/typescript/tests-ts/cli-suggest-owners.test.ts
index cbdb2e254..5d2f7e86b 100644
--- a/sdk/typescript/tests-ts/cli-suggest-owners.test.ts
+++ b/sdk/typescript/tests-ts/cli-suggest-owners.test.ts
@@ -35,7 +35,7 @@ async function input() {
}
const report: OwnerSuggestions = {
- schemaVersion: 1,
+ schemaVersion: 2,
revision: "a".repeat(40),
model: "synthetic-model",
reasoningEffort: "high",
@@ -169,3 +169,43 @@ test("reports owner lookup errors without changing the diagnostic or leaving lis
expect(signals.listeners.get("SIGINT")?.size).toBe(0);
expect(signals.listeners.get("SIGTERM")?.size).toBe(0);
});
+
+test("emits a primary CODEOWNERS identity using the existing command and report fields", async () => {
+ const { directory, document } = await input();
+ const deps = dependencies({ currentDirectory: directory });
+ const declared: OwnerSuggestions = {
+ ...report,
+ results: [
+ {
+ findingId: document.findings[0]!.findingId,
+ occurrenceId: null,
+ status: "identified",
+ owner: {
+ kind: "group",
+ provider: "github",
+ handle: "example/maintainers",
+ },
+ reason: "Declared owner of an affected file in CODEOWNERS.",
+ evidence: [
+ {
+ id: "e1",
+ kind: "codeowners",
+ path: ".github/CODEOWNERS",
+ commit: report.revision,
+ startLine: 1,
+ endLine: 1,
+ rule: "* @example/maintainers",
+ matchedPath: "handler.ts",
+ },
+ ],
+ limitations: [],
+ },
+ ],
+ };
+ deps.suggestOwners = async () => declared;
+ const { stdout, runCli } = createCliTest(main);
+ expect(
+ await runCli(["suggest-owners", "findings.json", "--json"], deps),
+ ).toBe(0);
+ expect(JSON.parse(stdout.text())).toEqual(declared);
+});
diff --git a/sdk/typescript/tests-ts/codeowners.test.ts b/sdk/typescript/tests-ts/codeowners.test.ts
new file mode 100644
index 000000000..5fd12d86e
--- /dev/null
+++ b/sdk/typescript/tests-ts/codeowners.test.ts
@@ -0,0 +1,123 @@
+import { expect, test } from "bun:test";
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import { codeownersForPath, parseCodeowners } from "../src/codeowners.js";
+
+test.each([
+ ["*.ts", "src/a.ts", true],
+ ["/handler.ts", "src/handler.ts", false],
+ ["/handler.ts", "handler.ts", true],
+ ["apps/", "nested/apps/handler.ts", true],
+ ["/apps/", "nested/apps/handler.ts", false],
+ ["docs/*", "docs/start.md", true],
+ ["docs/*", "docs/nested/start.md", false],
+ ["/service*", "services/api.ts", true],
+ ["/service*", "nested/services/api.ts", false],
+ ["service*", "nested/services/api.ts", true],
+ ["docs/service*", "docs/services/api.ts", true],
+ ["/api?", "api1/main.ts", true],
+ ["/api?", "api12/main.ts", false],
+ ["**/logs", "deep/logs/file.txt", true],
+ ["src/**/test?.ts", "src/test1.ts", true],
+ ["src/**/test?.ts", "src/deep/test1.ts", true],
+ ["src/**/test?.ts", "src/deep/test12.ts", false],
+ ["src/**", "src/deep/file.ts", true],
+ ["/a\\ b.ts", "a b.ts", true],
+ ["/app/\\[id\\]/page.ts", "app/[id]/page.ts", true],
+ ["/app/\\[id\\]/page.ts", "app/i/page.ts", false],
+ ["/\\*\\*\\*/main.rb", "***/main.rb", true],
+ ["*.ts", "src/A.TS", false],
+ ["**/logs", "logs/file.txt", true],
+ ["**/logs", "catalogs/file.txt", false],
+ ["a/**/b/**/file?.ts", "a/b/file1.ts", true],
+ ["a/**/b/**/file?.ts", "a/x/b/y/z/file1.ts", true],
+ ["a/**/b/**/file?.ts", "a/x/b/y/z/file12.ts", false],
+ ["/a*b?c", "axbyc/child.ts", true],
+ ["/a*b?c", "a/xbyc/child.ts", false],
+ ["/literal\\?.ts", "literal?.ts", true],
+ ["/literal\\?.ts", "literal1.ts", false],
+ ["/src/?.ts", "src/💡.ts", true],
+ ["/src/💡*.ts", "src/💡-test.ts", true],
+ ["docs/*/", "docs/chapter/start.md", true],
+] as const)("matches %s against %s: %p", (pattern, path, matches) => {
+ expect(
+ codeownersForPath(parseCodeowners(`${pattern} @alex`), path) !== undefined,
+ ).toBe(matches);
+});
+
+test("matches overlapping wildcards without backtracking", async () => {
+ const module = new URL("../src/codeowners.ts", import.meta.url).href;
+ // Run in a child so a regression cannot hang the test runner's event loop.
+ // The deadline is a watchdog, not a microbenchmark assertion.
+ const { stdout } = await promisify(execFile)(
+ "node",
+ [
+ "--experimental-strip-types",
+ "--input-type=module",
+ "--eval",
+ `
+ import { parseCodeowners, codeownersForPath } from ${JSON.stringify(module)};
+ const cases = [
+ ["/" + "*a".repeat(24) + "b", "a".repeat(80)],
+ ["/" + "**/".repeat(24) + "b", "a/".repeat(80)],
+ ];
+ console.log(JSON.stringify(cases.map(([pattern, path]) => {
+ const rules = parseCodeowners(pattern + " @owner");
+ return ["b", "c"].map(end => codeownersForPath(rules, path + end) !== undefined);
+ })));
+ `,
+ ],
+ { timeout: 10_000 },
+ );
+ expect(JSON.parse(stdout)).toEqual([
+ [true, false],
+ [true, false],
+ ]);
+});
+
+test("uses the last matching rule and preserves all owners and ownerless overrides", () => {
+ const rules = parseCodeowners(
+ "* @default\n/apps/ @example/app-team @alex [email protected] # review team\n/apps/generated/\n",
+ );
+ expect(codeownersForPath(rules, "apps/handler.ts")).toMatchObject({
+ line: 2,
+ owners: [
+ { kind: "group", provider: "github", handle: "example/app-team" },
+ { kind: "person", provider: "github", handle: "alex" },
+ { kind: "person", email: "[email protected]" },
+ ],
+ });
+ expect(codeownersForPath(rules, "apps/generated/api.ts")?.owners).toEqual([]);
+});
+
+test.each(["@alex_corp", "@example/app-team @alex_corp"])(
+ "preserves a rule containing the managed user: %s",
+ (owners) => {
+ const rules = parseCodeowners(`* @default\n/apps/ ${owners}\n`);
+ expect(codeownersForPath(rules, "apps/handler.ts")).toMatchObject({
+ line: 2,
+ owners: expect.arrayContaining([
+ { kind: "person", provider: "github", handle: "alex_corp" },
+ ]),
+ });
+ },
+);
+
+test.each(["***/*.rb", "src/***/main.rb", "/app/[id]/page.ts"])(
+ "skips invalid pattern %s without replacing the default owner",
+ (pattern) => {
+ expect(parseCodeowners(`* @default\n${pattern} @other\n`)).toMatchObject([
+ { pattern: "*", owners: [{ handle: "default" }] },
+ ]);
+ },
+);
+
+test("skips unsupported and invalid rules without shadowing a valid owner", () => {
+ const rules = parseCodeowners(
+ "* @alex\n!*.ts @blair\n[ab].ts @blair\n\\#file @blair\n*.ts invalid-owner\n# comment\n",
+ );
+ expect(rules).toHaveLength(1);
+ expect(codeownersForPath(rules, "a.ts")?.owners).toEqual([
+ { kind: "person", provider: "github", handle: "alex" },
+ ]);
+});
diff --git a/sdk/typescript/tests-ts/suggest-owners.test.ts b/sdk/typescript/tests-ts/suggest-owners.test.ts
index 20887f900..30b13e94a 100644
--- a/sdk/typescript/tests-ts/suggest-owners.test.ts
+++ b/sdk/typescript/tests-ts/suggest-owners.test.ts
@@ -1,7 +1,7 @@
import { modelResponseText } from "./support/model-response-text.js";
import { execFile as execFileCallback } from "node:child_process";
import { cp, mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
-import { delimiter, join, relative } from "node:path";
+import { delimiter, dirname, join, relative } from "node:path";
import { promisify } from "node:util";
import type { ThreadOptions, TurnOptions } from "@openai/codex-sdk";
import { afterEach, expect, test } from "bun:test";
@@ -134,6 +134,7 @@ test.each(["ISO-8859-1", "UTF-16LE"])(
};
});
const report = await suggestOwners(repo.path, [finding], { codex });
+ expect(report.schemaVersion).toBe(2);
expect(report.results[0]).toMatchObject({
status: "identified",
owner: { name, email },
@@ -618,6 +619,342 @@ test("propagates cancellation", async () => {
).rejects.toThrow("Canceled by caller");
});
+test("prioritizes the first committed declared owner without a model call", async () => {
+ const repo = await repository();
+ await mkdir(join(repo.path, ".github"));
+ await mkdir(join(repo.path, "docs"));
+ await writeFile(
+ join(repo.path, ".github", "CODEOWNERS"),
+ "* @default\n/handler.ts @example/maintainers @reviewer [email protected]\n",
+ );
+ await writeFile(join(repo.path, "CODEOWNERS"), "* @wrong-root\n");
+ await writeFile(join(repo.path, "docs", "CODEOWNERS"), "* @wrong-docs\n");
+ await repo.git("add", ".");
+ await repo.git("commit", "-qm", "Declare owners");
+ const revision = await repo.git("rev-parse", "HEAD");
+ await writeFile(join(repo.path, ".github", "CODEOWNERS"), "* @uncommitted\n");
+ const { codex, calls } = fakeCodex(() => {
+ throw new Error("A declared owner does not require a model.");
+ });
+ const report = await suggestOwners(repo.path, [finding], { codex });
+ expect(calls).toHaveLength(0);
+ expect(report.revision).toBe(revision);
+ expect(report.schemaVersion).toBe(2);
+ expect(report.results[0]).toMatchObject({
+ findingId: finding.findingId,
+ status: "identified",
+ owner: {
+ kind: "group",
+ provider: "github",
+ handle: "example/maintainers",
+ },
+ evidence: [
+ {
+ kind: "codeowners",
+ path: ".github/CODEOWNERS",
+ commit: revision,
+ startLine: 2,
+ endLine: 2,
+ rule: "/handler.ts @example/maintainers @reviewer [email protected]",
+ matchedPath: "handler.ts",
+ },
+ ],
+ });
+ expect(report.results[0]!.evidence).toHaveLength(1);
+});
+
+test.each([
+ ["src/main.ts", "/src/ @alex_corp", "alex_corp", 2],
+ [
+ "src/main.ts",
+ "/src/ @example/maintainers @alex_corp",
+ "example/maintainers",
+ 2,
+ ],
+ ["lib/main.rb", "***/*.rb @ruby-team", "default", 1],
+ ["app/[id]/page.ts", "/app/\\[id\\]/page.ts @routes-team", "routes-team", 2],
+ ["services/api.ts", "/service* @service-team", "service-team", 2],
+ ["api1/main.ts", "/api? @api-team", "api-team", 2],
+ ["docs/start.md", "docs/* @docs-team", "docs-team", 2],
+ ["docs/nested/start.md", "docs/* @docs-team", "default", 1],
+ ["src/handler.ts", "/src/**/handler.ts @src-team", "src-team", 2],
+ ["src/deep/handler.ts", "/src/**/handler.ts @src-team", "src-team", 2],
+] as const)(
+ "selects the committed owner for %s using %s",
+ async (path, rule, handle, line) => {
+ const repo = await repository();
+ await mkdir(join(repo.path, dirname(path)), { recursive: true });
+ await writeFile(join(repo.path, path), "// Ownership fixture\n");
+ await writeFile(join(repo.path, "CODEOWNERS"), `* @default\n${rule}\n`);
+ await repo.git("add", ".");
+ await repo.git("commit", "-qm", "Declare owners");
+ const { codex, calls } = fakeCodex();
+ const report = await suggestOwners(
+ repo.path,
+ [{ ...finding, locations: [{ path }] }],
+ { codex },
+ );
+ expect(report.results[0]).toMatchObject({
+ status: "identified",
+ owner: { handle },
+ evidence: [
+ {
+ kind: "codeowners",
+ startLine: line,
+ matchedPath: path,
+ commit: report.revision,
+ rule: line === 1 ? "* @default" : rule,
+ },
+ ],
+ });
+ expect(calls).toHaveLength(0);
+ },
+);
+
+test("loads CODEOWNERS once per invocation while matching each finding separately", async () => {
+ const repo = await repository();
+ await writeFile(join(repo.path, "other.ts"), "// Another owned file\n");
+ await writeFile(
+ join(repo.path, "CODEOWNERS"),
+ "/handler.ts @handler-owner\n/other.ts @other-owner\n",
+ );
+ await repo.git("add", ".");
+ await repo.git("commit", "-qm", "Declare owners");
+ const trace = join(await temporaryDirectory("owner-trace-"), "git.jsonl");
+ const { codex, calls } = fakeCodex();
+ const options = {
+ codex,
+ environment: { ...process.env, GIT_TRACE2_EVENT: trace },
+ };
+ const findings = [
+ finding,
+ {
+ ...finding,
+ findingId: "finding-two",
+ locations: [{ path: "other.ts" }],
+ },
+ ];
+ const first = await suggestOwners(repo.path, findings, options);
+ expect(first.results).toMatchObject([
+ {
+ owner: { handle: "handler-owner" },
+ evidence: [{ matchedPath: "handler.ts", startLine: 1 }],
+ },
+ {
+ owner: { handle: "other-owner" },
+ evidence: [{ matchedPath: "other.ts", startLine: 2 }],
+ },
+ ]);
+ await writeFile(join(repo.path, "CODEOWNERS"), "* @new-owner\n");
+ await repo.git("commit", "-qam", "Update owners");
+ const second = await suggestOwners(repo.path, findings, options);
+ expect(second.revision).not.toBe(first.revision);
+ expect(second.results.map(({ owner }) => owner)).toEqual([
+ { kind: "person", provider: "github", handle: "new-owner" },
+ { kind: "person", provider: "github", handle: "new-owner" },
+ ]);
+ const reads = (await readFile(trace, "utf8"))
+ .trim()
+ .split("\n")
+ .map((line) => JSON.parse(line) as { event: string; argv?: string[] })
+ .filter(
+ ({ event, argv }) => event === "start" && argv?.includes("cat-file"),
+ );
+ expect(reads.map(({ argv }) => argv!.at(-1))).toEqual([
+ `${first.revision}:CODEOWNERS`,
+ `${second.revision}:CODEOWNERS`,
+ ]);
+ expect(calls).toHaveLength(0);
+});
+
+test("reports a lazy CODEOWNERS load failure for each finding", async () => {
+ const repo = await repository();
+ await writeFile(join(repo.path, "CODEOWNERS"), "* @owner\n");
+ await repo.git("add", ".");
+ await repo.git("commit", "-qm", "Declare owner");
+ const blob = await repo.git("rev-parse", "HEAD:CODEOWNERS");
+ await rm(join(repo.path, ".git", "objects", blob.slice(0, 2), blob.slice(2)));
+ const { codex, calls } = fakeCodex();
+ expect((await suggestOwners(repo.path, [], { codex })).results).toEqual([]);
+ const report = await suggestOwners(
+ repo.path,
+ [finding, { ...finding, findingId: "finding-two" }],
+ { codex },
+ );
+ expect(
+ report.results.map(({ findingId, status }) => ({ findingId, status })),
+ ).toEqual([
+ { findingId: finding.findingId, status: "error" },
+ { findingId: "finding-two", status: "error" },
+ ]);
+ expect(report.results[0]!.reason).toContain("cat-file");
+ expect(calls).toHaveLength(0);
+});
+
+test.each([
+ ["@reviewer", { kind: "person", provider: "github", handle: "reviewer" }],
+ ["[email protected]", { kind: "person", email: "[email protected]" }],
+] as const)("returns the declared person %s", async (declaration, owner) => {
+ const repo = await repository();
+ await writeFile(join(repo.path, "CODEOWNERS"), `* ${declaration}\n`);
+ await repo.git("add", ".");
+ await repo.git("commit", "-qm", "Declare owner");
+ const { codex, calls } = fakeCodex();
+ const report = await suggestOwners(repo.path, [finding], { codex });
+ expect(report.results[0]!.owner).toEqual(owner);
+ expect(report.results[0]!.status).toBe("identified");
+ expect(calls).toHaveLength(0);
+});
+
+test.each(["CODEOWNERS", "docs/CODEOWNERS"])(
+ "uses %s when no higher-priority ownership file exists",
+ async (path) => {
+ const repo = await repository();
+ await mkdir(join(repo.path, "docs"));
+ await writeFile(join(repo.path, path), "* @example/maintainers\n");
+ await repo.git("add", ".");
+ await repo.git("commit", "-qm", "Declare owner");
+ const report = await suggestOwners(repo.path, [finding]);
+ expect(report.results[0]!.evidence[0]!.path).toBe(path);
+ expect(report.results[0]!.owner).toEqual({
+ kind: "group",
+ provider: "github",
+ handle: "example/maintainers",
+ });
+ },
+);
+
+test.each([
+ "/elsewhere/ @example/maintainers\n",
+ "* @default\n/handler.ts\n",
+ "/handler.ts invalid-owner\n",
+])(
+ "falls back to Git when CODEOWNERS has no applicable owner: %s",
+ async (source) => {
+ const repo = await repository();
+ await mkdir(join(repo.path, ".github"));
+ await writeFile(join(repo.path, ".github", "CODEOWNERS"), source);
+ await writeFile(join(repo.path, "CODEOWNERS"), "* @wrong-root\n");
+ await repo.git("add", ".");
+ await repo.git("commit", "-qm", "Declare owners");
+ const { codex, calls } = fakeCodex();
+ const report = await suggestOwners(repo.path, [finding], { codex });
+ expect(calls).toHaveLength(1);
+ expect(report.results[0]!.status).toBe("identified");
+ expect(report.results[0]!.owner).toEqual({
+ name: "Alex Example",
+ email: "[email protected]",
+ });
+ expect(
+ report.results[0]!.evidence.every(({ kind }) => kind !== "codeowners"),
+ ).toBe(true);
+ },
+);
+
+test("selects the first affected path with a declared owner", async () => {
+ const repo = await repository();
+ await writeFile(join(repo.path, "other.ts"), "export const other = 1;\n");
+ await writeFile(
+ join(repo.path, "CODEOWNERS"),
+ "/handler.ts @handler-owner\n/other.ts @other-owner\n",
+ );
+ await repo.git("add", ".");
+ await repo.git("commit", "-qm", "Declare owners");
+ const report = await suggestOwners(repo.path, [
+ {
+ ...finding,
+ locations: [
+ { path: "missing.ts" },
+ { path: "other.ts" },
+ ...finding.locations,
+ ],
+ },
+ ]);
+ expect(report.results[0]!.owner).toEqual({
+ kind: "person",
+ provider: "github",
+ handle: "other-owner",
+ });
+ expect(report.results[0]!.evidence[0]!.matchedPath).toBe("other.ts");
+});
+
+test("ignores a CODEOWNERS symlink and uses the next regular ownership file", async () => {
+ const repo = await repository();
+ await mkdir(join(repo.path, ".github"));
+ await writeFile(join(repo.path, ".github", "CODEOWNERS"), "../CODEOWNERS\n");
+ await writeFile(join(repo.path, "CODEOWNERS"), "* @reviewer\n");
+ const blob = await repo.git("hash-object", "-w", ".github/CODEOWNERS");
+ await repo.git("add", ".");
+ await repo.git(
+ "update-index",
+ "--cacheinfo",
+ `120000,${blob},.github/CODEOWNERS`,
+ );
+ await repo.git("commit", "-qm", "Declare owner through regular file");
+ const report = await suggestOwners(repo.path, [finding]);
+ expect(report.results[0]!.evidence[0]!.path).toBe("CODEOWNERS");
+ expect(report.results[0]!.owner).toEqual({
+ kind: "person",
+ provider: "github",
+ handle: "reviewer",
+ });
+});
+
+test("ignores CODEOWNERS at GitHub's file-size limit and falls back to Git", async () => {
+ const repo = await repository();
+ const source = "* @reviewer\n#";
+ await writeFile(join(repo.path, "CODEOWNERS"), source.padEnd(3_000_000, "x"));
+ await repo.git("add", ".");
+ await repo.git("commit", "-qm", "Declare owner in oversized file");
+ const { codex, calls } = fakeCodex();
+ const report = await suggestOwners(repo.path, [finding], { codex });
+ expect(calls).toHaveLength(1);
+ expect(report.results[0]!.owner).toEqual({
+ name: "Alex Example",
+ email: "[email protected]",
+ });
+ expect(report.results[0]!.limitations.join(" ")).toContain("3 MB");
+});
+
+test("matches CODEOWNERS for Unicode repository-relative paths from a subdirectory", async () => {
+ const repo = await repository();
+ const subdir = join(repo.path, "src");
+ await mkdir(subdir);
+ await writeFile(join(repo.path, "café.ts"), "export const root = 1;\n");
+ await writeFile(join(subdir, "café.ts"), "export const nested = 2;\n");
+ await writeFile(
+ join(repo.path, "CODEOWNERS"),
+ "/café.ts @root-owner\n/src/café.ts @example/nested-team\n",
+ );
+ await repo.git("add", ".");
+ await repo.git("commit", "-qm", "Declare owners for Unicode paths");
+ const { codex, calls } = fakeCodex();
+ const report = await suggestOwners(
+ subdir,
+ [
+ {
+ ...finding,
+ findingId: "root-finding",
+ locations: [{ path: "café.ts" }],
+ },
+ {
+ ...finding,
+ findingId: "nested-finding",
+ locations: [{ path: "src/café.ts" }],
+ },
+ ],
+ { codex },
+ );
+ expect(report.results.map((result) => result.owner)).toEqual([
+ { kind: "person", provider: "github", handle: "root-owner" },
+ { kind: "group", provider: "github", handle: "example/nested-team" },
+ ]);
+ expect(
+ report.results.map((result) => result.evidence[0]!.matchedPath),
+ ).toEqual(["café.ts", "src/café.ts"]);
+ expect(calls).toHaveLength(0);
+});
+
test("subdirectory roots retain repository-relative paths when filenames collide", async () => {
const repo = await repository();
const subdir = join(repo.path, "src");
@@ -664,9 +1001,9 @@ test("subdirectory roots retain repository-relative paths when filenames collide
],
{ codex },
);
- expect(report.results.map((result) => result.owner?.email)).toEqual([
+ expect(report.results.map((result) => result.owner)).toEqual([
+ { name: "Alex Example", email: "[email protected]" },
+ { name: "Casey Example", email: "[email protected]" },
]);
expect(calls).toHaveLength(2);
});