OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
fix(findings): preserve scan history and publication outcomes (#1270)
mldangelo-oai49128248f7bf
diff --git a/plugins/codex-security/mcp-app/src/workbench/dashboard.ts b/plugins/codex-security/mcp-app/src/workbench/dashboard.tsindex bfb5b089c..1513248c4 100644--- a/plugins/codex-security/mcp-app/src/workbench/dashboard.ts+++ b/plugins/codex-security/mcp-app/src/workbench/dashboard.ts@@ -6,7 +6,7 @@ import { transaction } from "./transaction";const records = {findings: `- SELECT findings.id, json_extract(details_json, '$.title') AS title,+ SELECT findings.id, json_extract(dashboard_title(details_json), '$') AS title,COALESCE(repositories.ids, '[]') AS repositoryIds,json_extract(details_json, '$.severity.level') AS severity,findings.created_at AS createdAt, findings.updated_at AS updatedAt@@ -103,6 +103,11 @@ function detail(export function dashboard(database: DatabaseSync, query: DashboardQuery) {requireSqliteText([query.query, query.repository, query.id]);// JSON preserves text across Node 22 SQLite result and callback boundaries.+ database.function("dashboard_title", { deterministic: true }, (value) =>+ JSON.stringify(+ (JSON.parse(value as string).title as string).toWellFormed(),+ ),+ );database.function("dashboard_lower", { deterministic: true }, (value) =>(JSON.parse(value as string) as string).toLowerCase(),);diff --git a/plugins/codex-security/mcp-app/tests/test_workbench_dashboard.ts b/plugins/codex-security/mcp-app/tests/test_workbench_dashboard.tsindex c10b26d4f..4dc6eb23b 100644--- a/plugins/codex-security/mcp-app/tests/test_workbench_dashboard.ts+++ b/plugins/codex-security/mcp-app/tests/test_workbench_dashboard.ts@@ -228,3 +228,40 @@ test("dashboard reads its counts and rows from one WAL snapshot", async (t) => {]);assert.equal(dashboard(db, query).total, 2);});++test("dashboard preserves the existing lone-surrogate display behavior", (t) => {+ const db = database(t);+ const titles = [+ "high\ud800title",+ "low\udc00title",+ "paired\ud83d\udca0title",+ ];+ for (const [index, title] of titles.entries()) {+ const id = `surrogate-${index}`;+ const stored = insert(db, id, "synthetic-repository", title);+ const result = dashboard(db, {+ view: "findings",+ sort: "title",+ limit: 50,+ offset: 0,+ id,+ });+ assert.equal(result.detail?.item.title, title.toWellFormed());+ assert.deepEqual(+ result.detail?.finding,+ stored,+ "display does not change the canonical finding",+ );+ const matches = dashboard(db, {+ view: "findings",+ sort: "title",+ limit: 50,+ offset: 0,+ query: title.toWellFormed(),+ });+ assert.deepEqual(+ matches.items.map((item) => item.id),+ [id],+ );+ }+});diff --git a/plugins/codex-security/scripts/workbench_native_indexes.py b/plugins/codex-security/scripts/workbench_native_indexes.pyindex 71291b280..ce4be2e88 100644--- a/plugins/codex-security/scripts/workbench_native_indexes.py+++ b/plugins/codex-security/scripts/workbench_native_indexes.py@@ -160,8 +160,10 @@ def _indexed_findings(connection: sqlite3.Connection) -> Iterator[dict[str, Any]findings.append({**dict(latest),- "confirmed_in_latest_scan": latest_scan_by_target.get(latest["target_id"])- == latest["scan_id"],+ "confirmed_in_latest_scan": any(+ row["scan_id"] == latest_scan_by_target.get(row["target_id"])+ for row in occurrences+ ),"known_since": scans[0][0],"known_scan_ids": [scan_id for _, scan_id in scans],"matched_finding_ids": sorted({row["finding_id"] for row in occurrences}),diff --git a/plugins/codex-security/scripts/workbench_scan_history.py b/plugins/codex-security/scripts/workbench_scan_history.pyindex eaef30135..bceebb044 100644--- a/plugins/codex-security/scripts/workbench_scan_history.py+++ b/plugins/codex-security/scripts/workbench_scan_history.py@@ -204,6 +204,7 @@ def _repository_origin(target: Path) -> tuple[str, str] | None:def list_scans(connection: sqlite3.Connection, args: argparse.Namespace | None = None) -> dict[str, Any]:+ connection.create_function("casefold", 1, str.casefold, deterministic=True)if os.name == "nt":connection.create_function("codex_security_path_key", 1, _windows_path_key)clauses: list[str] = []@@ -263,13 +264,12 @@ def list_scans(if args is not None and args.query:query = args.query.strip().casefold()if query:- connection.create_function("codex_security_casefold", 1, str.casefold)clauses.append(- "(instr(lower(scans.target_path), ?) > 0 "- "OR instr(codex_security_casefold(COALESCE(scans.name, '')), ?) > 0 "- "OR instr(lower(COALESCE(scans.target_summary, '')), ?) > 0 "- "OR instr(lower(scans.scope), ?) > 0 "- "OR instr(lower(scans.mode), ?) > 0)"+ "(instr(casefold(scans.target_path), ?) > 0 "+ "OR instr(casefold(COALESCE(scans.name, '')), ?) > 0 "+ "OR instr(casefold(COALESCE(scans.target_summary, '')), ?) > 0 "+ "OR instr(casefold(scans.scope), ?) > 0 "+ "OR instr(casefold(scans.mode), ?) > 0)")values.extend((query, query, query, query, query))where = f"WHERE {' AND '.join(clauses)}" if clauses else ""@@ -1093,6 +1093,7 @@ def finding_occurrence_rows(severity: str | None = None,status: str | None = None,) -> list[sqlite3.Row]:+ connection.create_function("casefold", 1, str.casefold, deterministic=True)conditions, values = finding_occurrence_conditions(scan_id, query=query, severity=severity, status=status)@@ -1147,12 +1148,12 @@ def finding_occurrence_conditions(search = query.strip().casefold()if search:conditions.append(- "(instr(lower(occurrences.title), ?) > 0 "- "OR instr(lower(occurrences.summary), ?) > 0 "+ "(instr(casefold(occurrences.title), ?) > 0 "+ "OR instr(casefold(occurrences.summary), ?) > 0 ""OR EXISTS (""SELECT 1 FROM finding_locations AS locations ""WHERE locations.occurrence_id = occurrences.id "- "AND instr(lower(locations.relative_path), ?) > 0))"+ "AND instr(casefold(locations.relative_path), ?) > 0))")values.extend((search, search, search))return " AND ".join(conditions), valuesdiff --git a/plugins/codex-security/tests/test_workbench_native_indexes.py b/plugins/codex-security/tests/test_workbench_native_indexes.pyindex 617d864e9..fb219b5ce 100644--- a/plugins/codex-security/tests/test_workbench_native_indexes.py+++ b/plugins/codex-security/tests/test_workbench_native_indexes.py@@ -271,3 +271,53 @@ def test_repository_index_reports_latest_scan_open_findings_and_missing_checkoutassert second["latestScan"]["scanId"] == latest_second["scanId"]assert second["openFindingsCount"] == 1assert second["scanCount"] == 1+++def test_overlapping_scans_mark_findings_present_in_latest_started_scan(tmp_path: Path) -> None:+ state_dir = tmp_path / "state"+ target = tmp_path / "repo"+ target.mkdir()+ first = complete_scan(state_dir, target, identity_anchor="recurring-finding")+ second = complete_scan(state_dir, target, identity_anchor="recurring-finding")+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:+ connection.execute(+ "UPDATE scans SET started_at = ? WHERE id = ?",+ ("2026-01-01T00:00:00Z", first["scanId"]),+ )+ connection.execute(+ "UPDATE scans SET started_at = ? WHERE id = ?",+ ("2026-01-02T00:00:00Z", second["scanId"]),+ )+ connection.execute(+ "UPDATE finding_occurrences SET created_at = ? WHERE scan_id = ?",+ ("2026-01-04T00:00:00Z", first["scanId"]),+ )+ connection.execute(+ "UPDATE finding_occurrences SET created_at = ? WHERE scan_id = ?",+ ("2026-01-03T00:00:00Z", second["scanId"]),+ )+ finding = run_workbench(state_dir, "list-global-findings")["findings"][0]+ assert finding["confirmedInLatestScan"] is True+ assert set(finding["knownScanIds"]) == {first["scanId"], second["scanId"]}++[email protected]("query", ["strasse", "STRAẞE", "éclair", "ÉCLAIR"])+def test_scan_and_finding_search_casefold_unicode(tmp_path: Path, query: str) -> None:+ state_dir = tmp_path / "state"+ target = tmp_path / "Straße ÉCLAIR"+ target.mkdir()+ first = complete_scan(state_dir, target, identity_anchor="first-finding")+ complete_scan(state_dir, target, identity_anchor="second-finding")+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:+ connection.execute("UPDATE finding_occurrences SET title = ?", ("Straße ÉCLAIR",))+ page = run_workbench(state_dir, "list-scans", "--query", query, "--limit", "1")+ assert len(page["scans"]) == 1+ assert page["nextOffset"] == 1+ next_page = run_workbench(+ state_dir, "list-scans", "--query", query, "--limit", "1", "--offset", "1"+ )+ assert len(next_page["scans"]) == 1+ findings = run_workbench(+ state_dir, "list-findings", "--scan-id", str(first["scanId"]), "--query", query+ )+ assert len(findings["findingsPage"]["findings"]) == 1diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex 846f30194..603e74124 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -894,7 +894,9 @@ or effort. A successful run also writes `severity-classification.json`, butpublication reads the database. Original findings and sealed artifacts remainunchanged.-Repeat `--finding-id ID` for a subset, such as dedupe's `uniqueFindingIds`.+Repeat `--finding-id ID` for a subset from the selected scan. Dedupe's+`uniqueFindingIds` can represent findings from another scan; replace an outside-scan+representative with a member of its `duplicateGroups` entry from this scan.Linear publication defaults to saved classification selection, omits exclusions,and uses assessed severity for title and priority. Descriptions retain originalseverity and add the classification rationale. Publication rejects incomplete or@@ -916,7 +918,10 @@ import {classifyScanSeverity,classifyScanDirectorySeverity,publishScan,+ type FindingsDocument,} from "@openai/codex-security";+import { readFile } from "node:fs/promises";+import { join } from "node:path";// Assess supplied reports in memory.const classification = await classifySeverity(findings, {@@ -926,9 +931,24 @@ const classification = await classifySeverity(findings, {// Save assessments for a scan ID or sealed directory.await classifyScanSeverity("SCAN_ID", { rubricPath: "/path/to/policy.md" });+const scanFindings = (+ JSON.parse(+ await readFile(join(scanDirectory, "findings.json"), "utf8"),+ ) as FindingsDocument+).findings;+const scanFindingIds = new Set(+ scanFindings.map((finding) => finding.findingId),+);+// dedupeResult was produced by deduplicating this same scan.+const selectedIds = dedupeResult.uniqueFindingIds.map((representative) => {+ if (scanFindingIds.has(representative)) return representative;+ return dedupeResult.duplicateGroups+ .find((group) => group.includes(representative))!+ .find((member) => scanFindingIds.has(member))!;+});await classifyScanDirectorySeverity(scanDirectory, {rubricPath: "/path/to/policy.md",- findingIds: dedupeResult.uniqueFindingIds,+ findingIds: selectedIds,});// Or supply an in-memory assessment directly to publication.@@ -958,6 +978,12 @@ codex-security suggest-owners findings.json --source-root /path/to/repo --json >Input is a findings document or `{ "findings": [...] }`. The source rootdefaults to the current directory. The command reads committed `HEAD`, relevantsource, 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+subdirectory-relative locations to repository-relative paths before suggesting+owners.+Linked worktrees and bound separate Git directories are supported; borrowedexternal object stores such as `git clone --shared` are rejected.diff --git a/sdk/typescript/src/bulk-scan-discovery.ts b/sdk/typescript/src/bulk-scan-discovery.tsindex dca5d8825..5901418d1 100644--- a/sdk/typescript/src/bulk-scan-discovery.ts+++ b/sdk/typescript/src/bulk-scan-discovery.ts@@ -17,6 +17,7 @@ const GITHUB_REPOSITORIES_QUERY = `after: $cursorisArchived: falseisFork: false+ ownerAffiliations: [OWNER]orderBy: { field: PUSHED_AT, direction: DESC }) {nodes {diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex c84252d62..43a499bef 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -104,6 +104,7 @@ import {resolveCompletedScan,resolveWorkflowScan,type SavedScan,+ type SavedScanDependencies,} from "./saved-scan.js";import {publishFindingsCsvToCloud,@@ -2797,10 +2798,8 @@ export async function main(dependencies.environment,): undefined;- if (options.to !== "linear") {- signalHandlers(dependencies, "add", onInterrupt, onTerminate);- observingSignals = true;- }+ signalHandlers(dependencies, "add", onInterrupt, onTerminate);+ observingSignals = true;if (csvPath !== undefined) {const result = await (dependencies.publishFindingsCsvToCloud ?? publishFindingsCsvToCloud@@ -2812,18 +2811,26 @@ export async function main(});return { ...result };}+ const scanDependencies: SavedScanDependencies = {+ currentDirectory: dependencies.currentDirectory,+ runWorkbench: (args, input) =>+ dependencies.runWorkbench(args, input, controller.signal),+ };const selectedScans: { scanDir: string; scanId?: string }[] =directories.map((scanDir) => ({ scanDir }));for (const requestedId of new Set(options.scan)) {controller.signal.throwIfAborted();- const scan = await resolveCompletedScan(requestedId, dependencies);+ const scan = await resolveCompletedScan(+ requestedId,+ scanDependencies,+ );if (!selectedScans.some(({ scanId }) => scanId === scan.scanId)) {selectedScans.push(scan);}}if (options.workflowId !== undefined && selectedScans.length === 0) {selectedScans.push(- await resolveWorkflowScan(options.workflowId, dependencies),+ await resolveWorkflowScan(options.workflowId, scanDependencies),);}let scanDir = selectedScans[0]?.scanDir;@@ -2837,7 +2844,7 @@ export async function main(`Interactive scan selection requires a terminal. Select a saved scan: codex-security publish scan --scan SCAN_ID --to ${options.to}${options.to === "linear" ? " --linear-team TEAM_ID" : ""}.`,);}- const saved = await dependencies.runWorkbench([+ const saved = await scanDependencies.runWorkbench(["list-scans","--status","complete",@@ -2918,7 +2925,10 @@ export async function main(.replaceAll(/[\u0000-\u001F\u007F-\u009F]/gu, " ").replace(/\s+/gu, " ").slice(-6)}`;- repositories.set(directory, repository);+ repositories.set(+ resolveCliPath(currentDirectory, directory),+ repository,+ );scansById.set(scanId, {scanId,scanDir: resolveCliPath(currentDirectory, directory),@@ -2929,7 +2939,7 @@ export async function main(findings,age: publicationScanAge(timestamp, now),scanId: shortScanId,- value: options.to === "cloud" ? scanId : directory,+ value: scanId,},];});@@ -2993,12 +3003,16 @@ export async function main();scanDir = selectedScans[0]!.scanDir;} else {- scanDir = await prompt.select(+ controller.signal.throwIfAborted();+ const selectedId = await prompt.select("Which completed scan would you like to publish?",choices,{ header },+ controller.signal,);- selectedScans.push({ scanDir });+ controller.signal.throwIfAborted();+ selectedScans.push(scansById.get(selectedId)!);+ scanDir = selectedScans[0]!.scanDir;}publicationRepository =repositories.get(scanDir) ?? basename(scanDir);@@ -3107,8 +3121,6 @@ export async function main(publicationRepository,);presentation = progress;- signalHandlers(dependencies, "add", onInterrupt, onTerminate);- observingSignals = true;if (!options.dryRun) {progress.start();}@@ -3138,7 +3150,6 @@ export async function main(} finally {progress.stop();}- controller.signal.throwIfAborted();if (result.failed.length > 0) exitCode = 2;if ("warnings" in result && Array.isArray(result.warnings)) {for (const warning of result.warnings) {diff --git a/sdk/typescript/src/cloud-publish.ts b/sdk/typescript/src/cloud-publish.tsindex 5d3d9fe26..e07c02ec3 100644--- a/sdk/typescript/src/cloud-publish.ts+++ b/sdk/typescript/src/cloud-publish.ts@@ -8,6 +8,7 @@ import { AuthenticationRequiredError, CodexSecurityError } from "./errors.js";import type { Finding, ScanManifest } from "./models.js";import {CSV_TARGET_ID,+ bindImportedFindings,csvRowFinding,parseFindingsCsv,} from "./findings-import.js";@@ -93,7 +94,12 @@ export async function publishFindingsCsvToCloud(const scanId = `scan_csv_${sha256(["codex-security-csv-import/v1", VERSION, source].join("\0"),).slice(0, 24)}`;- const findings = rows.map((row) => csvRowFinding(row, scanId));+ const findings = bindImportedFindings(+ rows.map(csvRowFinding),+ "csv",+ scanId,+ CSV_TARGET_ID,+ );const timestamp = "1970-01-01T00:00:00.000Z";const findingsDocument = JSON.stringify({documentType: "codex-security.findings",diff --git a/sdk/typescript/src/findings-import.ts b/sdk/typescript/src/findings-import.tsindex c5b639752..929ea85c3 100644--- a/sdk/typescript/src/findings-import.ts+++ b/sdk/typescript/src/findings-import.ts@@ -109,11 +109,7 @@ export async function parseImportedFindings(pluginRoot: string,): Promise<Finding[]> {if (format === "csv") {- return parseFindingsCsv(source).map((row) => ({- ...csvRowFinding(row, "import"),- findingId: row.finding_id,- occurrenceId: row.occurrence_id,- }));+ return parseFindingsCsv(source).map(csvRowFinding);}let payload: unknown;@@ -276,18 +272,15 @@ function decodeExportedCsvCell(value: string): string {return EXPORTED_CSV_ESCAPE.test(value) ? value.slice(1) : value;}-export function csvRowFinding(row: CsvFindingRow, scanId: string): Finding {+export function csvRowFinding(row: CsvFindingRow): Finding {const ruleId = "import.csv";const anchor = row.occurrence_id;const fingerprint = `codex-security/v1:sha256:${sha256(["codex-security/v1", CSV_TARGET_ID, ruleId, anchor, ""].join("\0"),)}`;return {- findingId: `csf_${sha256(fingerprint).slice(0, 24)}`,- occurrenceId: `occ_${sha256([scanId, fingerprint].join("\0")).slice(- 0,- 24,- )}`,+ findingId: row.finding_id,+ occurrenceId: row.occurrence_id,ruleId,identity: { anchor },fingerprints: {diff --git a/sdk/typescript/src/github.ts b/sdk/typescript/src/github.tsindex da780d734..7c22935d1 100644--- a/sdk/typescript/src/github.ts+++ b/sdk/typescript/src/github.ts@@ -87,7 +87,13 @@ export async function createAuthenticatedGitHub(}return new Octokit({auth: token,- ...(host === "github.com" ? {} : { baseUrl: `https://${host}/api/v3` }),+ ...(host === "github.com"+ ? {}+ : {+ baseUrl: host.toLowerCase().endsWith(".ghe.com")+ ? `https://api.${host}`+ : `https://${host}/api/v3`,+ }),});}diff --git a/sdk/typescript/src/publish.ts b/sdk/typescript/src/publish.tsindex c26948ba8..fdb6cbda4 100644--- a/sdk/typescript/src/publish.ts+++ b/sdk/typescript/src/publish.ts@@ -450,6 +450,13 @@ export async function publishScanInternal(result.indeterminate = true;result.warnings = [`The Linear publication outcome is indeterminate; local history may not include every created issue. ${recoveryMessage}`,+ ...evidence.flatMap((item) =>+ item.source === "handoff" &&+ item.status === "invalid" &&+ item.ownerFindingId === undefined+ ? [item.error]+ : [],+ ),];await preserveConnectorEvents();if (eventLogNotice !== undefined) result.warnings.push(eventLogNotice);@@ -527,7 +534,6 @@ export async function publishScanInternal(`Could not save the publication receipt: ${errorMessage(error)}. Linear issues were already created; do not retry publication.`,];}- options.signal?.throwIfAborted();reportPublicationProgress(progressObserver, {type: "completed",created: result.counts.created,@@ -915,8 +921,17 @@ async function collectPublicationHandoffEvidence(let content: string;try {content = await readFile(file, "utf8");- } catch {- return [];+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];+ return [+ {+ source: "handoff",+ status: "invalid",+ possibleMutation: true,+ resolution: resolveClaims([]),+ error: `Could not read the Linear publication handoff: ${errorMessage(error)}`,+ },+ ];}const expectedIssues = new Map(publication.issues.map(findingEntry));@@ -1346,7 +1361,8 @@ async function preserveVerifiedHandoff(let current: string;try {current = await readFile(file, "utf8");- } catch {+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;current = "";}const planned = new Map(publication.issues.map(findingEntry));diff --git a/sdk/typescript/src/server/routes.ts b/sdk/typescript/src/server/routes.tsindex 040daf673..468517c61 100644--- a/sdk/typescript/src/server/routes.ts+++ b/sdk/typescript/src/server/routes.ts@@ -19,7 +19,15 @@ export async function handleFindingsRequest(validate: ValidateFunction<FindingsRequest>,): Promise<void> {try {- const url = new URL(request.url ?? "/", "http://localhost");+ let url: URL;+ try {+ url = new URL(request.url ?? "/", "http://localhost");+ } catch {+ throw new FindingsError(+ "invalid_request",+ "Request target must be a valid URL.",+ );+ }const route = `${request.method} ${url.pathname}`;if (request.method === "GET" &&diff --git a/sdk/typescript/src/server/validation.ts b/sdk/typescript/src/server/validation.tsindex a41e79c51..bfb26af03 100644--- a/sdk/typescript/src/server/validation.ts+++ b/sdk/typescript/src/server/validation.ts@@ -38,7 +38,7 @@ export async function findingsRequestValidator(): Promise<required: ["findings"],properties: {findings: schema.properties.findings,- repositoryId: { type: "string", minLength: 1 },+ repositoryId: { type: "string", minLength: 1, pattern: "^[^\\u0000]*$" },},});}@@ -47,6 +47,11 @@ export function findingSearchScope(parameters: URLSearchParams,): FindingSearchScope {const repositoryId = parameters.get("repositoryId");+ if (repositoryId?.includes("\0"))+ throw new FindingsError(+ "invalid_request",+ "repositoryId must not contain NUL bytes.",+ );const allRepositories = parameters.get("allRepositories");if (allRepositories === "true" && repositoryId === null)return { allRepositories: true };diff --git a/sdk/typescript/tests-ts/bulk-scan-discovery.test.ts b/sdk/typescript/tests-ts/bulk-scan-discovery.test.tsindex dbfecde64..03bff6ef4 100644--- a/sdk/typescript/tests-ts/bulk-scan-discovery.test.ts+++ b/sdk/typescript/tests-ts/bulk-scan-discovery.test.ts@@ -82,6 +82,7 @@ class FakePrompt implements BulkScanPrompt {interface Repository {fullName: string;+ affiliation?: "OWNER" | "COLLABORATOR";visibility?: "private" | "internal" | "public";archived?: boolean;fork?: boolean;@@ -191,7 +192,13 @@ function discoveryDependencies(}const visible = repositories.filter(- ({ archived, fork }) => !archived && !fork,+ ({ archived, fork, affiliation }) =>+ !archived &&+ !fork &&+ !(+ affiliation === "COLLABORATOR" &&+ /ownerAffiliations:\s*\[OWNER\]/u.test(body.query)+ ),);const start = Number(body.variables?.cursor ?? 0);const page = visible.slice(start, start + 100);@@ -380,16 +387,23 @@ describe("bulk scan repository discovery", () => {const root = await temporaryDirectory();const { dependencies, prompt, requests } = discoveryDependencies(root, {organizations: ["acme"],+ repositories: [+ { fullName: "personal-account/owned", affiliation: "OWNER" },+ { fullName: "another-owner/collaborated", affiliation: "COLLABORATOR" },+ ],});prompt.confirms = [true];prompt.choices = ["personal-account"];- await runBulkScanWizard(dependencies);+ const result = await runBulkScanWizard(dependencies);expect(prompt.searchOptions[0]).toEqual(["acme", "personal-account"]);expect(requests.find(({ path }) => path === "/graphql")?.variables?.owner,).toBe("personal-account");+ const csv = await readFile(result!.inputPath, "utf8");+ expect(csv).toContain("personal-account/owned");+ expect(csv).not.toContain("another-owner/collaborated");});test("includes organizations beyond the first GitHub results page", async () => {diff --git a/sdk/typescript/tests-ts/classify-scan-severity.test.ts b/sdk/typescript/tests-ts/classify-scan-severity.test.tsindex d371ab223..9af4ba3ad 100644--- a/sdk/typescript/tests-ts/classify-scan-severity.test.ts+++ b/sdk/typescript/tests-ts/classify-scan-severity.test.ts@@ -149,7 +149,7 @@ test("checkpoints each finding, resumes missing work, and reprocesses only the s(await query(environment,- "SELECT finding_id FROM finding_severity_assessments",+ "SELECT finding_id FROM scan_severity_assessments",)).map((row) => row["finding_id"]),).toEqual([findings[0]!.findingId]);@@ -173,7 +173,7 @@ test("checkpoints each finding, resumes missing work, and reprocesses only the s).toEqual(assessment);const rows = await query(environment,- "SELECT * FROM finding_severity_assessments ORDER BY finding_id",+ "SELECT * FROM scan_severity_assessments ORDER BY finding_id",);calls.length = 0;expect(@@ -183,7 +183,7 @@ test("checkpoints each finding, resumes missing work, and reprocesses only the sexpect(await query(environment,- "SELECT * FROM finding_severity_assessments ORDER BY finding_id",+ "SELECT * FROM scan_severity_assessments ORDER BY finding_id",),).toEqual(rows);@@ -198,7 +198,7 @@ test("checkpoints each finding, resumes missing work, and reprocesses only the sexpect(revised.assessments[0]!.decision).toBe("excluded");const revisedRows = await query(environment,- "SELECT * FROM finding_severity_assessments ORDER BY finding_id",+ "SELECT * FROM scan_severity_assessments ORDER BY finding_id",);expect(revisedRows).toHaveLength(2);expect(@@ -226,7 +226,7 @@ test("checkpoints each finding, resumes missing work, and reprocesses only the sexpect(await query(environment,- "SELECT * FROM finding_severity_assessments ORDER BY finding_id",+ "SELECT * FROM scan_severity_assessments ORDER BY finding_id",),).toEqual(revisedRows);});@@ -670,3 +670,51 @@ test("migrates existing databases without changing findings and reads older statawait query(environment, "SELECT * FROM findings ORDER BY id"),).toEqual(original);});++test("classifying another scan preserves both recurring-finding assessments", async () => {+ const first = await fixture();+ const second = await fixture();+ const manifestPath = join(second.scanDirectory, "scan-manifest.json");+ const manifest = JSON.parse(+ await readFile(manifestPath, "utf8"),+ ) as ScanManifest;+ manifest.scan.id = "scan_example_002";+ for (const file of ["findings.json", "coverage.json"]) {+ const path = join(second.scanDirectory, file);+ const document = JSON.parse(await readFile(path, "utf8"));+ document.scanId = manifest.scan.id;+ if (file === "findings.json") {+ for (const finding of document.findings as Finding[]) {+ finding.occurrenceId = `occ_${sha256([manifest.scan.id, finding.fingerprints.primary].join("\0")).slice(0, 24)}`;+ }+ }+ await writeFile(path, JSON.stringify(document));+ }+ for (const artifact of manifest.scan.artifacts)+ artifact.sha256 = sha256(+ await readFile(join(second.scanDirectory, artifact.path)),+ );+ await writeFile(manifestPath, JSON.stringify(manifest));+ const { codex, calls } = recordingClassifier();+ const options = {+ environment: first.environment,+ rubricPath: first.rubricPath,+ codex,+ };+ await classifyScanDirectorySeverity(first.scanDirectory, options);+ await classifyScanDirectorySeverity(second.scanDirectory, options);+ expect(calls).toHaveLength(4);+ calls.length = 0;+ for (const scan of [first, second, first, second]) {+ expect(+ (+ await prepareScanPublication(scan.scanDirectory, {+ ...destination,+ environment: first.environment,+ })+ ).issues,+ ).toHaveLength(2);+ await classifyScanDirectorySeverity(scan.scanDirectory, options);+ }+ expect(calls).toEqual([]);+});diff --git a/sdk/typescript/tests-ts/cli-publish.test.ts b/sdk/typescript/tests-ts/cli-publish.test.tsindex 1b1f50421..89e745e18 100644--- a/sdk/typescript/tests-ts/cli-publish.test.ts+++ b/sdk/typescript/tests-ts/cli-publish.test.ts@@ -28,6 +28,83 @@ const { temporaryDirectory: publicationDirectory, cleanup } =afterEach(cleanup);+test.each(["linear", "custom"] as const)(+ "interactive %s selection preserves scan identity and cancellation",+ async (destination) => {+ const [scanDir] = await publicationScanDirectories(1);+ for (const cancel of [false, true]) {+ const signals = new FakeSignals();+ const deps = dependencies({+ signals,+ onWorkbench: () => ({+ scans: [+ {+ scanId: "selected-scan",+ scanDir: scanDir!,+ targetSummary: "repository",+ progress: { status: "complete" },+ },+ ],+ }),+ });+ deps.publishPrompt = {+ isInteractive: () => true,+ select: async (_message, choices, _presentation, signal) => {+ expect(signal).toBeInstanceOf(AbortSignal);+ if (cancel) {+ signals.emit("SIGINT");+ signal!.throwIfAborted();+ }+ return choices[0]!.value;+ },+ };+ let published = false;+ deps.publishScan = async (_directory, options) => {+ published = true;+ expect(options.expectedScanId).toBe("selected-scan");+ return publicationResult();+ };+ deps.publishScanToCustom = async (_directory, options) => {+ published = true;+ expect(options.expectedScanId).toBe("selected-scan");+ return {+ scanId: "selected-scan",+ repositoryId: "repository",+ findingIds: [],+ findingCount: 0,+ };+ };+ const args =+ destination === "linear"+ ? [...DESTINATION_OPTIONS]+ : ["--to", "custom", "--findings-url", "http://localhost:3000"];+ const { runCli } = createCliTest(main);+ expect(await runCli(["publish", "scan", ...args, "--json"], deps)).toBe(+ cancel ? 130 : 0,+ );+ expect(published).toBe(!cancel);+ expect(signals.listeners.get("SIGINT")?.size).toBe(0);+ }+ },+);++test("prints completed publication when an interrupt arrives with its result", async () => {+ const signals = new FakeSignals();+ const deps = dependencies({ signals });+ deps.publishScan = async () => {+ signals.emit("SIGINT");+ return publicationResult();+ };+ const { runCli, stdout } = createCliTest(main);+ expect(+ await runCli(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS, "--json"],+ deps,+ ),+ ).toBe(0);+ expect(JSON.parse(stdout.text())).toEqual(publicationResult());+});+async function publicationScanDirectories(count: number): Promise<string[]> {const root = await publicationDirectory("codex-security-publish-picker-");return Promise.all(@@ -2009,8 +2086,8 @@ describe("publish scan", () => {await runCli(["publish", "scan", ...DESTINATION_OPTIONS, "--json"], deps),).toBe(0);expect(offered.map(({ value }) => value)).toEqual([- firstDirectory,- "selected-completed-scan",+ "first-scan",+ "selected-scan",]);expect(offered.map(({ label }) => label)).toEqual([expect.stringContaining("first-scan"),@@ -2381,3 +2458,69 @@ const publishWithProgress: ReturnType<async function successfulPublication<Args extends unknown[]>(..._args: Args) {return publicationResult();}++for (const [selection, expectedCommand] of [+ [["--scan", "saved-scan"], "get-scan"],+ [["--scan", "latest"], "list-scans"],+ [["--workflow-id", "saved-workflow"], "finding-workflow"],+ [[], "list-scans"],+] as const) {+ for (const [signalName, expectedCode] of [+ ["SIGINT", 130],+ ["SIGTERM", 143],+ ] as const) {+ test(`publication ${selection.join(" ") || "picker"} cancels lookup on ${signalName}`, async () => {+ const signals = new FakeSignals();+ const started = Promise.withResolvers<AbortSignal | undefined>();+ const cleanup = Promise.withResolvers<void>();+ let published = false;+ let command: string | undefined;+ const deps = dependencies({+ signals,+ onWorkbench: async (args, _input, signal) => {+ command = args[0];+ started.resolve(signal);+ await cleanup.promise;+ signal?.throwIfAborted();+ throw new Error("Lookup finished without cancellation.");+ },+ });+ deps.publishPrompt = {+ isInteractive: () => true,+ select: async () => {+ throw new Error("Unexpected picker.");+ },+ };+ deps.publishScan = async () => {+ published = true;+ throw new Error("Unexpected publication.");+ };+ deps.publishScanToCustom = async () => {+ published = true;+ throw new Error("Unexpected publication.");+ };+ const { runCli, stdout } = createCliTest(main);+ const destination =+ selection[0] === "--workflow-id"+ ? ["--to", "custom", "--findings-url", "https://example.invalid"]+ : ["--to", "linear", "--linear-team", "synthetic-team"];+ const running = runCli(+ ["publish", "scan", ...selection, ...destination, "--json"],+ deps,+ );+ const signal = await started.promise;+ signals.emit(signalName);+ const aborted = signal?.aborted;+ cleanup.resolve();+ const exitCode = await running;+ expect(command).toBe(expectedCommand);+ expect(aborted).toBe(true);+ expect(signal?.reason).toBe(signalName);+ expect(exitCode).toBe(expectedCode);+ expect(published).toBe(false);+ expect(stdout.text()).toBe("");+ expect(signals.listeners.get("SIGINT")?.size).toBe(0);+ expect(signals.listeners.get("SIGTERM")?.size).toBe(0);+ });+ }+}diff --git a/sdk/typescript/tests-ts/cloud-publish.test.ts b/sdk/typescript/tests-ts/cloud-publish.test.tsindex cf1a22921..ba4d2c1a7 100644--- a/sdk/typescript/tests-ts/cloud-publish.test.ts+++ b/sdk/typescript/tests-ts/cloud-publish.test.ts@@ -155,6 +155,50 @@ describe("Cloud publication", () => {expect(fetchMock).toHaveBeenCalledTimes(0);});+ test("publishes separate CSV occurrences with distinct canonical identities", async () => {+ const secondOccurrence = "occ_000000000000000000000002";+ const secondRow = csvRow.replace(+ "occ_e79cb19591e696572a1c22be",+ secondOccurrence,+ );+ const path = await csvFixture(`${csvHeader}\n${csvRow}\n${secondRow}\n`);+ const { environment } = await fixture();+ const preview = await publishFindingsCsvToCloud(path, { dryRun: true });+ const findings = preview.findings!;+ expect(new Set(findings.map((finding) => finding.findingId)).size).toBe(2);+ expect(new Set(findings.map((finding) => finding.occurrenceId)).size).toBe(+ 2,+ );+ expect(findings.map((finding) => finding.identity.anchor)).toEqual([+ "occ_e79cb19591e696572a1c22be",+ secondOccurrence,+ ]);+ for (const finding of findings) {+ expect(finding.findingId).toBe(+ `csf_${sha256(finding.fingerprints.primary).slice(0, 24)}`,+ );+ expect(finding.occurrenceId).toBe(+ `occ_${sha256([preview.scanId, finding.fingerprints.primary].join("\0")).slice(0, 24)}`,+ );+ }+ const result = await publishFindingsCsvToCloud(path, {+ environment,+ fetch: async (_url, options) => {+ const payload = JSON.parse(String(options.body));+ expect(payload.findings).toEqual(findings);+ return Response.json(+ {+ status: "accepted",+ finding_ids: ["first", "second"],+ finding_count: 2,+ },+ { status: 201 },+ );+ },+ });+ expect(result.findingCount).toBe(2);+ });+test("posts CSV findings with generated scan provenance", async () => {const path = await csvFixture();const { environment } = await fixture();@@ -222,7 +266,7 @@ describe("Cloud publication", () => {`${csvHeader.replace("finding_id,", "finding_id,candidate_id,")}\n${csvRow.replace("csf_852f90d6e1177502ff113d4a,", "csf_852f90d6e1177502ff113d4a,candidate-001,")}\n`,);const result = await publishFindingsCsvToCloud(path, { dryRun: true });- expect(result.findings?.[0]?.extensions).toEqual({+ expect(result.findings?.[0]?.extensions).toMatchObject({candidateId: "candidate-001",});});diff --git a/sdk/typescript/tests-ts/findings-import.test.ts b/sdk/typescript/tests-ts/findings-import.test.tsindex c62f8fc59..33c364460 100644--- a/sdk/typescript/tests-ts/findings-import.test.ts+++ b/sdk/typescript/tests-ts/findings-import.test.ts@@ -1,3 +1,4 @@+import { execFileSync } from "node:child_process";import { readFile } from "node:fs/promises";import { join } from "node:path";import { describe, expect, test } from "bun:test";@@ -60,13 +61,11 @@ describe("findings import formats", () => {).toEqual(rows.map(({ findingId, occurrenceId }) => [findingId, occurrenceId]),);- expect(- new Set(- bindImportedFindings(parsed, format, "scan", "target").map(- (row) => row.occurrenceId,- ),- ).size,- ).toBe(2);+ const bound = bindImportedFindings(parsed, format, "scan", "target");+ expect(new Set(bound.map((row) => row.occurrenceId)).size).toBe(2);+ if (format === "csv") {+ expect(new Set(bound.map((row) => row.findingId)).size).toBe(2);+ }}await expect(parseImportedFindings(@@ -85,6 +84,9 @@ describe("findings import formats", () => {"'--no-verify' skips hooks","''=literal","'Literal",+ "'=1+1",+ "''-x",+ "''literal","ordinary λ","=formula","\u0085=formula",@@ -261,4 +263,3 @@ describe("findings import formats", () => {).rejects.toThrow("duplicate occurrenceId");});});-import { execFileSync } from "node:child_process";diff --git a/sdk/typescript/tests-ts/findings-server.test.ts b/sdk/typescript/tests-ts/findings-server.test.tsindex 9d8069583..56255a8a7 100644--- a/sdk/typescript/tests-ts/findings-server.test.ts+++ b/sdk/typescript/tests-ts/findings-server.test.ts@@ -8,7 +8,9 @@ import {symlink,writeFile,} from "node:fs/promises";-import type { Server } from "node:http";+import type { IncomingMessage, Server, ServerResponse } from "node:http";+import { handleFindingsRequest } from "../src/server/routes.js";+import { findingsRequestValidator } from "../src/server/validation.js";import { tmpdir } from "node:os";import { delimiter, dirname, join } from "node:path";import { afterEach, expect, spyOn, test, mock } from "bun:test";@@ -1324,3 +1326,73 @@ print(db.execute("SELECT COUNT(*) FROM finding_embeddings").fetchone()[0])`;["repository-history", finding(2).findingId],]);});++test("dashboard can sort and search a stored title with an unpaired surrogate", async () => {+ const { store } = await fixture();+ const base = await start(store);+ const malformed = finding();+ malformed.title = "Synthetic title \ud800";+ expect((await insert(base, [malformed, finding(2)])).status).toBe(201);+ const queries: Record<string, string>[] = [+ {},+ { sort: "title" },+ { query: "synthetic" },+ ];+ for (const parameters of queries) {+ const result = await dashboard(base, parameters);+ expect(result.items).toHaveLength(2);+ expect(+ result.items.find((item) => item.id === malformed.findingId)?.title,+ ).toContain("Synthetic title");+ }+});++test("malformed request targets return invalid_request at the HTTP handler", async () => {+ const { store } = await fixture();+ let status: number | undefined;+ let body: string | undefined;+ await handleFindingsRequest(+ { method: "GET", url: "//" } as IncomingMessage,+ {+ writeHead(code: number) {+ status = code;+ },+ end(data: string) {+ body = data;+ },+ } as ServerResponse,+ store,+ embedder,+ await findingsRequestValidator(),+ );+ expect(status).toBe(400);+ expect(JSON.parse(body!).error).toBe("invalid_request");+});++test("NUL repository IDs are rejected before ingestion and lookup", async () => {+ const { store } = await fixture();+ const embed = mock(embedder.embed);+ const base = await start(store, { embed });+ for (const repositoryId of ["\0", "repository\0suffix"]) {+ const response = await insert(base, [finding()], repositoryId);+ expect(response.status).toBe(400);+ expect(await response.json()).toMatchObject({ error: "invalid_request" });+ const lookup = await fetch(+ `${base}/v1/finding/${finding().findingId}/potential-duplicates?${new URLSearchParams({ repositoryId })}`,+ );+ expect(lookup.status).toBe(400);+ expect(await lookup.json()).toMatchObject({ error: "invalid_request" });+ }+ expect(embed).toHaveBeenCalledTimes(0);+ expect((await store.list({ limit: 50, offset: 0 })).findings).toEqual([]);++ for (const repositoryId of ["repository-a", "\\^@"]) {+ expect((await insert(base, [finding()], repositoryId)).status).toBe(201);+ const lookup = await fetch(+ `${base}/v1/finding/${finding().findingId}/potential-duplicates?${new URLSearchParams({ repositoryId })}`,+ );+ expect(lookup.status).toBe(200);+ expect(await lookup.json()).toMatchObject({ finding: finding() });+ }+ expect(embed).toHaveBeenCalledTimes(2);+});diff --git a/sdk/typescript/tests-ts/github.test.ts b/sdk/typescript/tests-ts/github.test.tsindex 1695e354e..c366117b5 100644--- a/sdk/typescript/tests-ts/github.test.ts+++ b/sdk/typescript/tests-ts/github.test.ts@@ -443,3 +443,16 @@ describe("GitHub import CLI", () => {expect(signals.listeners.get("SIGTERM")?.size).toBe(0);});});++for (const [host, url] of [+ ["github.com", "https://api.github.com/user"],+ ["example.ghe.com", "https://api.example.ghe.com/user"],+ ["github.example.test", "https://github.example.test/api/v3/user"],+]) {+ test(`selects the documented API base for ${host}`, async () => {+ const client = await createAuthenticatedGitHub(host!, {+ token: "synthetic-token",+ });+ expect(client.request.endpoint("/user").url).toBe(url!);+ });+}diff --git a/sdk/typescript/tests-ts/publish.test.ts b/sdk/typescript/tests-ts/publish.test.tsindex a58acf3f3..74a9e949f 100644--- a/sdk/typescript/tests-ts/publish.test.ts+++ b/sdk/typescript/tests-ts/publish.test.ts@@ -6,8 +6,10 @@ import { nodeCommand } from "./support/shell.js";import { randomUUID } from "node:crypto";import {appendFile,+ mkdir,readFile,readdir,+ rename,stat,writeFile,} from "node:fs/promises";@@ -41,6 +43,86 @@ const copyPublishedIssues: PublishScanDependencies["recordPublishedIssues"] =return [...issues];};+test("returns completed publication when cancellation arrives during receipt persistence", async () => {+ const publication = preparedPublication();+ const controller = new AbortController();+ const receipts: PublishScanResult[] = [];+ const result = await publishScanInternal(+ "scan",+ { ...OPTIONS, signal: controller.signal },+ dependencies(publication, {+ writeReceipt: async (receipt) => {+ receipts.push(receipt);+ controller.abort(new Error("Cancellation after saved receipt"));+ },+ }),+ );+ expect(receipts).toHaveLength(1);+ expect(result.counts).toEqual({ findings: 1, created: 1, failed: 0 });+});++test("retains indeterminate publication evidence when reading the handoff fails", async () => {+ const publication = preparedPublication();+ const receipts: PublishScanResult[] = [];+ let file = "";+ const injected = dependencies(publication, {+ runCodex: async (_command, _args, input) => {+ file = publicationData(input).handoffFile;+ await writeHandoff(input, [+ handoffRecord(publication, publication.issues[0]!, {+ identifier: "SEC-123",+ }),+ ]);+ await rename(file, `${file}.saved`);+ await mkdir(file);+ return { exitCode: 0, stdout: "", stderr: "" };+ },+ writeReceipt: async (receipt) => {+ receipts.push(receipt);+ },+ });+ await expect(publishScanInternal("scan", OPTIONS, injected)).rejects.toThrow(+ "could not verify every completed mutation",+ );+ expect(receipts.length).toBeGreaterThan(0);+ expect(receipts[0]!.indeterminate).toBe(true);+ expect(receipts[0]!.failed[0]!.error).toContain("EISDIR");+ expect((await stat(dirname(file))).isDirectory()).toBe(true);+ expect(await readFile(`${file}.saved`, "utf8")).toContain("SEC-123");+});++test("preserves unreadable handoff diagnostics when every connector outcome failed", async () => {+ const publication = preparedPublication();+ const receipts: PublishScanResult[] = [];+ const injected = dependencies(publication, {+ runCodex: async (_command, _args, input) => {+ const file = publicationData(input).handoffFile;+ await rename(file, `${file}.saved`);+ await mkdir(file);+ return {+ exitCode: 0,+ stdout: issueEvent(publication.issues[0]!, {+ status: "failed",+ error: "Synthetic connector failure",+ }),+ stderr: "",+ };+ },+ writeReceipt: async (receipt) => {+ receipts.push(structuredClone(receipt));+ },+ });+ await expect(publishScanInternal("scan", OPTIONS, injected)).rejects.toThrow(+ "EISDIR",+ );+ expect(receipts.length).toBeGreaterThan(0);+ for (const receipt of receipts) {+ expect(receipt.indeterminate).toBe(true);+ expect(receipt.warnings?.join(" ")).toContain("EISDIR");+ expect(receipt.failed[0]?.error).toBe("Synthetic connector failure");+ }+});+function issueMapping(record: Record<string, unknown>) {return [record["findingId"], record["issueIdentifier"]];}@@ -2823,7 +2905,7 @@ describe("connected Linear publication", () => {'].join("");','spawn(process.execPath, ["-e", descendant], { env: { CODEX_PUBLICATION_DESCENDANT_PID: process.env.CODEX_PUBLICATION_DESCENDANT_PID }, stdio: "ignore" });',"const waiter = new Int32Array(new SharedArrayBuffer(4));",- "for (let attempts = 0; !fs.existsSync(process.env.CODEX_PUBLICATION_DESCENDANT_PID); attempts += 1) {",+ "for (let attempts = 0; (!fs.existsSync(process.env.CODEX_PUBLICATION_DESCENDANT_PID) || fs.statSync(process.env.CODEX_PUBLICATION_DESCENDANT_PID).size === 0); attempts += 1) {"," if (attempts === 1000) process.exit(3);"," Atomics.wait(waiter, 0, 0, 10);","}",diff --git a/sdk/typescript/tests-ts/suggest-owners.test.ts b/sdk/typescript/tests-ts/suggest-owners.test.tsindex 5c2e5d6aa..cab02606d 100644--- a/sdk/typescript/tests-ts/suggest-owners.test.ts+++ b/sdk/typescript/tests-ts/suggest-owners.test.ts@@ -479,3 +479,56 @@ test("propagates cancellation", async () => {}),).rejects.toThrow("Canceled by caller");});++test("subdirectory roots retain repository-relative paths when filenames collide", async () => {+ const repo = await repository();+ const subdir = join(repo.path, "src");+ await mkdir(subdir);+ await writeFile(+ join(subdir, "handler.ts"),+ "// Subdirectory handler\nexport function readOther(id) {\n return other[id];\n}\n",+ );+ await repo.git("add", "src/handler.ts");+ await repo.git(+ "-c",+ "user.name=Casey Example",+ "-c",+ "[email protected]",+ "commit",+ "-qm",+ "Add subdirectory handler",+ );+ const { codex, calls } = fakeCodex((context) => {+ const identityIndex = context.identities.findIndex(+ (identity) =>+ identity.email ===+ (context.evidence[0]!.path.startsWith("src/")+ ? "[email protected]"+ : "[email protected]"),+ );+ return {+ identityIndex,+ reason: "Author of the affected committed lines.",+ evidenceIds: context.evidence+ .filter((item) => item.identityIndex === identityIndex)+ .map((item) => item.id),+ };+ });+ const report = await suggestOwners(+ subdir,+ [+ finding,+ {+ ...finding,+ findingId: "subdirectory-finding",+ locations: [{ path: "src/handler.ts", startLine: 2, endLine: 3 }],+ },+ ],+ { codex },+ );+ expect(report.results.map((result) => result.owner?.email)).toEqual([+ "[email protected]",+ "[email protected]",+ ]);+ expect(calls).toHaveLength(2);+});