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
feat(scan): emit optional owner suggestions after scans (#1760)
jameshiester-oaidd42caa7a22a
diff --git a/plugins/codex-security/scripts/workbench_finding_workflows.py b/plugins/codex-security/scripts/workbench_finding_workflows.pyindex 6305d786f..cc692de83 100644--- a/plugins/codex-security/scripts/workbench_finding_workflows.py+++ b/plugins/codex-security/scripts/workbench_finding_workflows.py@@ -210,6 +210,8 @@ def finding_workflow(state["stages"][stage] = {"status": "completed", "result": payload["result"]}elif action == "fail":current.update(status="failed", error=payload["error"])+ if "result" in payload:+ current["result"] = payload["result"]elif action == "prepare-dedupe":current.update(result=payload["result"], pendingWrite=payload["pendingWrite"])else:diff --git a/plugins/codex-security/tests/test_workbench_finding_workflows.py b/plugins/codex-security/tests/test_workbench_finding_workflows.pyindex 251cb989a..5905b7fc2 100644--- a/plugins/codex-security/tests/test_workbench_finding_workflows.py+++ b/plugins/codex-security/tests/test_workbench_finding_workflows.py@@ -138,7 +138,7 @@ def test_failed_stages_resume_and_completed_results_are_immutable(assert completed["workflow"]["stages"][stage] == {"status": "completed", "result": result}for action, payload in [("begin", {}),- ("fail", {"error": "Late failure"}),+ ("fail", {"error": "Late failure", "result": {"unexpected": True}}),("complete", {"result": {"unexpected": True}}),]:assert workflow(workbench_api, workbench_db, action, stage=stage, **payload) == completeddiff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 84d15ab8b..95f036724 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -225,6 +225,7 @@ const result = await security.run("/path/to/repository", {| `scanPrompt` / `scanPromptFile` | Additional scan instructions. Inline text takes precedence. || `validationPrompt` / `validationPromptFile` | Custom validation instructions for standard scans. || `postScanPrompt` / `postScanPromptFile` | Follow-up instructions after the scan. |+| `ownerSuggestions` | Write optional owner suggestions after a committed scan (default: `false`). || `outputDir` | Results directory; omit to use the state directory. || `archiveExisting` | Move previous results aside before reusing `outputDir`. || `maxCostUsd` | Stop at an estimated model cost; see [cost limits](#progress-and-cost). |@@ -233,6 +234,16 @@ const result = await security.run("/path/to/repository", {The exported `ScanOptions` type describes all options and callbacks. For fullCLI behavior, see [scan options and output](docs/cli.md#scan-options-and-output).+Set `ownerSuggestions: true` or run `codex-security scan --owner-suggestions`+to write `owner-suggestions.json` beside a completed committed Git scan. Project+files can set `scan.owner_suggestions: true`. The report uses the scan's finding+IDs and frozen revision; it does not change the sealed findings or assign users.+Owner failures leave the base scan completed and appear as+`result.ownerSuggestionsError`; successful reports set `result.ownerSuggestionsPath`.+Owner inference uses the scan's model and reasoning effort. Owner enrichment is+skipped with a warning when `maxCostUsd` is set, because its inference cannot yet+share the scan cost limit. Working-tree and directory snapshots are unsupported.+### Scan a diff```tsdiff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex 799f22a0f..cf80a3042 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -391,6 +391,7 @@ codex-security scan .codex-security scan . --path src --path testscodex-security scan . --diff origin/main --jsoncodex-security scan . --working-tree+codex-security scan . --owner-suggestionscodex-security scan . --output-dir /path/outside/repository/results --dry-run```@@ -402,6 +403,13 @@ changes. Both require Git. Deep scans support whole repositories and path scopesWorking-tree snapshots include untracked nested Git repositories. Initialized submodules mustbe clean and at the commit recorded by the parent.+`--owner-suggestions` writes optional `owner-suggestions.json` after a completed+committed Git scan, using the same checkout, model, and reasoning effort. Owner+errors leave the base scan completed. The JSON result includes+`ownerSuggestionsPath` or `ownerSuggestionsError`; the sealed findings and+manifest stay unchanged. This option is unsupported for working-tree and+directory snapshots, and is skipped with a warning when `--max-cost` is set.+Repeat `--knowledge-base PATH` for context: UTF-8 text files (including JSON andSARIF), PDF, DOCX, or directories. Directory traversal skips other binary files;explicit unsupported binary files are rejected. Bulk scans share this contextdiff --git a/sdk/typescript/docs/hosted-scans.md b/sdk/typescript/docs/hosted-scans.mdindex 5bb04274d..7f0b0b29d 100644--- a/sdk/typescript/docs/hosted-scans.md+++ b/sdk/typescript/docs/hosted-scans.md@@ -74,6 +74,18 @@ Standard scan lifecycle. Omit `scope` for the entire repository, or pass literalrepository-relative folders/files. Model settings come from the frozen input;local profiles and other local scan options are not accepted.+Set `ownerSuggestions: true` on the input to generate the optional+`owner-suggestions.json` after sealing the base scan. The completed receipt+includes that artifact when available, or `ownerSuggestionsError` if the owner+stage fails. Owner failure or cancellation does not invalidate sealed findings.+The SDK host can pass `ownerCodex` in the options to execute read-only owner+decisions using its own inference service. Without that callback, CODEOWNERS+matches still work and findings that require inference report an owner error.+The callback receives the model and reasoning effort in `startThread`, then+the prompt, output schema, and cancellation signal in `run`.+The CLI protocol does not provide an owner inference callback. Hosted owner+enrichment never launches local Codex or selects local credentials.+`ScanExecutor.run` receives an AbortSignal and an optional `onEvent` observer for`{type: "progress", progress}` or `{type: "activity", activity}` events. Progressuses the existing `ScanProgress` type; activity uses `ScanActivity`. Progress maydiff --git a/sdk/typescript/schemas/project-config.schema.json b/sdk/typescript/schemas/project-config.schema.jsonindex aad9005b5..841ee768d 100644--- a/sdk/typescript/schemas/project-config.schema.json+++ b/sdk/typescript/schemas/project-config.schema.json@@ -31,6 +31,10 @@"type": "string","enum": ["standard", "daybreak_blue", "daybreak_red"]},+ "owner_suggestions": {+ "description": "Generate optional owner-suggestions.json after a committed scan (default: false).",+ "type": "boolean"+ },"scope": {"description": "One scope variant. Omit for the whole repository. Mode compatibility is checked after overrides.","anyOf": [diff --git a/sdk/typescript/scripts/fixtures/package-consumer.ts b/sdk/typescript/scripts/fixtures/package-consumer.tsindex 985170fc7..062823f0f 100644--- a/sdk/typescript/scripts/fixtures/package-consumer.ts+++ b/sdk/typescript/scripts/fixtures/package-consumer.ts@@ -314,12 +314,25 @@ export async function hostedScan(): Promise<HostedScanResult> {const options: HostedScanOptions = {executor,+ ownerCodex: {+ startThread(options) {+ options.model satisfies string | undefined;+ options.modelReasoningEffort satisfies string | undefined;+ return {+ async run(input, options) {+ input satisfies string;+ options.signal satisfies AbortSignal | undefined;+ return { finalResponse: "{}" };+ },+ };+ },+ },signal,onEvent(event) {event.type satisfies "progress" | "activity";},};- return await runHostedScan(input, options);+ return await runHostedScan({ ...input, ownerSuggestions: true }, options);}const localOptions: ScanOptions = {diff --git a/sdk/typescript/scripts/package-dist-files.mjs b/sdk/typescript/scripts/package-dist-files.mjsindex e57af79bd..5f73d814c 100644--- a/sdk/typescript/scripts/package-dist-files.mjs+++ b/sdk/typescript/scripts/package-dist-files.mjs@@ -44,6 +44,7 @@ const distModules = ["provider-profile","scan-modes","scan-settings",+ "scan-owner-suggestions","scan-time-budget","errors","feedback",diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex f83677934..bd5c74ea7 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -43,6 +43,7 @@ import {} from "@openai/codex-sdk";import { z } from "zod";import { readThreatModelPath } from "./artifact-export.js";+import type { HostedScanOptions } from "./hosted-scan.js";import { scanSkillConfig } from "./scan-skill-paths.js";import { isRecord } from "./record.js";import {@@ -614,6 +615,7 @@ interface ClientDependencies {/** Explicit hosted execution; never falls back to createCodex. */hostedScan?: {executor: ScanExecutor;+ ownerCodex: NonNullable<HostedScanOptions["ownerCodex"]>;context: Pick<ScanExecutionRequest,"repository" | "revision" | "scope" | "identity"@@ -755,7 +757,12 @@ export class CodexSecurity {});type ScanMetadata = Pick<ScanResultOptions,- "threadId" | "turnResult" | "sarifPath" | "repositoryFindings"+ | "threadId"+ | "turnResult"+ | "sarifPath"+ | "repositoryFindings"+ | "ownerSuggestionsPath"+ | "ownerSuggestionsError">;if (state.scanId && state.scanDir) {await workflow.protectArtifacts(state.scanDir);@@ -767,7 +774,7 @@ export class CodexSecurity {(scan["progress"] as JsonObject | undefined)?.["status"] ==="complete";if (completed)- metadata = {+ metadata ??= {threadId: (scan["continuationThreadId"] as string) ?? "",turnResult: { status: "completed" },};@@ -794,8 +801,17 @@ export class CodexSecurity {}}await workflow.begin("scan");+ let metadata: ScanMetadata | undefined;try {const result = await this.#run(repository, options, local);+ metadata = {+ threadId: result.threadId,+ turnResult: result.turnResult,+ sarifPath: result.sarifPath,+ repositoryFindings: result.repositoryFindings,+ ownerSuggestionsPath: result.ownerSuggestionsPath,+ ownerSuggestionsError: result.ownerSuggestionsError,+ };await workflow.protectArtifacts(result.scanDir);await workflow.bind({scanId: result.manifest.scan.id,@@ -806,15 +822,10 @@ export class CodexSecurity {coverage: result.coverage,}),});- await workflow.complete("scan", {- threadId: result.threadId,- turnResult: result.turnResult,- sarifPath: result.sarifPath,- repositoryFindings: result.repositoryFindings,- } satisfies ScanMetadata);+ await workflow.complete("scan", metadata);return result;} catch (error) {- await workflow.fail("scan", error);+ await workflow.fail("scan", error, metadata);throw error;}}@@ -2136,6 +2147,7 @@ export class CodexSecurity {maxTimeMinutes: options.maxTimeMinutes,auth: options.auth,cyberAccessProgram: options.cyberAccessProgram,+ ownerSuggestions: options.ownerSuggestions,});if (options.scanPrompt?.trim()) recipe["requiresScanPrompt"] = true;recipe["scanInputs"] = scanInputIdentity(@@ -2893,6 +2905,60 @@ export class CodexSecurity {)(`Could not run post-scan instructions: ${errorMessage(error)}`);}}+ const inferenceRuntimeConfig: JsonObject = {+ ...structuredClone(workerRuntimeConfig),+ responses_api_metadata: workerSnapshot["responses_api_metadata"]!,+ };+ const inferenceFeatures = inferenceRuntimeConfig["features"];+ if (isRecord(inferenceFeatures)) delete inferenceFeatures["plugins"];+ const inferenceOptions = {+ environment,+ nativeProfile: runtime.providerProfile,+ config: {+ codexOverrides: {+ ...scanPreflightCodexConfig(+ resolveCodexProfile(session.sessionConfig),+ ),+ ...inferenceRuntimeConfig,+ },+ },+ model,+ cyberAccessProgram: options.cyberAccessProgram,+ signal,+ };+ if (options.ownerSuggestions) {+ try {+ if (options.maxCostUsd !== undefined)+ throw new Error(+ "Owner suggestions are unavailable when maxCostUsd is set.",+ );+ const { writeScanOwnerSuggestions } =+ await import("./scan-owner-suggestions.js");+ const writer = await prepareArtifactRestorer(+ workbenchOptions,+ scanDir,+ );+ result.ownerSuggestionsPath = await writeScanOwnerSuggestions(+ repo,+ result,+ writer,+ {+ ...inferenceOptions,+ auth: options.auth,+ reasoningEffort: scanModelConfiguration(session.sessionConfig)+ .reasoningEffort,+ codex: this.#dependencies.hostedScan?.ownerCodex,+ },+ this.#surface,+ );+ } catch (error) {+ result.ownerSuggestionsError = errorMessage(error);+ notifyObserver(+ options,+ "onWarning",+ )(`Could not generate owner suggestions: ${errorMessage(error)}`);+ }+ }if (this.#dependencies.hostedScan !== undefined) return result;try {const runWorkbench = (args: readonly string[], input?: string) =>@@ -2903,12 +2969,6 @@ export class CodexSecurity {"all",);if (previousFindings !== undefined) {- const matchingRuntimeConfig: JsonObject = {- ...structuredClone(workerRuntimeConfig),- responses_api_metadata: workerSnapshot["responses_api_metadata"]!,- };- const matchingFeatures = matchingRuntimeConfig["features"];- if (isRecord(matchingFeatures)) delete matchingFeatures["plugins"];await matchCompletedScan({scanId,repository: repo,@@ -2929,19 +2989,7 @@ export class CodexSecurity {singleTurn: options.maxCostUsd !== undefined,},),- environment,- nativeProfile: runtime.providerProfile,- config: {- codexOverrides: {- ...scanPreflightCodexConfig(- resolveCodexProfile(session.sessionConfig),- ),- ...matchingRuntimeConfig,- },- },- model,- cyberAccessProgram: options.cyberAccessProgram,- signal,+ ...inferenceOptions,});result.repositoryFindings = (await listRepositoryFindings(runWorkbench,@@ -4042,6 +4090,7 @@ export class CodexSecurity {maxTimeMinutes: options.maxTimeMinutes,auth: options.auth,cyberAccessProgram: options.cyberAccessProgram,+ ownerSuggestions: options.ownerSuggestions,}),mock: true,},@@ -4940,6 +4989,7 @@ function scanRecipe({deepScan,auth,cyberAccessProgram,+ ownerSuggestions,}: {repository: string;target: NormalizedTarget;@@ -4954,6 +5004,7 @@ function scanRecipe({deepScan?: Required<DeepScanOptions>;auth?: ScanAuthMode;cyberAccessProgram?: ScanSettings["cyberAccessProgram"];+ ownerSuggestions?: boolean;}): JsonObject {return {repository,@@ -4962,6 +5013,7 @@ function scanRecipe({...(repositoryRevision === null ? {} : { repositoryRevision }),pluginVersion,config,+ ...(ownerSuggestions === undefined ? {} : { ownerSuggestions }),...(auth === undefined ? {} : { auth }),...(cyberAccessProgram === undefined ? {} : { cyberAccessProgram }),...(failOnSeverity === undefined ? {} : { failOnSeverity }),diff --git a/sdk/typescript/src/cli-help.ts b/sdk/typescript/src/cli-help.tsindex 1d5347aab..6893c532a 100644--- a/sdk/typescript/src/cli-help.ts+++ b/sdk/typescript/src/cli-help.ts@@ -37,6 +37,7 @@ const SCAN_GROUPS: readonly Group[] = [["output-dir","archive-existing",+ "owner-suggestions","max-cost","max-time","show-cost",diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 27e52285f..307254f14 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -3854,6 +3854,7 @@ export async function main(maxCost: ScanSettingsSchema.shape.maxCostUsd.describe("Stop above AMOUNT in estimated USD; the dashboard offers increases near the limit.",),+ ownerSuggestions: ScanSettingsSchema.shape.ownerSuggestions,showCost: SHOW_COST_OPTION,headless: z.boolean()@@ -6715,6 +6716,13 @@ async function prepareScanArgumentsFromRecipe("The saved scan recipe is missing resolved deep scan settings.",);}+ const ownerSuggestions = ScanSettingsSchema.shape.ownerSuggestions.safeParse(+ recipe["ownerSuggestions"],+ );+ if (!ownerSuggestions.success)+ throw new CodexSecurityError(+ "The saved scan recipe contains an invalid owner suggestions setting.",+ );const auth = z.enum(SCAN_AUTH_MODES).optional().safeParse(recipe["auth"]);const cyberAccessProgram =ScanSettingsSchema.shape.cyberAccessProgram.safeParse(@@ -6762,6 +6770,7 @@ async function prepareScanArgumentsFromRecipe(repository,auth: auth.data ?? DEFAULT_SCAN_AUTH,cyberAccessProgram: cyberAccessProgram.data,+ ownerSuggestions: ownerSuggestions.data,// Saved scopes contain literal repository names, not home-relative inputs.target:paths.length > 0diff --git a/sdk/typescript/src/finding-workflow.ts b/sdk/typescript/src/finding-workflow.tsindex 1acd49f61..fb2eea068 100644--- a/sdk/typescript/src/finding-workflow.ts+++ b/sdk/typescript/src/finding-workflow.ts@@ -111,11 +111,16 @@ export class FindingWorkflow {return (await this.command({ action: "complete", stage, result }))!;}- async fail(stage: WorkflowStage, error: unknown): Promise<void> {+ async fail(+ stage: WorkflowStage,+ error: unknown,+ result?: unknown,+ ): Promise<void> {await this.command({action: "fail",stage,error: errorMessage(error),+ ...(result === undefined ? {} : { result }),}).catch(() => undefined);}diff --git a/sdk/typescript/src/hosted-scan.ts b/sdk/typescript/src/hosted-scan.tsindex b7471b40f..799a3bae4 100644--- a/sdk/typescript/src/hosted-scan.ts+++ b/sdk/typescript/src/hosted-scan.ts@@ -31,6 +31,7 @@ export const HostedScanInputSchema = z.strictObject({stateDirectory: z.string().min(1),model: z.string().min(1),reasoningEffort: z.string(),+ ownerSuggestions: z.boolean().optional(),identity: z.strictObject({runId: z.string().min(1),attemptId: z.string().min(1),@@ -171,6 +172,15 @@ function hostedScanEnvironment(stateDirectory: string): Record<string, string> {export interface HostedScanOptions {executor: ScanExecutor;+ /** Host-owned, read-only inference for the optional owner stage. Never uses local credentials. */+ ownerCodex?: {+ startThread(options: { model?: string; modelReasoningEffort?: string }): {+ run(+ input: string,+ options: { outputSchema?: unknown; signal?: AbortSignal },+ ): Promise<{ finalResponse: string }>;+ };+ };signal?: AbortSignal;onEvent?: (event: ScanExecutionEvent) => void;}@@ -201,6 +211,11 @@ export async function runHostedScan(environment: hostedScanEnvironment(input.stateDirectory),hostedScan: {context,+ ownerCodex: options.ownerCodex ?? {+ startThread() {+ throw new Error("Hosted owner inference is unavailable.");+ },+ },executor: {async run(value, runOptions) {request = value;@@ -245,6 +260,7 @@ export async function runHostedScan(mode: "standard",outputDir: outputDirectory,signal: options.signal,+ ownerSuggestions: input.ownerSuggestions,onOutputDirReady(path) {outputDirectory = path;},@@ -261,8 +277,8 @@ export async function runHostedScan(});if (result.manifest.scan.target.revision !== context.revision ||- (await repositoryRevision(context.repository, options.signal)) !==- context.revision+ // Owner cancellation cannot invalidate an already sealed base scan.+ (await repositoryRevision(context.repository)) !== context.revision)throw new Error("Checkout changed from the frozen revision during execution.",@@ -284,6 +300,8 @@ export async function runHostedScan(...result.manifest.scan.artifacts.map((artifact) => artifact.path),...(isRecord(sources) ? Object.keys(sources) : []),]);+ if (result.ownerSuggestionsPath !== undefined)+ names.add("owner-suggestions.json");const artifacts = await Promise.all([...names].sort().map(async (path) => {const contents = await readScanFile(outputDirectory, path, path);@@ -297,6 +315,9 @@ export async function runHostedScan(return {...base(),status: "completed" as const,+ ...(result.ownerSuggestionsError === undefined+ ? {}+ : { ownerSuggestionsError: result.ownerSuggestionsError }),artifacts,};} catch (error) {diff --git a/sdk/typescript/src/project-config-schema.ts b/sdk/typescript/src/project-config-schema.tsindex 7808a4d2c..6bd59aedb 100644--- a/sdk/typescript/src/project-config-schema.ts+++ b/sdk/typescript/src/project-config-schema.ts@@ -41,6 +41,7 @@ export const ProjectConfigInputSchema = z.strictObject({mode: ScanSettingsSchema.shape.mode,max_time_minutes: ScanSettingsSchema.shape.maxTimeMinutes,cyber_access_program: ScanSettingsSchema.shape.cyberAccessProgram,+ owner_suggestions: ScanSettingsSchema.shape.ownerSuggestions,scope: ProjectScopeSchema.optional().describe("One scope variant. Omit for the whole repository. Mode compatibility is checked after overrides.",),diff --git a/sdk/typescript/src/project-config.ts b/sdk/typescript/src/project-config.tsindex 7cd110a1c..de96005c0 100644--- a/sdk/typescript/src/project-config.ts+++ b/sdk/typescript/src/project-config.ts@@ -59,6 +59,7 @@ const PROJECT_SETTING_KEYS = {mode: "scan.mode",maxTimeMinutes: "scan.max_time_minutes",cyberAccessProgram: "scan.cyber_access_program",+ ownerSuggestions: "scan.owner_suggestions",target: "scan.scope",knowledgeBasePaths: "scan.knowledge_base",scanPromptFile: "scan.instructions_file",@@ -373,6 +374,11 @@ export function resolveScanSettings(mode,maxTimeMinutes,target,+ ownerSuggestions: choose(+ "scan.owner_suggestions",+ file?.scan?.owner_suggestions,+ overrides.ownerSuggestions,+ ),knowledgeBasePaths,scanPromptFile: choose("scan.instructions_file",diff --git a/sdk/typescript/src/result.ts b/sdk/typescript/src/result.tsindex 4f1a937c9..944a6d14a 100644--- a/sdk/typescript/src/result.ts+++ b/sdk/typescript/src/result.ts@@ -45,6 +45,8 @@ export interface ScanResultOptions {sarifPath?: string | null;threatModelPath?: string | null;repositoryFindings?: readonly RepositoryFinding[];+ ownerSuggestionsPath?: string;+ ownerSuggestionsError?: string;}export class ScanResult {@@ -58,6 +60,8 @@ export class ScanResult {public readonly sarifPath: string | null;public readonly threatModelPath: string | null;public repositoryFindings: readonly RepositoryFinding[] | undefined;+ public ownerSuggestionsPath: string | undefined;+ public ownerSuggestionsError: string | undefined;public constructor(options: ScanResultOptions) {this.manifest = options.manifest;@@ -67,6 +71,8 @@ export class ScanResult {this.threadId = options.threadId;this.turnResult = options.turnResult;this.repositoryFindings = options.repositoryFindings;+ this.ownerSuggestionsPath = options.ownerSuggestionsPath;+ this.ownerSuggestionsError = options.ownerSuggestionsError;this.threatModelPath = options.threatModelPath ?? null;this.cost = estimateScanCost(options.turnResult.model,@@ -131,6 +137,12 @@ export class ScanResult {return {manifest: this.manifest,repositoryFindings: this.repositoryFindings,+ ...(this.ownerSuggestionsPath === undefined+ ? {}+ : { ownerSuggestionsPath: this.ownerSuggestionsPath }),+ ...(this.ownerSuggestionsError === undefined+ ? {}+ : { ownerSuggestionsError: this.ownerSuggestionsError }),findings: this.findings,coverage: this.coverage,scanDir: this.scanDir,diff --git a/sdk/typescript/src/scan-owner-suggestions.ts b/sdk/typescript/src/scan-owner-suggestions.tsnew file mode 100644index 000000000..e5295a6b8--- /dev/null+++ b/sdk/typescript/src/scan-owner-suggestions.ts@@ -0,0 +1,65 @@+import { join, relative, sep } from "node:path";+import type { ScanResult } from "./result.js";+import type { ScanArtifactRestorer } from "./runtime.js";+import type { ReadOnlyCodexOptions } from "./scan-comparison.js";+import {+ enclosingGitWorktreeRoot,+ normalizeRepository,+ repositoryRevision,+} from "./targets.js";+import {+ suggestOwnersInternal,+ type SuggestOwnersOptions,+} from "./suggest-owners.js";++export const OWNER_SUGGESTIONS_ARTIFACT = "owner-suggestions.json";++/** Write enrichment beside the sealed scan, without changing its manifest or findings. */+export async function writeScanOwnerSuggestions(+ repository: string,+ result: ScanResult,+ writer: ScanArtifactRestorer,+ options: SuggestOwnersOptions & Pick<ReadOnlyCodexOptions, "auth">,+ surface: "sdk" | "cli" = "sdk",+): Promise<string> {+ const target = result.manifest.scan.target;+ const revision = target.revision ?? target.headRevision;+ if (+ result.manifest.scan.status !== "completed" ||+ !revision ||+ !["git_revision", "git_diff"].includes(target.kind)+ )+ throw new Error(+ "Owner suggestions require a completed scan of committed Git content.",+ );+ if ((await repositoryRevision(repository, options.signal)) !== revision)+ throw new Error(+ "Owner checkout does not match the completed scan revision.",+ );+ const scanRoot = await normalizeRepository(repository, options.signal);+ const gitRoot =+ (await enclosingGitWorktreeRoot(scanRoot, options.signal, {+ requireIfPresent: true,+ })) ?? scanRoot;+ const prefix = relative(gitRoot, scanRoot).split(sep).join("/");+ const report = await suggestOwnersInternal(+ repository,+ result.findings.findings.map((finding) => ({+ ...finding,+ sourceRevision: revision,+ locations: finding.locations.map((location) => ({+ ...location,+ path: prefix ? `${prefix}/${location.path}` : location.path,+ })),+ })),+ options,+ surface,+ );+ if (report.revision !== revision)+ throw new Error("Owner report revision does not match the completed scan.");+ await writer.restore(+ OWNER_SUGGESTIONS_ARTIFACT,+ Buffer.from(`${JSON.stringify(report)}\n`),+ );+ return join(result.scanDir, OWNER_SUGGESTIONS_ARTIFACT);+}diff --git a/sdk/typescript/src/scan-settings.ts b/sdk/typescript/src/scan-settings.tsindex d60439c3e..06e042e2f 100644--- a/sdk/typescript/src/scan-settings.ts+++ b/sdk/typescript/src/scan-settings.ts@@ -125,6 +125,12 @@ export const ScanSettingsSchema = DeepScanSettingsSchema.extend({outputDir: inputPath.optional(),failureSeverity: z.enum(SCAN_SEVERITIES).optional(),maxCostUsd: z.number().positive().optional(),+ ownerSuggestions: z+ .boolean()+ .optional()+ .describe(+ "Generate optional owner-suggestions.json after a committed scan (default: false).",+ ),});/** Scan settings shared by SDK calls, CLI flags, and project files. */diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 2e475f177..a83d5fb31 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -62,7 +62,12 @@ import {import { estimateScanCost, type ScanCost } from "../src/cost.js";import { resolveCodexCommand, runWorkbench } from "../src/runtime.js";import * as runtime from "../src/runtime.js";-import { matchScanFindingsInternal } from "../src/scan-comparison.js";+import * as ownerArtifacts from "../src/scan-owner-suggestions.js";+import { CODEX_SECURITY_THREAD_SOURCES } from "../src/thread-source.js";+import {+ runReadOnlyCodex,+ matchScanFindingsInternal,+} from "../src/scan-comparison.js";import { normalizeTarget } from "../src/targets.js";import {copyCompletedScan,@@ -137,7 +142,16 @@ async function scanDirectories() {return { ...directories, scanDir };}-test.each(["completed", "receipt-lost", "scan-interrupted", "prompt-files"])(+test.each([+ "completed",+ "receipt-lost",+ "scan-interrupted",+ "prompt-files",+ "owner-success",+ "owner-failure",+ "owner-success-receipt-lost",+ "owner-failure-receipt-lost",+])("durable scan workflow resumes after %s without rerunning completed work",async (scenario) => {const root = await temporaryDirectory();@@ -156,9 +170,22 @@ test.each(["completed", "receipt-lost", "scan-interrupted", "prompt-files"])(const scanPrompt = "Review synthetic authentication boundaries.";const promptFile = join(root, "instructions.md");if (scenario === "prompt-files") await writeFile(promptFile, scanPrompt);+ const ownerScenario = scenario.startsWith("owner-");+ const ownerFailure = scenario.startsWith("owner-failure");+ const receiptLost = scenario.endsWith("receipt-lost");+ const ownerPath = join(scanDir, "owner-suggestions.json");+ const ownerSpy = ownerScenario+ ? spyOn(ownerArtifacts, "writeScanOwnerSuggestions").mockImplementation(+ async () => {+ if (ownerFailure) throw new Error("Synthetic owner failure");+ await writeFile(ownerPath, "{}\n");+ return ownerPath;+ },+ )+ : undefined;let modelCalls = 0;let completed = false;- let loseReceipt = scenario === "receipt-lost";+ let loseReceipt = receiptLost;const makeClient = async (attempt: number) => {const codexHome = join(root, `codex-home-${attempt}`);await mkdir(codexHome);@@ -190,6 +217,9 @@ test.each(["completed", "receipt-lost", "scan-interrupted", "prompt-files"])(};if (args[0] === "register-cli-scan") {expect(JSON.parse(input!).workflowId).toBe(workflowId);+ expect(JSON.parse(input!).recipe.ownerSuggestions).toBe(+ ownerScenario || undefined,+ );const registration = mockScanRegistration(args, input);await new FindingWorkflow(workflowId, environment).bind({scanId: registration["scanId"] as string,@@ -213,19 +243,16 @@ test.each(["completed", "receipt-lost", "scan-interrupted", "prompt-files"])(const first = await makeClient(1);let original: Record<string, unknown> | undefined;try {- if (scenario === "completed" || scenario === "prompt-files")- original = (- await first.run(repository, {- workflowId,- ...(scenario === "prompt-files"- ? { scanPromptFile: promptFile }- : {}),- })- ).toJSON();- else- await expect(first.run(repository, { workflowId })).rejects.toThrow(+ const options = {+ workflowId,+ ownerSuggestions: ownerScenario || undefined,+ ...(scenario === "prompt-files" ? { scanPromptFile: promptFile } : {}),+ };+ if (receiptLost || scenario === "scan-interrupted")+ await expect(first.run(repository, options)).rejects.toThrow("Synthetic",);+ else original = (await first.run(repository, options)).toJSON();} finally {await first.close();}@@ -236,6 +263,7 @@ test.each(["completed", "receipt-lost", "scan-interrupted", "prompt-files"])(if (scenario === "prompt-files") await writeFile(replacement, scanPrompt);const result = await resumed.run(repository, {workflowId,+ ownerSuggestions: ownerScenario || undefined,...(scenario === "prompt-files" ? { scanPromptFile: replacement } : {}),});expect(result.manifest.scan.id).toBe("scan_example_001");@@ -243,6 +271,17 @@ test.each(["completed", "receipt-lost", "scan-interrupted", "prompt-files"])(expect.objectContaining({ protectedRoot: repository }),);if (original) expect(result.toJSON()).toEqual(original);+ if (ownerScenario) {+ expect(ownerSpy).toHaveBeenCalledTimes(1);+ expect(result.ownerSuggestionsPath).toBe(+ ownerFailure ? undefined : ownerPath,+ );+ expect(result.ownerSuggestionsError).toBe(+ ownerFailure ? "Synthetic owner failure" : undefined,+ );+ if (!ownerFailure)+ expect(await readFile(ownerPath, "utf8")).toBe("{}\n");+ }expect(modelCalls).toBe(scenario === "scan-interrupted" ? 2 : 1);expect((await new FindingWorkflow(workflowId, environment).get())?.stages.scan@@ -254,6 +293,7 @@ test.each(["completed", "receipt-lost", "scan-interrupted", "prompt-files"])(} finally {python.mockRestore();await resumed.close();+ ownerSpy?.mockRestore();}},);@@ -3557,6 +3597,9 @@ describe("CodexSecurity orchestration", () => {return mockWorkbench(args, input);},hostedScan: {+ ownerCodex: {+ startThread: () => fail("owner inference must not run"),+ },context: {repository,revision: "deadbeef",@@ -5203,8 +5246,39 @@ describe("CodexSecurity orchestration", () => {},);+ const ownerSpy =+ failure === "managed"+ ? spyOn(+ ownerArtifacts,+ "writeScanOwnerSuggestions",+ ).mockImplementation(+ async (_repository, _result, _writer, options) => {+ expect(options.config?.codexOverrides).toMatchObject({+ responses_api_metadata: {+ "team.tag": "synthetic-matching",+ codex_security_integration: "github_action",+ codex_security_command: "scan",+ codex_security_scan_mode: "standard",+ codex_security_provider: "custom",+ },+ });+ await runReadOnlyCodex(+ "Synthetic owner inference",+ {},+ options,+ {+ surface: "sdk",+ command: "suggest-owners",+ threadSource: CODEX_SECURITY_THREAD_SOURCES.suggestOwners,+ },+ );+ return join(scanDir, "owner-suggestions.json");+ },+ )+ : undefined;try {const result = await client.run(repository, {+ ownerSuggestions: failure === "managed",...(limited ? { maxCostUsd: 1 } : {}),cyberAccessProgram: "daybreak_blue",onProgress() {},@@ -5257,10 +5331,17 @@ describe("CodexSecurity orchestration", () => {.trim().split("\n").map((line) => JSON.parse(line));+ expect(ownerSpy).toHaveBeenCalledTimes(1);+ expect(result.ownerSuggestionsPath).toBe(+ join(scanDir, "owner-suggestions.json"),+ );expect(calls.map(({ kind }) => kind)).toEqual(["mcp","preflight","exec",+ "mcp",+ "preflight",+ "exec",]);const metadata = {"synthetic.provider": {@@ -5293,6 +5374,7 @@ describe("CodexSecurity orchestration", () => {} finally {await client.close();spawnSpy?.mockRestore();+ ownerSpy?.mockRestore();}},);diff --git a/sdk/typescript/tests-ts/classify-scan-severity.test.ts b/sdk/typescript/tests-ts/classify-scan-severity.test.tsindex 40a85efa2..6bb4e0a8c 100644--- a/sdk/typescript/tests-ts/classify-scan-severity.test.ts+++ b/sdk/typescript/tests-ts/classify-scan-severity.test.ts@@ -328,7 +328,11 @@ test.each(["id", "prefix", "latest", "missing target"])(: selection === "prefix"? f.scanId.slice(0, 8): f.scanId,- { environment, expectedScanId: f.scanId },+ {+ environment,+ expectedScanId: f.scanId,+ codex: recordingClassifier().codex,+ },{currentDirectory: () =>selection === "latest" ? f.repository : f.caller,@@ -358,6 +362,7 @@ test("saved severity protects repository and caller tools across concurrent lookconst result = await classifyScanSeverityInternal(f.scanId,{+ codex: recordingClassifier().codex,environment: {...f.environment,PYTHON: f.python,diff --git a/sdk/typescript/tests-ts/cli-help.test.ts b/sdk/typescript/tests-ts/cli-help.test.tsindex c8030119e..6bc94cfbe 100644--- a/sdk/typescript/tests-ts/cli-help.test.ts+++ b/sdk/typescript/tests-ts/cli-help.test.ts@@ -81,6 +81,9 @@ describe("CLI help", () => {expect(option(text, "--codex")).toContain("<key=value>");expect(option(text, "--codex")).toMatch(/repeat/iu);expect(option(text, "--max-cost")).toContain("<usd>");+ expect(option(text, "--owner-suggestions")).toContain(+ "owner-suggestions.json",+ );expect(option(text, "--mode")).toContain("<mode>");expect(option(text, "--mode")).toContain("standard");expect(option(text, "--mode")).toContain("deep");diff --git a/sdk/typescript/tests-ts/cli-scan-failures.test.ts b/sdk/typescript/tests-ts/cli-scan-failures.test.tsindex 865f2f49f..72ba3b292 100644--- a/sdk/typescript/tests-ts/cli-scan-failures.test.ts+++ b/sdk/typescript/tests-ts/cli-scan-failures.test.ts@@ -445,3 +445,42 @@ test.each(commands.slice(1))(expectFailure(failure.text(), true, "SCAN_FAILED", message);},);++for (const command of ["rerun", "resume"]) {+ test.each([true, false, undefined])(+ `${command} restores owner suggestions from its saved recipe (%s)`,+ async (ownerSuggestions) => {+ let observed: boolean | undefined;+ let called = false;+ const deps = dependencies({+ onWorkbench: () => ({+ scanId: "saved-scan",+ scanDir: "/tmp/saved-scan",+ recipe: {+ repository: "/original/repository",+ target: { kind: "repository", paths: [] },+ mode: "deep",+ config: {},+ ...(ownerSuggestions === undefined ? {} : { ownerSuggestions }),+ },+ }),+ onTurn: (_repository, options) => {+ called = true;+ observed = options.ownerSuggestions;+ },+ });+ const stdout = capture();+ const stderr = capture();+ expect(+ await main(+ ["scans", command, "saved-scan", "--json"],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(called).toBe(true);+ expect(observed).toBe(ownerSuggestions);+ },+ );+}diff --git a/sdk/typescript/tests-ts/hosted-scan.test.ts b/sdk/typescript/tests-ts/hosted-scan.test.tsindex 4310b50fe..4b45a063a 100644--- a/sdk/typescript/tests-ts/hosted-scan.test.ts+++ b/sdk/typescript/tests-ts/hosted-scan.test.ts@@ -18,6 +18,10 @@ import { runHostProtocol } from "../src/host-protocol.js";import { CodexSecurity, runHostedScan } from "../src/index.js";import * as config from "../src/config.js";import * as hostedScan from "../src/hosted-scan.js";+import * as ownerSuggestions from "../src/suggest-owners.js";+import * as ownerArtifacts from "../src/scan-owner-suggestions.js";+import { runReadOnlyCodex } from "../src/scan-comparison.js";+import { CODEX_SECURITY_THREAD_SOURCES } from "../src/thread-source.js";import {ScanExecutionEventSchema,ScanExecutionResultSchema,@@ -43,6 +47,74 @@ import { writeSource } from "./support/shell.js";const { cleanup, temporaryDirectory } = createApiTestFixtures("hosted-scan-");afterEach(cleanup);+test("hosted owner artifact is opt-in and included in the completed receipt", async () => {+ for (const enabled of [false, true]) {+ const input = await fixture();+ const executor = draftExecutor();+ const result = await runHostedScan(+ { ...input, ownerSuggestions: enabled },+ { executor },+ );+ expect(result.status).toBe("completed");+ expect(executor.run).toHaveBeenCalledTimes(1);+ if (result.status !== "completed") throw new Error(result.status);+ expect(+ result.artifacts.some(({ path }) => path === "owner-suggestions.json"),+ ).toBe(enabled);+ const manifest = await readJson(+ join(input.outputDirectory, "scan-manifest.json"),+ );+ expect(JSON.stringify(manifest)).not.toContain("owner-suggestions.json");+ if (enabled)+ expect(+ await readJson(join(input.outputDirectory, "owner-suggestions.json")),+ ).toMatchObject({+ schemaVersion: 2,+ revision: input.revision,+ results: [],+ });+ }+});++test.each([false, true])(+ "owner failure preserves the completed hosted scan (cancel=%s)",+ async (cancel) => {+ const controller = new AbortController();+ const suggestion = spyOn(+ ownerSuggestions,+ "suggestOwnersInternal",+ ).mockImplementation(async () => {+ if (cancel) controller.abort();+ throw new Error("Synthetic owner-stage failure");+ });+ try {+ const input = await fixture();+ const executor = draftExecutor();+ const result = await runHostedScan(+ { ...input, ownerSuggestions: true },+ {+ executor,+ signal: controller.signal,+ },+ );+ expect(result.status).toBe("completed");+ expect(result).toHaveProperty(+ "ownerSuggestionsError",+ "Synthetic owner-stage failure",+ );+ expect(executor.run).toHaveBeenCalledTimes(1);+ expect(+ result.artifacts.some(({ path }) => path === "owner-suggestions.json"),+ ).toBe(false);+ expect(+ await readJson(join(input.outputDirectory, "scan-manifest.json")),+ ).toHaveProperty("scan.status", "completed");+ } finally {+ suggestion.mockRestore();+ }+ },+);+async function fixture(additionalFiles: readonly string[] = [],): Promise<HostedScanInput> {@@ -1183,3 +1255,61 @@ test("ordinary SDK rejects the removed hosted option instead of using local infeawait client.close();}});++test.each([true, false])(+ "hosted owner inference uses only the hosted callback (supplied=%s)",+ async (supplied) => {+ const input = await fixture();+ const run = mock(async () => ({+ finalResponse: "synthetic owner response",+ }));+ const startThread = mock(() => ({ run }));+ const owner = spyOn(+ ownerArtifacts,+ "writeScanOwnerSuggestions",+ ).mockImplementation(async (_repository, _result, writer, options) => {+ const response = await runReadOnlyCodex(+ "Synthetic owner prompt",+ {},+ options,+ {+ surface: "sdk",+ command: "suggest-owners",+ threadSource: CODEX_SECURITY_THREAD_SOURCES.suggestOwners,+ },+ );+ expect(response).toBe("synthetic owner response");+ await writer.restore("owner-suggestions.json", Buffer.from("{}\n"));+ return join(input.outputDirectory, "owner-suggestions.json");+ });+ try {+ const result = await runHostedScan(+ { ...input, ownerSuggestions: true },+ {+ executor: draftExecutor(),+ ...(supplied ? { ownerCodex: { startThread } } : {}),+ },+ );+ expect(result.status).toBe("completed");+ if (supplied) {+ expect(startThread).toHaveBeenCalledTimes(1);+ expect(run).toHaveBeenCalledTimes(1);+ expect(startThread).toHaveBeenCalledWith(+ expect.objectContaining({+ sandboxMode: "read-only",+ networkAccessEnabled: false,+ }),+ );+ expect(result).not.toHaveProperty("ownerSuggestionsError");+ } else {+ expect(startThread).not.toHaveBeenCalled();+ expect(result).toHaveProperty(+ "ownerSuggestionsError",+ "Hosted owner inference is unavailable.",+ );+ }+ } finally {+ owner.mockRestore();+ }+ },+);diff --git a/sdk/typescript/tests-ts/package-tar-listing.test.ts b/sdk/typescript/tests-ts/package-tar-listing.test.tsindex 014e56d52..b0cf5ec6b 100644--- a/sdk/typescript/tests-ts/package-tar-listing.test.ts+++ b/sdk/typescript/tests-ts/package-tar-listing.test.ts@@ -197,7 +197,7 @@ function commandPath(command: string): string {return path;}-function installPackage(+async function installPackage(root: string,archivePath: string,environment: NodeJS.ProcessEnv,@@ -208,7 +208,7 @@ function installPackage(join(consumer, "package.json"),JSON.stringify({ name: "synthetic-consumer", private: true }),);- const resolved = spawnSync(+ const resolved = await execFileAsync(commandPath("node"),["--input-type=module",@@ -217,15 +217,13 @@ function installPackage(],{ encoding: "utf8", env: environment, windowsHide: true },);- expect({ status: resolved.status, stderr: resolved.stderr }).toEqual({- status: 0,- stderr: "",- });+ expect(resolved.stderr).toBe("");const npm = JSON.parse(resolved.stdout) as {command: string;args: string[];};- return spawnSync(+ return runPackageCommand(+ consumer,npm.command,[...npm.args,@@ -240,13 +238,7 @@ function installPackage("--no-fund",archivePath,],- {- cwd: consumer,- env: environment,- encoding: "utf8",- timeout: 30_000,- windowsHide: true,- },+ environment,);}@@ -255,15 +247,29 @@ function checkPackage(archivePath: string,contractPath: string,environment: NodeJS.ProcessEnv,+): Promise<{ status: number; stderr: string }> {+ return runPackageCommand(+ root,+ commandPath("node"),+ [+ fileURLToPath(new URL("../scripts/check-package.mjs", import.meta.url)),+ archivePath,+ contractPath,+ ],+ environment,+ );+}++function runPackageCommand(+ root: string,+ command: string,+ args: string[],+ environment: NodeJS.ProcessEnv,): Promise<{ status: number; stderr: string }> {return new Promise((resolve, reject) => {execFile(- commandPath("node"),- [- fileURLToPath(new URL("../scripts/check-package.mjs", import.meta.url)),- archivePath,- contractPath,- ],+ command,+ args,{cwd: root,env: environment,@@ -494,7 +500,7 @@ describe("npm package tar listings", () => {test.each(["environment", "user-config"])("keeps npm fixture installs local with global %s settings",- (configuration) => {+ async (configuration) => {const root = mkdtempSync(join(tmpdir(), "codex-package-npm-local-"));try {const archivePath = join(root, "package.tgz");@@ -518,7 +524,7 @@ describe("npm package tar listings", () => {? { npm_config_global: "true" }: {}),});- const installed = installPackage(root, archivePath, environment);+ const installed = await installPackage(root, archivePath, environment);expect({status: installed.status,stderr: installed.status === 0 ? "" : installed.stderr,@@ -689,7 +695,7 @@ describe("npm package tar listings", () => {npm_config_cache: join(root, "npm-cache"),};delete environment["CODEX_SECURITY_EXPECTED_GIT_HEAD"];- const installed = installPackage(root, archivePath, environment);+ const installed = await installPackage(root, archivePath, environment);const consumer = join(root, "consumer");expect({status: installed.status,@@ -844,13 +850,12 @@ describe("npm package tar listings", () => {npm_config_cache: join(root, "npm-cache"),CODEX_SECURITY_EXPECTED_GIT_HEAD: gitHead,};- const installed = installPackage(root, archivePath, environment);+ const installed = await installPackage(root, archivePath, environment);const invalidJson = ["oldgnu-manifest","pax-map-prefix","overwrite-json",].includes(representation);- expect(installed.error).toBeUndefined();if (invalidJson) expect(installed.status).not.toBe(0);else {expect({diff --git a/sdk/typescript/tests-ts/project-config.test.ts b/sdk/typescript/tests-ts/project-config.test.tsindex 726b71d3b..42fabe322 100644--- a/sdk/typescript/tests-ts/project-config.test.ts+++ b/sdk/typescript/tests-ts/project-config.test.ts@@ -23,6 +23,13 @@ afterEach(cleanup);const cases: [string, unknown, boolean][] = [["minimal file", {}, true],+ ["owner artifact enabled", { scan: { owner_suggestions: true } }, true],+ ["owner artifact disabled", { scan: { owner_suggestions: false } }, true],+ [+ "owner artifact requires a boolean",+ { scan: { owner_suggestions: "true" } },+ false,+ ],["fractional investigation minutes",{ scan: { max_time_minutes: 0.5 } },diff --git a/sdk/typescript/tests-ts/scan-owner-suggestions.test.ts b/sdk/typescript/tests-ts/scan-owner-suggestions.test.tsnew file mode 100644index 000000000..9ad6819b6--- /dev/null+++ b/sdk/typescript/tests-ts/scan-owner-suggestions.test.ts@@ -0,0 +1,169 @@+import { afterEach, expect, mock, test } from "bun:test";+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { ScanResult } from "../src/result.js";+import { writeScanOwnerSuggestions } from "../src/scan-owner-suggestions.js";+import { fakeResult } from "./cli-fixtures.js";+import { git } from "./git-fixture.js";+import { createApiTestFixtures } from "./support/temporary-directories.js";++const { cleanup, temporaryDirectory } = createApiTestFixtures("scan-owners-");+afterEach(cleanup);++async function fixture() {+ const repository = await temporaryDirectory();+ await writeFile(join(repository, "handler.ts"), "export const value = 1;\n");+ await writeFile(join(repository, "CODEOWNERS"), "*.ts [email protected]\n");+ git(repository, "init", "-q");+ git(repository, "add", ".");+ git(repository, "commit", "-qm", "Synthetic fixture");+ const source = fakeResult(["high"]);+ source.manifest.scan.target.kind = "git_revision";+ source.manifest.scan.target.revision = git(repository, "rev-parse", "HEAD");+ source.findings.findings[0]!.locations = [+ { path: "handler.ts", startLine: 1 },+ ];+ source.findings.findings[0]!.summary = "Synthetic finding summary.";+ source.findings.findings[0]!.title = "Synthetic ownership finding";+ source.findings.findings[0]!.findingId = "finding-one";+ source.findings.findings[0]!.occurrenceId = "occurrence-one";+ const result = new ScanResult({+ ...source,+ scanDir: await temporaryDirectory(),+ });+ return { repository, result };+}++test.each(["git_revision", "git_diff"] as const)(+ "writes a v2 owner artifact for %s beside unchanged sealed base artifacts",+ async (kind) => {+ const { repository, result } = await fixture();+ const target = result.manifest.scan.target;+ if (kind === "git_diff") {+ const baseRevision = target.revision!;+ await writeFile(+ join(repository, "handler.ts"),+ "export const value = 2;\n",+ );+ git(repository, "add", "handler.ts");+ git(repository, "commit", "-qm", "Synthetic source change");+ target.kind = kind;+ delete target.revision;+ target.baseRevision = baseRevision;+ target.headRevision = git(repository, "rev-parse", "HEAD");+ }+ const revision = target.revision ?? target.headRevision;+ const documents = {+ "scan-manifest.json": result.manifest,+ "findings.json": result.findings,+ "coverage.json": result.coverage,+ };+ for (const [name, document] of Object.entries(documents))+ await writeFile(join(result.scanDir, name), JSON.stringify(document));+ const inference = mock(() => {+ throw new Error("CODEOWNERS needs no inference");+ });+ const restore = mock(async (name: string, bytes: Uint8Array) => {+ await writeFile(join(result.scanDir, name), bytes);+ });+ const path = await writeScanOwnerSuggestions(+ repository,+ result,+ { restore },+ {+ codex: { startThread: inference },+ },+ );+ const report = JSON.parse(await readFile(path, "utf8"));+ expect(report).toMatchObject({+ schemaVersion: 2,+ revision,+ results: [+ {+ findingId: result.findings.findings[0]!.findingId,+ occurrenceId: result.findings.findings[0]!.occurrenceId,+ status: "identified",+ owner: { kind: "person", email: "[email protected]" },+ },+ ],+ });+ expect(restore).toHaveBeenCalledTimes(1);+ expect(inference).not.toHaveBeenCalled();+ for (const [name, document] of Object.entries(documents))+ expect(await readFile(join(result.scanDir, name), "utf8")).toBe(+ JSON.stringify(document),+ );+ },+);++test.each(["directory_snapshot", "git_worktree"] as const)(+ "does not attribute %s findings to committed HEAD",+ async (kind) => {+ const { repository, result } = await fixture();+ result.manifest.scan.target.kind = kind;+ const restore = mock(async () => {});+ await expect(+ writeScanOwnerSuggestions(repository, result, { restore }, {}),+ ).rejects.toThrow("committed Git content");+ expect(restore).not.toHaveBeenCalled();+ },+);++test("rejects a changed checkout before starting owner inference", async () => {+ const { repository, result } = await fixture();+ result.manifest.scan.target.revision = "a".repeat(40);+ const restore = mock(async () => {});+ const inference = mock(() => {+ throw new Error("must not run");+ });+ await expect(+ writeScanOwnerSuggestions(+ repository,+ result,+ { restore },+ {+ codex: { startThread: inference },+ },+ ),+ ).rejects.toThrow("checkout does not match");+ expect(inference).not.toHaveBeenCalled();+ expect(restore).not.toHaveBeenCalled();+});++test.each([true, false])(+ "subdirectory owners use Git-root paths (root collision=%s)",+ async (collision) => {+ const { repository, result } = await fixture();+ const service = join(repository, "service");+ await mkdir(service);+ await writeFile(join(service, "handler.ts"), "export const service = 1;\n");+ await writeFile(+ join(repository, "CODEOWNERS"),+ "/handler.ts [email protected]\n/service/handler.ts [email protected]\n",+ );+ if (!collision) await rm(join(repository, "handler.ts"));+ git(repository, "add", ".");+ git(repository, "commit", "-qm", "Synthetic service");+ result.manifest.scan.target.revision = git(repository, "rev-parse", "HEAD");+ const inference = mock(() => {+ throw new Error("CODEOWNERS needs no inference");+ });+ const path = await writeScanOwnerSuggestions(+ service,+ result,+ {+ restore: async (name, bytes) => {+ await writeFile(join(result.scanDir, name), bytes);+ },+ },+ { codex: { startThread: inference } },+ );+ const report = JSON.parse(await readFile(path, "utf8"));+ expect(report.results[0]).toMatchObject({+ status: "identified",+ owner: { email: "[email protected]" },+ });+ expect(result.findings.findings[0]!.locations[0]!.path).toBe("handler.ts");+ expect(inference).not.toHaveBeenCalled();+ },+);