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(cli): publish completed security scans to Linear (#447)
Kyle Browneb38385a415e
diff --git a/README.md b/README.mdindex 353830ea0..4089fb3cd 100644--- a/README.md+++ b/README.md@@ -79,6 +79,29 @@ root cause, reuses saved matches, and identifies new, persisting, reopened,resolved, or unknown findings. Missing findings remain unknown when coverage isincomplete or their original location was not reviewed.+## Publish scan findings++Publish every finding from a completed scan to a Linear team:++```bash+npx @openai/codex-security publish scan /path/to/scan \+ --to linear \+ --linear-team TEAM_ID+```++Add `--project PROJECT_ID` to place the issues in a Linear project, or omit it+to create issues directly in the team. Omit the scan directory to select a+completed scan interactively. You can also set `CODEX_SECURITY_LINEAR_TEAM` and+the optional `CODEX_SECURITY_LINEAR_PROJECT` instead of passing the destination+flags. Add `--dry-run` to preview the issues or `--json` to return+machine-readable results.++Publishing uses your existing Codex sign-in and connected Linear app; no+separate Linear token is required. Every finding creates a new issue containing+the scan ID, affected code locations, source snippets, and remediation guidance.+Choose a destination authorized to receive the repository's source code and+vulnerability details.+## Verbose diagnosticsAdd `--verbose` to print scan diagnostics to stderr:diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex e60c3590b..abad08a5e 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -242,6 +242,8 @@ npx @openai/codex-security exportnpx @openai/codex-security export /path/outside/repository/results --export-format sarif --output /path/outside/repository/results.sarifnpx @openai/codex-security export /path/outside/repository/results --export-format csv --output /path/outside/repository/findings.csvnpx @openai/codex-security export /path/outside/repository/results --export-format json --output /path/outside/repository/findings.json+npx @openai/codex-security publish scan /path/outside/repository/results --to linear --linear-team TEAM_ID+npx @openai/codex-security publish scan --to linear --linear-team TEAM_IDnpx @openai/codex-security validate /path/outside/repository/findings.json "Possible SQL injection in src/query.ts:42"npx @openai/codex-security validate "Possible SQL injection" --effort highnpx @openai/codex-security patch /path/outside/repository/findings.json "Missing authorization check in src/routes.ts:18"@@ -544,6 +546,72 @@ and scans stopped at their configured cost limit do not start another turn.invocation and defaults to `1`. Results remain under `--output-dir`; rerun thesame command to resume.+### Publish completed scans to Linear++Publish every finding from a completed standard, deep, or scoped scan to one+Linear team:++```bash+npx @openai/codex-security publish scan /path/to/completed-scan \+ --to linear \+ --linear-team TEAM_ID+```++Add `--project PROJECT_ID` to place the issues in a Linear project. Without a+project, issues are created directly in the selected team.++To choose from all completed scans saved in your local scan history, omit the+scan directory:++```bash+npx @openai/codex-security publish scan \+ --to linear \+ --linear-team TEAM_ID+```++Destination flags take precedence over `CODEX_SECURITY_LINEAR_TEAM` and the+optional `CODEX_SECURITY_LINEAR_PROJECT`. Use `--dry-run` to preview the issue+titles without creating them, or `--json` to return structured publication+results.++Publishing starts Codex with your existing Codex configuration and connected+Linear app. Sign in to Codex and connect Linear before publishing. The command+does not require a Linear API token and does not use the isolated Codex home+created for security scans.++Each finding creates a separate new issue titled+`[Codex Security][HIGH] Finding title`. The issue includes the scan ID,+repository, scanned scope, source locations and code snippets, severity,+confidence, vulnerability classification, summary, and remediation guidance.+Verified immutable Git revisions include source links. Findings are published+concurrently in batches of up to 20. Successful issue identifiers are linked+to their findings in the local scan-history database, and structured results+are read back from that database rather than generated by Codex. The completed+scan must already exist in the local scan history. Running publication again+creates another set of issues for the same scan; existing issues are not+matched, updated, or reused.++Issue descriptions contain source code and vulnerability details. Select a+Linear destination authorized to receive that information. Publication receipts+are stored separately from the sealed scan artifacts.++You can also publish a scan from TypeScript:++```ts+import { publishScan } from "@openai/codex-security";++const publication = await publishScan("/path/to/completed-scan", {+ destination: "linear",+ teamId: "TEAM_ID",+});++console.log(publication.scanId);+console.log(publication.created.length);+```++Add `projectId: "PROJECT_ID"` to the options to publish into a specific Linear+project instead of directly to the team.+### Scan history and reruns`scans` or `scans list` lists scans for the current repository. Pass a repositorydiff --git a/sdk/typescript/scripts/smoke-package.mjs b/sdk/typescript/scripts/smoke-package.mjsindex 3ccb900a1..b2c811d2d 100644--- a/sdk/typescript/scripts/smoke-package.mjs+++ b/sdk/typescript/scripts/smoke-package.mjs@@ -1,6 +1,8 @@import assert from "node:assert/strict";import { spawnSync } from "node:child_process";import {+ chmod,+ cp,mkdir,mkdtemp,readFile,@@ -344,7 +346,7 @@ try {["--input-type=module","--eval",- `const sdk = await import(${JSON.stringify(packageManifest.name)}); if (typeof sdk.CodexSecurity !== "function") throw new Error("The installed package does not export CodexSecurity.");`,+ `const sdk = await import(${JSON.stringify(packageManifest.name)}); if (typeof sdk.CodexSecurity !== "function") throw new Error("The installed package does not export CodexSecurity."); if (typeof sdk.publishScan !== "function") throw new Error("The installed package does not export publishScan.");`,],{ cwd: consumer },);@@ -398,6 +400,51 @@ try {const help = runInstalledCli("--help");assert.match(help, /Usage: codex-security\b/u);+ assert.match(help, /\bpublish\b/u);++ const publicationScan = join(consumer, "publication-scan");+ await cp(+ join(installedRoot, "_bundled_plugin", "examples", "completed-scan"),+ publicationScan,+ { recursive: true },+ );+ if (process.platform !== "win32") await chmod(publicationScan, 0o700);+ const publication = JSON.parse(+ run(+ process.execPath,+ [+ launcher,+ "publish",+ "scan",+ publicationScan,+ "--to",+ "linear",+ "--linear-team",+ "team-example",+ "--dry-run",+ "--json",+ ],+ {+ cwd: consumer,+ capture: true,+ env: {+ ...process.env,+ CODEX_SECURITY_LINEAR_PROJECT: "",+ CODEX_SECURITY_STATE_DIR: join(consumer, "publication-state"),+ },+ },+ ),+ );+ assert.equal(publication.scanId, "scan_example_001");+ assert.equal(publication.uploadId, publication.scanId);+ assert.deepEqual(publication.destination, {+ type: "linear",+ teamId: "team-example",+ });+ assert.equal(publication.dryRun, true);+ assert.equal(publication.counts.findings, 1);+ assert.equal(publication.counts.created, 0);+ assert.match(publication.issues[0].title, /^\[Codex Security\]\[HIGH\] /u);await smokeNestedDeepScanWorker(installedRoot, consumer);diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 8b949e52e..f1b79d6ba 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -82,6 +82,7 @@ import {} from "./errors.js";import type { SeverityLevel } from "./models.js";import { runMultiscan } from "./multiscan.js";+import { publishScan } from "./publish.js";import type { ScanResult } from "./result.js";import {bundledPluginRoot,@@ -211,6 +212,9 @@ const VALUE_OPTIONS = new Set(["--token-offset","--scan-root","--reason",+ "--to",+ "--linear-team",+ "--project",]);const PROVIDER_OPTION = z.enum(["openai", "openrouter", "fireworks", "amazon-bedrock"])@@ -408,6 +412,8 @@ interface CliDependencies {) => Promise<string>;hasStoredChatGPTSignIn?: () => Promise<boolean>;scanAuthenticationPrompt?: Pick<BulkScanPrompt, "isInteractive" | "select">;+ publishPrompt?: Pick<BulkScanPrompt, "isInteractive" | "select">;+ publishScan?: typeof publishScan;currentDirectory(): string;now(): number;setInterval(callback: () => void, milliseconds: number): NodeJS.Timeout;@@ -1233,8 +1239,213 @@ export async function main();},});+ const publication = Cli.create("publish", {+ description: "Publish completed Codex Security scan findings.",+ }).command("scan", {+ description: "Publish every finding from a completed scan to Linear.",+ destructive: true,+ mcp: false,+ args: z.object({+ scanDir: z+ .string()+ .optional()+ .describe("Completed scan directory; omit to select a saved scan."),+ }),+ options: z.object({+ to: z.literal("linear").describe("Publication destination."),+ linearTeam: optionValue("--linear-team")+ .optional()+ .describe("Linear team ID; defaults to CODEX_SECURITY_LINEAR_TEAM."),+ project: optionValue("--project")+ .optional()+ .describe(+ "Optional Linear project ID; defaults to CODEX_SECURITY_LINEAR_PROJECT.",+ ),+ dryRun: z+ .boolean()+ .default(false)+ .describe("Preview the findings without creating Linear issues."),+ }),+ output: z.record(z.string(), z.unknown()).optional(),+ async run({ args, options }) {+ const controller = new AbortController();+ const onInterrupt = (): void => controller.abort("SIGINT");+ const onTerminate = (): void => controller.abort("SIGTERM");+ let observingSignals = false;+ try {+ const teamId =+ options.linearTeam?.trim() ||+ dependencies.environment["CODEX_SECURITY_LINEAR_TEAM"]?.trim();+ if (!teamId) {+ throw new CodexSecurityError(+ "--linear-team or CODEX_SECURITY_LINEAR_TEAM is required.",+ );+ }+ const selectedProject = options.project?.trim();+ if (options.project !== undefined && !selectedProject) {+ throw new CodexSecurityError("--project must not be empty.");+ }+ const projectId =+ selectedProject ||+ dependencies.environment["CODEX_SECURITY_LINEAR_PROJECT"]?.trim() ||+ undefined;++ let scanDir = args.scanDir;+ if (scanDir === undefined) {+ const prompt =+ dependencies.publishPrompt ??+ createBulkScanDiscoveryDependencies({+ output: errorOutput,+ now: dependencies.now,+ currentDirectory: dependencies.currentDirectory,+ }).prompt;+ if (!prompt.isInteractive()) {+ throw new CodexSecurityError(+ "Interactive scan selection requires a terminal. Provide a completed scan directory: codex-security publish scan /path/to/sealed-scan --to linear --linear-team TEAM_ID.",+ );+ }+ const saved = await dependencies.runWorkbench([+ "list-scans",+ "--status",+ "complete",+ ]);+ const listedScans = saved["scans"];+ if (!Array.isArray(listedScans)) {+ throw new CodexSecurityError(+ "Could not read completed Codex Security scans.",+ );+ }+ const scans = (+ await Promise.all(+ listedScans.map(async (scan) => {+ if (!isJsonObject(scan)) return undefined;+ const directory = scan["scanDir"];+ if (typeof directory !== "string" || directory.length === 0) {+ return undefined;+ }+ const metadata = await lstat(+ resolve(dependencies.currentDirectory(), directory),+ ).catch(() => undefined);+ return metadata?.isDirectory() === true &&+ !metadata.isSymbolicLink()+ ? scan+ : undefined;+ }),+ )+ ).filter((scan): scan is JsonObject => scan !== undefined);+ const choices = scans.flatMap((scan) => {+ if (!isJsonObject(scan)) return [];+ const progress = scan["progress"];+ const scanId = scan["scanId"];+ const directory = scan["scanDir"];+ if (+ typeof scanId !== "string" ||+ scanId.length === 0 ||+ typeof directory !== "string" ||+ directory.length === 0 ||+ progress === undefined ||+ !isJsonObject(progress) ||+ progress["status"] !== "complete"+ ) {+ return [];+ }+ const targetSummary = scan["targetSummary"];+ const targetPath = scan["targetPath"];+ const repository =+ typeof targetSummary === "string" && targetSummary.trim()+ ? targetSummary.trim()+ : typeof targetPath === "string" && targetPath.trim()+ ? basename(targetPath)+ : "unknown repository";+ const completedAt = scan["completedAt"];+ const startedAt = scan["startedAt"];+ const updatedAt = scan["updatedAt"];+ const timestamp =+ typeof completedAt === "string" && completedAt+ ? completedAt+ : typeof startedAt === "string" && startedAt+ ? startedAt+ : typeof updatedAt === "string" && updatedAt+ ? updatedAt+ : "unknown date";+ const findingCount = scan["findingCount"];+ const findings =+ typeof findingCount === "number"+ ? `${findingCount} finding${findingCount === 1 ? "" : "s"}`+ : "unknown findings";+ return [+ {+ label: `${repository} · ${scanId} · ${timestamp} · ${findings} · COMPLETE`,+ value: directory,+ },+ ];+ });+ if (choices.length === 0) {+ throw new CodexSecurityError(+ "No completed Codex Security scans are available to publish.",+ );+ }+ scanDir = await prompt.select(+ "Which completed scan would you like to publish?",+ choices,+ );+ }++ if (!options.dryRun) {+ dependencies.addSignalListener("SIGINT", onInterrupt);+ dependencies.addSignalListener("SIGTERM", onTerminate);+ observingSignals = true;+ }+ const result = await (dependencies.publishScan ?? publishScan)(+ resolve(dependencies.currentDirectory(), scanDir),+ {+ destination: options.to,+ teamId,+ ...(projectId === undefined ? {} : { projectId }),+ dryRun: options.dryRun,+ ...(options.dryRun ? {} : { signal: controller.signal }),+ },+ );+ controller.signal.throwIfAborted();+ if (result.failed.length > 0) exitCode = 2;+ if ("warnings" in result && Array.isArray(result.warnings)) {+ for (const warning of result.warnings) {+ if (typeof warning !== "string") continue;+ errorOutput.write(+ `codex-security: ${diagnosticValue(safeErrorMessage(warning))}\n`,+ );+ }+ }+ return { ...result };+ } catch (error) {+ const signal = controller.signal.reason;+ if (signal === "SIGINT" || signal === "SIGTERM") {+ const reason =+ signal === "SIGINT"+ ? "Publication canceled by Ctrl-C."+ : "Publication terminated by SIGTERM.";+ const recovery =+ error === signal+ ? ""+ : ` ${diagnosticValue(safeErrorMessage(error))}`;+ errorOutput.write(`codex-security: ${reason}${recovery}\n`);+ exitCode = signal === "SIGINT" ? 130 : 143;+ } else {+ errorOutput.write(`codex-security: ${errorMessage(error)}\n`);+ exitCode = 2;+ }+ return undefined;+ } finally {+ if (observingSignals) {+ dependencies.removeSignalListener("SIGINT", onInterrupt);+ dependencies.removeSignalListener("SIGTERM", onTerminate);+ }+ }+ },+ });const cli = Cli.create("codex-security", {- description: "Run, validate, patch, and export Codex Security findings.",+ description:+ "Run, validate, patch, export, and publish Codex Security findings.",version: VERSION,mcp: {command: "npx --yes @openai/codex-security --mcp",@@ -1534,6 +1745,7 @@ export async function main(}).command(scanHistory).command(findingFeedback)+ .command(publication).command("bulk-scan", {description:"Discover repositories and run resumable bulk security scans.",@@ -2240,6 +2452,7 @@ function validateCliArguments("scans","findings","export",+ "publish","validate","patch","login",@@ -2302,7 +2515,8 @@ function validateCliArguments(return "Markdown output is not supported for scan results.";}}- const nestedCommand = command === "scans" || command === "findings";+ const nestedCommand =+ command === "scans" || command === "findings" || command === "publish";const subcommand = nestedCommand ? argv[commandIndex + 1] : undefined;if (command === "info") {const metadataFields = new Set([diff --git a/sdk/typescript/src/contract.ts b/sdk/typescript/src/contract.tsindex bd7549f3b..559f17a1e 100644--- a/sdk/typescript/src/contract.ts+++ b/sdk/typescript/src/contract.ts@@ -831,8 +831,8 @@ async function openCheckedScanFile(throwIfAborted(signal);if (!opened.isFile() ||- opened.dev !== checked.metadata.dev ||- opened.ino !== checked.metadata.ino+ opened.ino !== checked.metadata.ino ||+ !(await sameCheckedFileDevice(file, checked, opened))) {throw new ContractValidationError(`${context}: expected the checked regular file.`,@@ -876,6 +876,46 @@ async function openCheckedScanFile(}}+export async function sameCheckedFileDevice(+ file: FileHandle,+ checked: CheckedScanFile,+ opened: Stats,+ platform: NodeJS.Platform = process.platform,+ openReference: (path: string, flags: number) => Promise<FileHandle> = open,+): Promise<boolean> {+ if (opened.ino !== checked.metadata.ino) return false;+ if (opened.dev === checked.metadata.dev) return true;+ if (platform !== "win32") return false;++ const [openedIdentity, checkedIdentity] = await Promise.all([+ file.stat({ bigint: true }),+ lstat(checked.path, { bigint: true }),+ ]);+ if (+ !openedIdentity.isFile() ||+ !checkedIdentity.isFile() ||+ checkedIdentity.isSymbolicLink() ||+ openedIdentity.ino !== checkedIdentity.ino+ ) {+ return false;+ }++ const reference = await openReference(+ checked.path,+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,+ );+ try {+ const referenceIdentity = await reference.stat({ bigint: true });+ return (+ referenceIdentity.isFile() &&+ openedIdentity.dev === referenceIdentity.dev &&+ openedIdentity.ino === referenceIdentity.ino+ );+ } finally {+ await reference.close();+ }+}+function throwIfAborted(signal?: AbortSignal): void {if (!signal?.aborted) return;throw (diff --git a/sdk/typescript/tests-ts/cli-publish.test.ts b/sdk/typescript/tests-ts/cli-publish.test.tsnew file mode 100644index 000000000..03b6b4a95--- /dev/null+++ b/sdk/typescript/tests-ts/cli-publish.test.ts@@ -0,0 +1,789 @@+import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { afterEach, describe, expect, test } from "bun:test";+import { main } from "../src/cli.js";+import { capture, dependencies, FakeSignals } from "./cli-fixtures.js";++const DESTINATION_OPTIONS = [+ "--to",+ "linear",+ "--linear-team",+ "team-from-flags",+ "--project",+ "project-from-flags",+] as const;+const temporaryDirectories: string[] = [];++afterEach(async () => {+ await Promise.all(+ temporaryDirectories+ .splice(0)+ .map((directory) => rm(directory, { recursive: true, force: true })),+ );+});++async function publicationDirectory(): Promise<string> {+ const directory = await mkdtemp(+ join(tmpdir(), "codex-security-cli-publication-"),+ );+ temporaryDirectories.push(directory);+ return directory;+}++function publicationResult(+ failed: { findingId: string; error: string }[] = [],+) {+ const created = [+ {+ findingId: "finding-1",+ occurrenceId: "occurrence-1",+ issueIdentifier: "SEC-123",+ url: "https://linear.app/example/issue/SEC-123",+ },+ ];+ return {+ scanId: "scan-123",+ uploadId: "scan-123",+ destination: {+ type: "linear" as const,+ teamId: "team-from-flags",+ projectId: "project-from-flags",+ },+ created,+ failed,+ counts: {+ findings: created.length + failed.length,+ created: created.length,+ failed: failed.length,+ },+ };+}++describe("publish scan", () => {+ test("publishes an explicit scan directory without inspecting scan history", async () => {+ const currentDirectory = join(tmpdir(), "codex-security-publish-current");+ const stdout = capture();+ const stderr = capture();+ let invocation:+ | { scanDirectory: string; options: Record<string, unknown> }+ | undefined;+ const deps = dependencies({+ currentDirectory,+ onWorkbench: () => {+ throw new Error("scan history must not be inspected");+ },+ });+ deps.createSecurity = () => {+ throw new Error("a new security scan must not be started");+ };+ deps.publishScan = async (scanDirectory, options) => {+ invocation = { scanDirectory, options: { ...options } };+ return publicationResult();+ };++ expect(+ await main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS, "--json"],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(invocation).toEqual({+ scanDirectory: resolve(currentDirectory, "completed-scan"),+ options: {+ destination: "linear",+ teamId: "team-from-flags",+ projectId: "project-from-flags",+ dryRun: false,+ signal: expect.any(AbortSignal),+ },+ });+ expect(JSON.parse(stdout.text())).toEqual(publicationResult());+ expect(stderr.text()).toBe("");+ });++ test("publishes directly to a Linear team when no project is selected", async () => {+ const stdout = capture();+ const stderr = capture();+ const result = {+ ...publicationResult(),+ destination: { type: "linear" as const, teamId: "team-from-flags" },+ };+ let options: Record<string, unknown> | undefined;+ const deps = dependencies();+ deps.publishScan = async (_scanDirectory, selected) => {+ options = { ...selected };+ return result;+ };++ expect(+ await main(+ [+ "publish",+ "scan",+ "completed-scan",+ "--to",+ "linear",+ "--linear-team",+ "team-from-flags",+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(options).toMatchObject({+ destination: "linear",+ teamId: "team-from-flags",+ dryRun: false,+ signal: expect.any(AbortSignal),+ });+ expect(options).not.toHaveProperty("projectId");+ expect(JSON.parse(stdout.text())).toEqual(result);+ expect(JSON.parse(stdout.text()).destination).not.toHaveProperty(+ "projectId",+ );+ expect(stderr.text()).toBe("");+ });++ test("waits for interrupted publication recovery before honoring either terminal signal", async () => {+ for (const [signal, expectedCode, expectedMessage] of [+ ["SIGINT", 130, "Publication canceled by Ctrl-C."],+ ["SIGTERM", 143, "Publication terminated by SIGTERM."],+ ] as const) {+ const stdout = capture();+ const stderr = capture();+ const signals = new FakeSignals();+ const events: string[] = [];+ let enteredPublication!: () => void;+ const publicationStarted = new Promise<void>((resolve) => {+ enteredPublication = resolve;+ });+ let finishRecovery!: () => void;+ const recoveryFinished = new Promise<void>((resolve) => {+ finishRecovery = resolve;+ });+ const deps = dependencies({ signals });+ deps.forceExit = (forced) => events.push(`forced ${forced}`);+ deps.publishScan = async (_scanDirectory, options) => {+ expect(options.signal).toBeInstanceOf(AbortSignal);+ options.signal?.addEventListener("abort", () => {+ events.push(`aborted ${String(options.signal?.reason)}`);+ });+ signals.emit(signal);+ expect(events).toEqual([`aborted ${signal}`]);+ enteredPublication();+ await recoveryFinished;+ events.push("recovered created issues");+ throw new Error(+ "The publication handoff remains at /tmp/synthetic-handoff; recover it before retrying to avoid creating duplicate issues.",+ );+ };++ let finished = false;+ const publishing = main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS, "--json"],+ stdout.stream,+ stderr.stream,+ deps,+ ).then((status) => {+ finished = true;+ return status;+ });+ await publicationStarted;+ expect(finished).toBe(false);+ expect(signals.listeners.get("SIGINT")?.size).toBe(1);+ expect(signals.listeners.get("SIGTERM")?.size).toBe(1);+ expect(stdout.text()).toBe("");+ expect(stderr.text()).toBe("");+ finishRecovery();++ expect(await publishing).toBe(expectedCode);++ expect(events).toEqual([`aborted ${signal}`, "recovered created issues"]);+ expect(stderr.text()).toContain(expectedMessage);+ expect(stderr.text()).toContain("recover it before retrying");+ expect(stdout.text()).toBe("");+ expect(signals.listeners.get("SIGINT")?.size).toBe(0);+ expect(signals.listeners.get("SIGTERM")?.size).toBe(0);+ }+ });++ test("interactively selects a completed scan across all repositories", async () => {+ const directory = await publicationDirectory();+ const firstDirectory = join(directory, "first-completed-scan");+ const selectedDirectory = join(directory, "selected-completed-scan");+ await Promise.all([mkdir(firstDirectory), mkdir(selectedDirectory)]);+ const stdout = capture();+ const stderr = capture(true);+ let question = "";+ let choices: readonly { label: string; value: string }[] = [];+ let workbenchArguments: readonly string[] | undefined;+ let publishedDirectory: string | undefined;+ const deps = dependencies({+ onWorkbench: (args) => {+ workbenchArguments = args;+ return {+ scans: [+ {+ scanId: "first-scan",+ scanDir: firstDirectory,+ targetPath: join(tmpdir(), "first-repository"),+ startedAt: "2026-08-15T01:00:00Z",+ completedAt: "2026-08-15T01:05:00Z",+ updatedAt: "2026-08-15T01:05:00Z",+ findingCount: 1,+ progress: { status: "complete" },+ },+ {+ scanId: "second-scan",+ scanDir: selectedDirectory,+ targetPath: join(tmpdir(), "second-repository"),+ startedAt: null,+ completedAt: null,+ updatedAt: "2026-08-15T02:15:00Z",+ findingCount: 3,+ progress: { status: "complete" },+ },+ {+ scanId: "running-scan",+ scanDir: join(tmpdir(), "running-scan"),+ targetPath: join(tmpdir(), "running-repository"),+ startedAt: "2026-08-15T03:00:00Z",+ completedAt: null,+ updatedAt: "2026-08-15T03:01:00Z",+ findingCount: 0,+ progress: { status: "running" },+ },+ ],+ };+ },+ });+ deps.publishPrompt = {+ isInteractive: () => true,+ select: async <Value extends string>(+ message: string,+ options: readonly { label: string; value: Value }[],+ ): Promise<Value> => {+ question = message;+ choices = options;+ return options[1]!.value;+ },+ };+ deps.publishScan = async (scanDirectory) => {+ publishedDirectory = scanDirectory;+ return publicationResult();+ };++ expect(+ await main(+ ["publish", "scan", ...DESTINATION_OPTIONS, "--json"],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(workbenchArguments).toEqual(["list-scans", "--status", "complete"]);+ expect(question).toBe("Which completed scan would you like to publish?");+ expect(choices).toHaveLength(2);+ expect(choices[0]!.label).toContain("first-repository");+ expect(choices[0]!.label).toContain("first-scan");+ expect(choices[0]!.label).toContain("2026-08-15T01:05:00Z");+ expect(choices[0]!.label).toContain("1 finding");+ expect(choices[1]!.label).toContain("second-repository");+ expect(choices[1]!.label).toContain("second-scan");+ expect(choices[1]!.label).toContain("2026-08-15T02:15:00Z");+ expect(choices[1]!.label).toContain("3 findings");+ expect(choices[1]!.label).toContain("COMPLETE");+ expect(publishedDirectory).toBe(selectedDirectory);+ expect(JSON.parse(stdout.text())).toEqual(publicationResult());+ expect(stderr.text()).toBe("");+ });++ test("omits deleted, replaced, and linked scan directories without changing valid scan order", async () => {+ const directory = await publicationDirectory();+ const firstDirectory = join(directory, "first-completed-scan");+ const selectedDirectory = join(directory, "selected-completed-scan");+ const deletedDirectory = join(directory, "deleted-scan");+ const replacedDirectory = join(directory, "replaced-scan");+ const linkedDirectory = join(directory, "linked-scan");+ await Promise.all([+ mkdir(firstDirectory),+ mkdir(selectedDirectory),+ mkdir(deletedDirectory),+ mkdir(replacedDirectory),+ ]);+ await Promise.all([+ rm(deletedDirectory, { recursive: true }),+ rm(replacedDirectory, { recursive: true }),+ ]);+ await Promise.all([+ writeFile(replacedDirectory, "This completed scan was replaced."),+ symlink(firstDirectory, linkedDirectory, "junction"),+ ]);++ const saved = [+ { id: "first-scan", directory: firstDirectory },+ { id: "deleted-scan", directory: deletedDirectory },+ { id: "replaced-scan", directory: replacedDirectory },+ { id: "linked-scan", directory: linkedDirectory },+ { id: "selected-scan", directory: "selected-completed-scan" },+ ];+ const stdout = capture();+ const stderr = capture(true);+ let offered: readonly { label: string; value: string }[] = [];+ let publishedDirectory: string | undefined;+ const deps = dependencies({+ currentDirectory: directory,+ onWorkbench: () => ({+ scans: saved.map(({ id, directory: scanDirectory }) => ({+ scanId: id,+ scanDir: scanDirectory,+ targetSummary: id,+ completedAt: "2030-01-01T00:00:00Z",+ findingCount: 1,+ progress: { status: "complete" },+ })),+ }),+ });+ deps.publishPrompt = {+ isInteractive: () => true,+ select: async <Value extends string>(+ _message: string,+ choices: readonly { label: string; value: Value }[],+ ): Promise<Value> => {+ offered = choices;+ return choices[1]!.value;+ },+ };+ deps.publishScan = async (scanDirectory) => {+ publishedDirectory = scanDirectory;+ return publicationResult();+ };++ expect(+ await main(+ ["publish", "scan", ...DESTINATION_OPTIONS, "--json"],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(offered.map(({ value }) => value)).toEqual([+ firstDirectory,+ "selected-completed-scan",+ ]);+ expect(offered.map(({ label }) => label)).toEqual([+ expect.stringContaining("first-scan"),+ expect.stringContaining("selected-scan"),+ ]);+ expect(publishedDirectory).toBe(selectedDirectory);+ expect(JSON.parse(stdout.text())).toEqual(publicationResult());+ expect(stderr.text()).toBe("");+ });++ test("requires an interactive terminal when no scan directory is supplied", async () => {+ const stdout = capture();+ const stderr = capture();+ let listed = false;+ let published = false;+ const deps = dependencies({+ onWorkbench: () => {+ listed = true;+ return { scans: [] };+ },+ });+ deps.publishPrompt = {+ isInteractive: () => false,+ select: async <Value extends string>(+ _message: string,+ options: readonly { label: string; value: Value }[],+ ): Promise<Value> => options[0]!.value,+ };+ deps.publishScan = async () => {+ published = true;+ return publicationResult();+ };++ expect(+ await main(+ ["publish", "scan", ...DESTINATION_OPTIONS],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(stderr.text()).toContain(+ "Interactive scan selection requires a terminal.",+ );+ expect(stderr.text()).toContain("codex-security publish scan");+ expect(stdout.text()).toBe("");+ expect(listed).toBe(false);+ expect(published).toBe(false);+ });++ test("fails clearly when no completed scans are available", async () => {+ const stdout = capture();+ const stderr = capture(true);+ let prompted = false;+ let published = false;+ const deps = dependencies({ onWorkbench: () => ({ scans: [] }) });+ deps.publishPrompt = {+ isInteractive: () => true,+ select: async <Value extends string>(+ _message: string,+ options: readonly { label: string; value: Value }[],+ ): Promise<Value> => {+ prompted = true;+ return options[0]!.value;+ },+ };+ deps.publishScan = async () => {+ published = true;+ return publicationResult();+ };++ expect(+ await main(+ ["publish", "scan", ...DESTINATION_OPTIONS],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(stderr.text()).toContain(+ "No completed Codex Security scans are available to publish.",+ );+ expect(stdout.text()).toBe("");+ expect(prompted).toBe(false);+ expect(published).toBe(false);+ });++ test("does not offer completed history when every scan directory is unavailable", async () => {+ const directory = await publicationDirectory();+ const replacedDirectory = join(directory, "replaced-scan");+ const validDirectory = join(directory, "unlisted-valid-scan");+ const linkedDirectory = join(directory, "linked-scan");+ await Promise.all([+ mkdir(validDirectory),+ writeFile(replacedDirectory, "This completed scan was replaced."),+ ]);+ await symlink(validDirectory, linkedDirectory, "junction");++ const stdout = capture();+ const stderr = capture(true);+ let prompted = false;+ let published = false;+ const deps = dependencies({+ onWorkbench: () => ({+ scans: [+ join(directory, "deleted-scan"),+ replacedDirectory,+ linkedDirectory,+ ].map((scanDirectory, index) => ({+ scanId: `unavailable-scan-${index}`,+ scanDir: scanDirectory,+ progress: { status: "complete" },+ })),+ }),+ });+ deps.publishPrompt = {+ isInteractive: () => true,+ select: async <Value extends string>(+ _message: string,+ choices: readonly { value: Value }[],+ ): Promise<Value> => {+ prompted = true;+ return choices[0]!.value;+ },+ };+ deps.publishScan = async () => {+ published = true;+ return publicationResult();+ };++ expect(+ await main(+ ["publish", "scan", ...DESTINATION_OPTIONS, "--json"],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(stderr.text()).toContain(+ "No completed Codex Security scans are available to publish.",+ );+ expect(stdout.text()).toBe("");+ expect(prompted).toBe(false);+ expect(published).toBe(false);+ });++ test("requires an explicit supported destination and team with valid optional flags", async () => {+ const cases: ReadonlyArray<[readonly string[], string]> = [+ [["publish", "scan", "completed-scan"], "to"],+ [["publish", "scan", "completed-scan", "--to", "azure"], "linear"],+ [+ ["publish", "scan", "completed-scan", "--to", "linear"],+ "--linear-team or CODEX_SECURITY_LINEAR_TEAM is required.",+ ],+ [+ ["publish", "scan", "completed-scan", "--to"],+ "Missing value for flag: --to",+ ],+ [+ [+ "publish",+ "scan",+ "completed-scan",+ "--to",+ "linear",+ "--linear-team",+ ],+ "Missing value for flag: --linear-team",+ ],+ [+ [+ "publish",+ "scan",+ "completed-scan",+ "--to",+ "linear",+ "--linear-team",+ "team-id",+ "--project",+ ],+ "Missing value for flag: --project",+ ],+ [+ [+ "publish",+ "scan",+ "completed-scan",+ "--to",+ "linear",+ "--linear-team",+ "team-id",+ "--project",+ " ",+ ],+ "--project must not be empty.",+ ],+ ];++ for (const [argv, expected] of cases) {+ const stdout = capture();+ const stderr = capture();+ let published = false;+ const deps = dependencies();+ deps.publishScan = async () => {+ published = true;+ return publicationResult();+ };++ expect(await main(argv, stdout.stream, stderr.stream, deps)).toBe(2);+ expect(stderr.text()).toContain(expected);+ expect(stdout.text()).toBe("");+ expect(published).toBe(false);+ }+ });++ test("uses environment destination settings and gives flags precedence", async () => {+ for (const scenario of [+ {+ argv: ["publish", "scan", "completed-scan", "--to", "linear"],+ expectedTeam: "team-from-environment",+ expectedProject: "project-from-environment",+ },+ {+ argv: ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS],+ expectedTeam: "team-from-flags",+ expectedProject: "project-from-flags",+ },+ ]) {+ const deps = dependencies({+ environment: {+ CODEX_SECURITY_LINEAR_TEAM: " team-from-environment ",+ CODEX_SECURITY_LINEAR_PROJECT: " project-from-environment ",+ },+ });+ let destination:+ | { teamId: string; projectId: string | undefined }+ | undefined;+ deps.publishScan = async (_scanDirectory, options) => {+ destination = {+ teamId: options.teamId,+ projectId: options.projectId,+ };+ return publicationResult();+ };++ expect(+ await main(scenario.argv, capture().stream, capture().stream, deps),+ ).toBe(0);+ expect(destination).toEqual({+ teamId: scenario.expectedTeam,+ projectId: scenario.expectedProject,+ });+ }+ });++ test("passes dry-run mode through and preserves machine-readable output", async () => {+ const stdout = capture();+ const stderr = capture();+ let dryRun: boolean | undefined;+ const signals = new FakeSignals();+ const deps = dependencies({ signals });+ deps.publishScan = async (_scanDirectory, options) => {+ dryRun = options.dryRun;+ return { ...publicationResult(), dryRun: true, issues: [] };+ };++ expect(+ await main(+ [+ "publish",+ "scan",+ "completed-scan",+ ...DESTINATION_OPTIONS,+ "--dry-run",+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(dryRun).toBe(true);+ expect(JSON.parse(stdout.text())).toMatchObject({+ scanId: "scan-123",+ uploadId: "scan-123",+ dryRun: true,+ issues: [],+ });+ expect(stderr.text()).toBe("");+ expect(signals.listeners.size).toBe(0);+ });++ test("surfaces receipt warnings without changing published issues or JSON output", async () => {+ const warning =+ "Could not save the publication receipt: [redacted]. Linear issues were already created; do not retry publication.";+ const result = { ...publicationResult(), warnings: [warning] };+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies();+ deps.publishScan = async () => result;++ expect(+ await main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS, "--json"],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(JSON.parse(stdout.text())).toEqual(result);+ expect(stderr.text()).toBe(`codex-security: ${warning}\n`);+ });++ test("surfaces receipt warnings for default human-readable publication output", async () => {+ const warning =+ "Could not save the publication receipt: Disk is unavailable. Linear issues were already created; do not retry publication.";+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies();+ deps.publishScan = async () => ({+ ...publicationResult(),+ warnings: [warning],+ });++ expect(+ await main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(stdout.text()).toContain("SEC-123");+ expect(stderr.text()).toBe(`codex-security: ${warning}\n`);+ });++ test("sanitizes receipt warnings while preserving partial publication results", async () => {+ const warnings = [+ "Receipt storage failed.\n\u001B[31mDo not retry publication.",+ "Receipt storage failed: sk-proj-SYNTHETIC_RECEIPT_SECRET",+ ];+ const result = {+ ...publicationResult([+ { findingId: "finding-2", error: "Linear issue creation failed." },+ ]),+ warnings,+ };+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies();+ deps.publishScan = async () => result;++ expect(+ await main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS, "--json"],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(JSON.parse(stdout.text())).toEqual(result);+ expect(stderr.text()).toBe(+ "codex-security: Receipt storage failed. [31mDo not retry publication.\n" ++ "codex-security: [redacted]\n",+ );+ expect(stderr.text()).not.toContain("\u001B");+ expect(stderr.text()).not.toContain("SYNTHETIC_RECEIPT_SECRET");+ });++ test("returns a nonzero exit code while preserving partial publication results", async () => {+ const stdout = capture();+ const stderr = capture();+ const failed = [+ { findingId: "finding-2", error: "Linear issue creation failed." },+ ];+ const deps = dependencies();+ deps.publishScan = async () => publicationResult(failed);++ expect(+ await main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS, "--json"],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(JSON.parse(stdout.text())).toEqual(publicationResult(failed));+ expect(stderr.text()).toBe("");+ });++ test("reports publisher failures without claiming a successful upload", async () => {+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies();+ deps.publishScan = async () => {+ throw new Error("Linear is not connected to your Codex account.");+ };++ expect(+ await main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(stderr.text()).toContain(+ "Linear is not connected to your Codex account.",+ );+ expect(stdout.text()).toBe("");+ });+});diff --git a/sdk/typescript/tests-ts/contract.test.ts b/sdk/typescript/tests-ts/contract.test.tsindex a47dcd0b6..4fdfcd05f 100644--- a/sdk/typescript/tests-ts/contract.test.ts+++ b/sdk/typescript/tests-ts/contract.test.ts@@ -1,18 +1,22 @@import { createHash } from "node:crypto";+import type { Stats } from "node:fs";import {chmod,cp,+ lstat,mkdir,mkdtemp,readFile,rm,symlink,+ type FileHandle,writeFile,} from "node:fs/promises";import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { afterEach, describe, expect, test } from "bun:test";import { ContractValidationError, loadContract } from "../src/index.js";+import { sameCheckedFileDevice } from "../src/contract.js";import type { NormalizedTarget, ScanExpectation } from "../src/index.js";import { PLUGIN_ROOT } from "./plugin-root.js";@@ -101,6 +105,110 @@ function expectation(}describe("canonical scan contract", () => {+ test("compares exact Windows volume serials without rounding file identity", async () => {+ const scanDir = await copyExample();+ const path = join(scanDir, "scan-manifest.json");+ const metadata = await lstat(path);+ const identity = await lstat(path, { bigint: true });+ const volume = BigInt.asUintN(32, identity.dev);+ const highDevice = (1n << 60n) | volume;+ expect(highDevice).toBeGreaterThan(BigInt(Number.MAX_SAFE_INTEGER));++ let device = highDevice;+ let inode = identity.ino;+ let regular = true;+ let inspected = 0;+ let referenceDevice = highDevice;+ let referenceInode = identity.ino;+ let referenceRegular = true;+ let referenceClosed = 0;+ const file = {+ stat: async () => {+ inspected += 1;+ return {+ dev: device,+ ino: inode,+ isFile: () => regular,+ };+ },+ } as unknown as FileHandle;+ const reference = {+ stat: async () => ({+ dev: referenceDevice,+ ino: referenceInode,+ isFile: () => referenceRegular,+ }),+ close: async () => {+ referenceClosed += 1;+ },+ } as unknown as FileHandle;+ const openReference = async () => reference;+ const checked = { path, metadata, parents: [] };+ const opened = { dev: Number(highDevice), ino: metadata.ino } as Stats;++ await expect(+ sameCheckedFileDevice(file, checked, opened, "win32", openReference),+ ).resolves.toBe(true);+ expect(referenceClosed).toBe(1);++ const inconsistentNumberInode = {+ dev: metadata.dev,+ ino: metadata.ino + 1024,+ } as Stats;+ await expect(+ sameCheckedFileDevice(+ file,+ checked,+ inconsistentNumberInode,+ "win32",+ openReference,+ ),+ ).resolves.toBe(false);++ device = highDevice ^ 1n;+ await expect(+ sameCheckedFileDevice(file, checked, opened, "win32", openReference),+ ).resolves.toBe(false);+ expect(referenceClosed).toBe(2);++ referenceDevice = device;+ await expect(+ sameCheckedFileDevice(file, checked, opened, "win32", openReference),+ ).resolves.toBe(true);+ expect(referenceClosed).toBe(3);++ device = highDevice;+ referenceDevice = highDevice;+ inode = identity.ino + 1n;+ await expect(+ sameCheckedFileDevice(file, checked, opened, "win32", openReference),+ ).resolves.toBe(false);++ inode = identity.ino;+ regular = false;+ await expect(+ sameCheckedFileDevice(file, checked, opened, "win32", openReference),+ ).resolves.toBe(false);++ regular = true;+ referenceInode = identity.ino + 1n;+ await expect(+ sameCheckedFileDevice(file, checked, opened, "win32", openReference),+ ).resolves.toBe(false);++ referenceInode = identity.ino;+ referenceRegular = false;+ await expect(+ sameCheckedFileDevice(file, checked, opened, "win32", openReference),+ ).resolves.toBe(false);++ const windowsInspections = inspected;+ await expect(+ sameCheckedFileDevice(file, checked, opened, "linux", openReference),+ ).resolves.toBe(false);+ expect(inspected).toBe(windowsInspections);+ });+test("loads the unchanged plugin example with typed canonical names", async () => {const scanDir = await copyExample();const contract = await loadContract(scanDir, { pluginRoot: PLUGIN_ROOT });diff --git a/sdk/typescript/tests-ts/publication-integration.test.ts b/sdk/typescript/tests-ts/publication-integration.test.tsnew file mode 100644index 000000000..1b43b675b--- /dev/null+++ b/sdk/typescript/tests-ts/publication-integration.test.ts@@ -0,0 +1,723 @@+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import {+ appendFile,+ chmod,+ cp,+ mkdir,+ mkdtemp,+ readFile,+ readdir,+ realpath,+ rm,+ writeFile,+} from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { afterEach, describe, expect, test } from "bun:test";+import { main } from "../src/cli.js";+import type {+ CoverageDocument,+ Finding,+ FindingsDocument,+ ScanManifest,+} from "../src/models.js";+import {+ publishScanInternal,+ type PublishScanProgress,+ type PublishScanResult,+} from "../src/publish.js";+import { runWorkbench } from "../src/runtime.js";+import { capture, dependencies, FakeSignals } from "./cli-fixtures.js";+import { PLUGIN_ROOT } from "./plugin-root.js";++const SCAN_ID = "11111111-1111-4111-8111-111111111111";+const WORKSPACE_ID = "22222222-2222-4222-8222-222222222222";+const OPTIONS = {+ destination: "linear",+ teamId: "team-example",+ projectId: "project-example",+} as const;+const temporaryDirectories: string[] = [];++interface PublicationFixture {+ python: string;+ scanDirectory: string;+ stateDirectory: string;+ environment: NodeJS.ProcessEnv;+ findings: Finding[];+}++interface PromptFinding {+ findingId: string;+ occurrenceId: string;+ arguments: Record<string, unknown>;+}++interface PublicationPrompt {+ scanId: string;+ destination: { type: "linear"; teamId: string; projectId?: string };+ handoffFile: string;+ publicationFile: string;+ batches: Array<Array<Omit<PromptFinding, "arguments">>>;+}++interface StoredPublication {+ scan_id: string;+ finding_id: string;+ occurrence_id: string;+ destination_type: string;+ team_id: string;+ project_id: string | null;+ external_id: string;+ external_url: string;+}++afterEach(async () => {+ await Promise.all(+ temporaryDirectories+ .splice(0)+ .map((directory) => rm(directory, { recursive: true, force: true })),+ );+});++function sha256(value: string | Uint8Array): string {+ return createHash("sha256").update(value).digest("hex");+}++function setFindingIdentity(manifest: ScanManifest, finding: Finding): void {+ const fingerprint = `codex-security/v1:sha256:${sha256(+ [+ "codex-security/v1",+ manifest.scan.target.targetId,+ finding.ruleId,+ finding.identity.anchor,+ finding.identity.instance ?? "",+ ].join("\0"),+ )}`;+ finding.fingerprints = {+ algorithm: "codex-security/v1",+ primary: fingerprint,+ };+ finding.findingId = `csf_${sha256(fingerprint).slice(0, 24)}`;+ finding.occurrenceId = `occ_${sha256(+ [manifest.scan.id, fingerprint].join("\0"),+ ).slice(0, 24)}`;+}++async function fixture(count: number): Promise<PublicationFixture> {+ const root = await realpath(+ await mkdtemp(join(tmpdir(), "codex-security-publication-integration-")),+ );+ temporaryDirectories.push(root);+ const scanDirectory = join(root, "scan");+ const stateDirectory = join(root, "state");+ const repository = join(root, "repository");+ await cp(join(PLUGIN_ROOT, "examples", "completed-scan"), scanDirectory, {+ recursive: true,+ });+ await mkdir(stateDirectory, { mode: 0o700 });+ await mkdir(repository, { mode: 0o700 });+ if (process.platform !== "win32") await chmod(scanDirectory, 0o700);++ const manifestPath = join(scanDirectory, "scan-manifest.json");+ const findingsPath = join(scanDirectory, "findings.json");+ const coveragePath = join(scanDirectory, "coverage.json");+ const manifest = JSON.parse(+ await readFile(manifestPath, "utf8"),+ ) as ScanManifest;+ const findings = JSON.parse(+ await readFile(findingsPath, "utf8"),+ ) as FindingsDocument;+ const coverage = JSON.parse(+ await readFile(coveragePath, "utf8"),+ ) as CoverageDocument;+ manifest.scan.id = SCAN_ID;+ findings.scanId = SCAN_ID;+ coverage.scanId = SCAN_ID;+ const example = findings.findings[0]!;+ findings.findings = Array.from({ length: count }, (_, index) => {+ const finding = structuredClone(example);+ finding.identity.anchor = `${example.identity.anchor}-${index + 1}`;+ finding.title = `Synthetic finding ${index + 1}`;+ setFindingIdentity(manifest, finding);+ return finding;+ });+ await writeFile(findingsPath, `${JSON.stringify(findings, null, 2)}\n`);+ await writeFile(coveragePath, `${JSON.stringify(coverage, null, 2)}\n`);+ for (const artifact of manifest.scan.artifacts) {+ artifact.sha256 = sha256(+ await readFile(join(scanDirectory, artifact.path)),+ );+ }+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);++ const python = Bun.which("python3") ?? Bun.which("python");+ expect(python).not.toBeNull();+ if (python === null) {+ throw new Error("A Python interpreter is required for publication tests.");+ }+ const environment: NodeJS.ProcessEnv = {+ PATH: process.env["PATH"],+ ...(process.env["SystemRoot"] === undefined+ ? {}+ : { SystemRoot: process.env["SystemRoot"] }),+ PYTHON: python,+ CODEX_SECURITY_STATE_DIR: stateDirectory,+ };+ await runWorkbench({ python, pluginRoot: PLUGIN_ROOT, environment }, [+ "database-info",+ ]);++ const seedFile = join(root, "seed.json");+ await writeFile(+ seedFile,+ JSON.stringify({+ scanId: SCAN_ID,+ workspaceId: WORKSPACE_ID,+ scanDirectory,+ repository,+ findings: findings.findings,+ }),+ );+ const seed = [+ "import json, sqlite3, sys",+ "from pathlib import Path",+ "payload = json.loads(Path(sys.argv[2]).read_text())",+ "connection = sqlite3.connect(sys.argv[1])",+ "connection.execute('PRAGMA foreign_keys = ON')",+ "timestamp = '2026-08-15T00:00:00Z'",+ "connection.execute('INSERT INTO workspaces (id, created_at, updated_at) VALUES (?, ?, ?)', (payload['workspaceId'], timestamp, timestamp))",+ "connection.execute('INSERT INTO scans (id, workspace_id, target_path, target_revision, scope, mode, scan_dir, status, phase, started_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (payload['scanId'], payload['workspaceId'], payload['repository'], 'deadbeef', '.', 'standard', payload['scanDirectory'], 'complete', 'reporting', timestamp, timestamp, timestamp))",+ "for finding in payload['findings']:",+ " connection.execute('INSERT INTO findings (id, fingerprint, rule_id, identity_anchor, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)', (finding['findingId'], finding['fingerprints']['primary'], finding['ruleId'], finding['identity']['anchor'], timestamp, timestamp))",+ " connection.execute('INSERT INTO finding_occurrences (id, finding_id, scan_id, title, summary, severity, confidence, remediation, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', (finding['occurrenceId'], finding['findingId'], payload['scanId'], finding['title'], finding['summary'], finding['severity']['level'], finding['confidence']['level'], finding['remediation'], timestamp))",+ "connection.commit()",+ "connection.close()",+ ].join("\n");+ execFileSync(+ python,+ [+ "-I",+ "-B",+ "-c",+ seed,+ join(stateDirectory, "workbench.sqlite3"),+ seedFile,+ ],+ { encoding: "utf8", env: environment },+ );++ return {+ python,+ scanDirectory,+ stateDirectory,+ environment,+ findings: findings.findings,+ };+}++async function publicationPayload(+ value: string,+): Promise<+ Omit<PublicationPrompt, "batches"> & { batches: PromptFinding[][] }+> {+ const json = value+ .split("BEGIN UNTRUSTED PUBLICATION DATA\n")[1]!+ .split("\nEND UNTRUSTED PUBLICATION DATA")[0]!;+ const prompt = JSON.parse(json) as PublicationPrompt;+ const publication = JSON.parse(+ await readFile(prompt.publicationFile, "utf8"),+ ) as { batches: PromptFinding[][] };+ return { ...prompt, batches: publication.batches };+}++async function artifactDigests(+ scanDirectory: string,+): Promise<Record<string, string>> {+ const names = (await readdir(scanDirectory)).sort();+ return Object.fromEntries(+ await Promise.all(+ names.map(async (name) => [+ name,+ sha256(await readFile(join(scanDirectory, name))),+ ]),+ ),+ );+}++function storedPublications(fixture: PublicationFixture): StoredPublication[] {+ const script = [+ "import json, sqlite3, sys",+ "connection = sqlite3.connect(sys.argv[1])",+ "connection.row_factory = sqlite3.Row",+ "rows = connection.execute('SELECT scan_id, finding_id, occurrence_id, destination_type, team_id, project_id, external_id, external_url FROM finding_publications ORDER BY id').fetchall()",+ "print(json.dumps([dict(row) for row in rows]))",+ ].join("\n");+ return JSON.parse(+ execFileSync(+ fixture.python,+ [+ "-I",+ "-B",+ "-c",+ script,+ join(fixture.stateDirectory, "workbench.sqlite3"),+ ],+ { encoding: "utf8", env: fixture.environment },+ ),+ ) as StoredPublication[];+}++function receiptPath(fixture: PublicationFixture): string {+ return join(+ fixture.stateDirectory,+ "publications",+ "linear",+ `${sha256(SCAN_ID)}.json`,+ );+}++describe("database-backed Linear publication integration", () => {+ test("publishes 23 sealed findings through a durable handoff without Codex JSON", async () => {+ const completed = await fixture(23);+ const sealed = await artifactDigests(completed.scanDirectory);+ const stdout = capture();+ const stderr = capture();+ const progress: PublishScanProgress[] = [];+ const cli = dependencies({ environment: completed.environment });+ let sdkResult: PublishScanResult | undefined;+ let handoffFile = "";+ cli.publishScan = async (directory, options) => {+ sdkResult = await publishScanInternal(+ directory,+ {+ ...options,+ onProgress: (event) => {+ progress.push(event);+ options.onProgress?.(event);+ },+ },+ {+ environment: completed.environment,+ resolveCodex: () => ({ command: "synthetic-codex" }),+ runCodex: async (_command, args, prompt, _environment, onEvent) => {+ const payload = await publicationPayload(prompt);+ handoffFile = payload.handoffFile;+ expect(args[args.indexOf("--sandbox") + 1]).toBe("workspace-write");+ expect(args[args.indexOf("--cd") + 1]).toBe(dirname(handoffFile));+ expect(handoffFile.startsWith(completed.scanDirectory)).toBe(false);+ expect(prompt).toContain("concurrently with Promise.allSettled");+ expect(payload.scanId).toBe(SCAN_ID);+ expect(payload.destination).toEqual({+ type: "linear",+ teamId: OPTIONS.teamId,+ projectId: OPTIONS.projectId,+ });+ expect(payload.batches.map((batch) => batch.length)).toEqual([+ 20, 3,+ ]);++ const indices = new Map(+ completed.findings.map(({ findingId }, index) => [+ findingId,+ index,+ ]),+ );+ for (const batch of payload.batches) {+ const settled = await Promise.all(+ batch.map(async (finding) => {+ const index = indices.get(finding.findingId)!;+ expect(finding.occurrenceId).toBe(+ completed.findings[index]!.occurrenceId,+ );+ expect(finding.arguments).toMatchObject({+ team: OPTIONS.teamId,+ project: OPTIONS.projectId,+ title: `[Codex Security][HIGH] Synthetic finding ${index + 1}`,+ priority: 2,+ });+ expect(finding.arguments["description"]).toContain(+ finding.findingId,+ );+ const identifier = `SEC-${700 + index}`;+ return {+ scanId: payload.scanId,+ findingId: finding.findingId,+ occurrenceId: finding.occurrenceId,+ issueIdentifier: identifier,+ url: `https://linear.app/example/issue/${identifier}`,+ arguments: finding.arguments,+ };+ }),+ );+ await appendFile(+ payload.handoffFile,+ `${settled+ .reverse()+ .map((record) => JSON.stringify(record))+ .join("\n")}\n`,+ );+ }+ onEvent?.({+ type: "item.completed",+ item: {+ id: "agent-message-1",+ type: "agent_message",+ text: "Created zero issues: {not valid JSON; imaginary SEC-999999}",+ },+ });+ return { exitCode: 0, stdout: "not valid JSON\n", stderr: "" };+ },+ },+ );+ return sdkResult;+ };++ expect(+ await main(+ [+ "publish",+ "scan",+ completed.scanDirectory,+ "--to",+ "linear",+ "--linear-team",+ OPTIONS.teamId,+ "--project",+ OPTIONS.projectId,+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ cli,+ ),+ ).toBe(0);++ expect(sdkResult?.counts).toEqual({+ findings: 23,+ created: 23,+ failed: 0,+ });+ expect(+ sdkResult?.created.map(({ issueIdentifier }) => issueIdentifier),+ ).toEqual(Array.from({ length: 23 }, (_, index) => `SEC-${700 + index}`));+ expect(JSON.parse(stdout.text())).toEqual(sdkResult);+ expect(stdout.text()).not.toContain("not valid JSON");+ expect(stdout.text()).not.toContain("SEC-999999");+ expect(JSON.parse(await readFile(receiptPath(completed), "utf8"))).toEqual(+ sdkResult,+ );++ const persisted = storedPublications(completed);+ expect(persisted).toHaveLength(23);+ expect(persisted).toEqual(+ completed.findings.map((finding, index) => ({+ scan_id: SCAN_ID,+ finding_id: finding.findingId,+ occurrence_id: finding.occurrenceId,+ destination_type: "linear",+ team_id: OPTIONS.teamId,+ project_id: OPTIONS.projectId,+ external_id: `SEC-${700 + index}`,+ external_url: `https://linear.app/example/issue/SEC-${700 + index}`,+ })),+ );+ expect(+ progress.filter(({ type }) => type === "issue_completed"),+ ).toHaveLength(23);+ expect(progress.at(-1)).toEqual({+ type: "completed",+ created: 23,+ failed: 0,+ total: 23,+ });+ expect(await artifactDigests(completed.scanDirectory)).toEqual(sealed);+ expect(+ await readFile(handoffFile).then(+ () => true,+ () => false,+ ),+ ).toBe(false);+ });++ test("retains team-only database-backed partial successes when a later batch fails", async () => {+ const completed = await fixture(22);+ const sealed = await artifactDigests(completed.scanDirectory);+ const stdout = capture();+ const stderr = capture();+ const cli = dependencies({ environment: completed.environment });+ cli.publishScan = async (directory, options) =>+ await publishScanInternal(directory, options, {+ environment: completed.environment,+ resolveCodex: () => ({ command: "synthetic-codex" }),+ runCodex: async (_command, _args, prompt) => {+ const payload = await publicationPayload(prompt);+ expect(payload.destination).toEqual({+ type: "linear",+ teamId: OPTIONS.teamId,+ });+ expect(payload.batches.map((batch) => batch.length)).toEqual([20, 2]);+ for (const [batchIndex, batch] of payload.batches.entries()) {+ const records = batch.map((finding, index) => {+ expect(finding.arguments).not.toHaveProperty("project");+ return {+ scanId: payload.scanId,+ findingId: finding.findingId,+ occurrenceId: finding.occurrenceId,+ arguments: finding.arguments,+ ...(batchIndex === 1 && index === 0+ ? { error: "The second batch issue failed." }+ : {+ issueIdentifier: `SEC-${900 + batchIndex * 20 + index}`,+ }),+ };+ });+ await appendFile(+ payload.handoffFile,+ `${records.map((record) => JSON.stringify(record)).join("\n")}\n`,+ );+ }+ return { exitCode: 0, stdout: "", stderr: "" };+ },+ });++ expect(+ await main(+ [+ "publish",+ "scan",+ completed.scanDirectory,+ "--to",+ "linear",+ "--linear-team",+ OPTIONS.teamId,+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ cli,+ ),+ ).toBe(2);++ const result = JSON.parse(stdout.text()) as PublishScanResult;+ expect(result.destination).toEqual({+ type: "linear",+ teamId: OPTIONS.teamId,+ });+ expect(result.counts).toEqual({ findings: 22, created: 21, failed: 1 });+ expect(result.failed).toEqual([+ {+ findingId: completed.findings[20]!.findingId,+ error: "The second batch issue failed.",+ },+ ]);+ const persisted = storedPublications(completed);+ expect(persisted).toHaveLength(21);+ expect(persisted.every(({ project_id }) => project_id === null)).toBe(true);+ expect(+ persisted.some(+ ({ finding_id }) => finding_id === result.failed[0]!.findingId,+ ),+ ).toBe(false);+ expect(persisted.map(({ external_id }) => external_id)).toEqual(+ result.created.map(({ issueIdentifier }) => issueIdentifier),+ );+ expect(JSON.parse(await readFile(receiptPath(completed), "utf8"))).toEqual(+ result,+ );+ expect(await artifactDigests(completed.scanDirectory)).toEqual(sealed);+ });++ test("keeps SQLite-backed Linear issues successful when their optional receipt cannot be saved", async () => {+ const completed = await fixture(2);+ const sealed = await artifactDigests(completed.scanDirectory);+ const stdout = capture();+ const stderr = capture();+ const cli = dependencies({ environment: completed.environment });+ let publicationAttempts = 0;++ cli.publishScan = async (directory, options) =>+ await publishScanInternal(directory, options, {+ environment: completed.environment,+ resolveCodex: () => ({ command: "synthetic-codex" }),+ runCodex: async (_command, _args, prompt) => {+ publicationAttempts += 1;+ const payload = await publicationPayload(prompt);+ await appendFile(+ payload.handoffFile,+ `${payload.batches[0]!.map((finding, index) =>+ JSON.stringify({+ scanId: payload.scanId,+ findingId: finding.findingId,+ occurrenceId: finding.occurrenceId,+ arguments: finding.arguments,+ issueIdentifier: `SEC-${801 + index}`,+ }),+ ).join("\n")}\n`,+ );+ return { exitCode: 0, stdout: "", stderr: "" };+ },+ writeReceipt: async () => {+ throw new Error(+ "Receipt storage unavailable: sk-proj-SYNTHETIC_RECEIPT_SECRET",+ );+ },+ });++ expect(+ await main(+ [+ "publish",+ "scan",+ completed.scanDirectory,+ "--to",+ "linear",+ "--linear-team",+ OPTIONS.teamId,+ "--project",+ OPTIONS.projectId,+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ cli,+ ),+ ).toBe(0);++ const result = JSON.parse(stdout.text()) as PublishScanResult & {+ warnings?: string[];+ };+ expect(result.counts).toEqual({ findings: 2, created: 2, failed: 0 });+ expect(+ result.created.map(({ issueIdentifier }) => issueIdentifier),+ ).toEqual(["SEC-801", "SEC-802"]);+ expect(result.warnings).toEqual([+ "Could not save the publication receipt: [redacted]. Linear issues were already created; do not retry publication.",+ ]);+ expect(stderr.text()).toContain(result.warnings![0]!);+ expect(stdout.text()).not.toContain("SYNTHETIC_RECEIPT_SECRET");+ expect(stderr.text()).not.toContain("SYNTHETIC_RECEIPT_SECRET");+ expect(publicationAttempts).toBe(1);+ expect(+ storedPublications(completed).map(({ external_id }) => external_id),+ ).toEqual(["SEC-801", "SEC-802"]);+ expect(+ await readFile(receiptPath(completed), "utf8").catch(() => null),+ ).toBe(null);+ expect(await artifactDigests(completed.scanDirectory)).toEqual(sealed);+ });++ test("recovers verified SQLite publications before an interrupted CLI exits", async () => {+ const completed = await fixture(3);+ const sealed = await artifactDigests(completed.scanDirectory);+ const stdout = capture();+ const stderr = capture();+ const signals = new FakeSignals();+ const cli = dependencies({ environment: completed.environment, signals });+ let handoffFile = "";++ cli.publishScan = async (directory, options) =>+ await publishScanInternal(directory, options, {+ environment: completed.environment,+ resolveCodex: () => ({ command: "synthetic-codex" }),+ runCodex: async (+ _command,+ _args,+ prompt,+ _environment,+ _onEvent,+ signal,+ ) => {+ const payload = await publicationPayload(prompt);+ const recorded = payload.batches[0]![0]!;+ const salvaged = payload.batches[0]![1]!;+ handoffFile = payload.handoffFile;+ await appendFile(+ handoffFile,+ `${JSON.stringify({+ scanId: payload.scanId,+ findingId: recorded.findingId,+ occurrenceId: recorded.occurrenceId,+ arguments: recorded.arguments,+ issueIdentifier: "SEC-701",+ url: "https://linear.app/example/issue/SEC-701",+ })}\n`,+ );++ signals.emit("SIGINT");+ expect(signal?.aborted).toBe(true);+ expect(signal?.reason).toBe("SIGINT");++ return {+ exitCode: 1,+ stdout: JSON.stringify({+ type: "item.completed",+ item: {+ id: "tool-salvaged-publication",+ type: "mcp_tool_call",+ server: "codex_apps",+ tool: "linear.save_issue",+ arguments: salvaged.arguments,+ status: "completed",+ result: {+ content: [],+ structured_content: {+ identifier: "SEC-702",+ url: "https://linear.app/example/issue/SEC-702",+ },+ },+ },+ }),+ stderr: "Publication interrupted.",+ };+ },+ });++ expect(+ await main(+ [+ "publish",+ "scan",+ completed.scanDirectory,+ "--to",+ "linear",+ "--linear-team",+ OPTIONS.teamId,+ "--project",+ OPTIONS.projectId,+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ cli,+ ),+ ).toBe(130);++ expect(stdout.text()).toBe("");+ expect(stderr.text()).toContain("Publication canceled by Ctrl-C.");+ expect(stderr.text()).toContain(handoffFile);+ expect(stderr.text()).toContain("avoid creating duplicate issues");+ expect(+ storedPublications(completed).map(({ external_id }) => external_id),+ ).toEqual(["SEC-701", "SEC-702"]);++ const receipt = JSON.parse(+ await readFile(receiptPath(completed), "utf8"),+ ) as PublishScanResult;+ expect(receipt.counts).toEqual({ findings: 3, created: 2, failed: 1 });+ expect(+ receipt.created.map(({ issueIdentifier }) => issueIdentifier),+ ).toEqual(["SEC-701", "SEC-702"]);+ expect(+ (await readFile(handoffFile, "utf8"))+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line) as { issueIdentifier: string })+ .map(({ issueIdentifier }) => issueIdentifier),+ ).toEqual(["SEC-701", "SEC-702"]);+ expect(signals.listeners.get("SIGINT")?.size).toBe(0);+ expect(signals.listeners.get("SIGTERM")?.size).toBe(0);+ expect(await artifactDigests(completed.scanDirectory)).toEqual(sealed);+ });+});