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): add interactive scan publication presentation (#455)
Kyle Brown0fb8daf56102
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex abad08a5e..27044f633 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -561,7 +561,8 @@ Add `--project PROJECT_ID` to place the issues in a Linear project. Without aproject, issues are created directly in the selected team.To choose from all completed scans saved in your local scan history, omit the-scan directory:+scan directory. The selector highlights each repository and shows its finding+count, relative run time, and abbreviated scan ID:```bashnpx @openai/codex-security publish scan \@@ -573,6 +574,9 @@ Destination flags take precedence over `CODEX_SECURITY_LINEAR_TEAM` and theoptional `CODEX_SECURITY_LINEAR_PROJECT`. Use `--dry-run` to preview the issuetitles without creating them, or `--json` to return structured publicationresults.+Interactive publication shows a full-screen activity view with live Codex+output and issue-creation progress. Other terminals receive plain progress on+stderr, so `--json` output remains machine-readable.Publishing starts Codex with your existing Codex configuration and connectedLinear app. Sign in to Codex and connect Linear before publishing. The command@@ -603,6 +607,13 @@ import { publishScan } from "@openai/codex-security";const publication = await publishScan("/path/to/completed-scan", {destination: "linear",teamId: "TEAM_ID",+ onProgress: (progress) => {+ if (progress.type === "issue_completed") {+ console.error(+ `Processed ${progress.completed} of ${progress.total} findings.`,+ );+ }+ },});console.log(publication.scanId);diff --git a/sdk/typescript/src/bulk-scan-discovery.ts b/sdk/typescript/src/bulk-scan-discovery.tsindex 22d8ac2f7..197e4a424 100644--- a/sdk/typescript/src/bulk-scan-discovery.ts+++ b/sdk/typescript/src/bulk-scan-discovery.ts@@ -58,7 +58,8 @@ export interface BulkScanPrompt {input(question: string, defaultValue?: string): Promise<string>;select<Value extends string>(question: string,- options: readonly { label: string; value: Value }[],+ options: readonly { label: string; value: Value; short?: string }[],+ presentation?: { header?: string },): Promise<Value>;}@@ -79,6 +80,7 @@ export interface BulkScanWizardResult {interface PromptOutput {write(value: string): unknown;readonly isTTY?: boolean;+ readonly columns?: number;}export function createBulkScanDiscoveryDependencies(options: {@@ -324,15 +326,19 @@ async function validateWizardOutput(outputDir: string): Promise<void> {}function createTerminalPrompt(output: PromptOutput): BulkScanPrompt {- const context = () => ({- input: stdin,- output: new Writable({+ const context = () => {+ const stream = new Writable({write(chunk: Buffer, _encoding, callback) {output.write(chunk.toString("utf8"));callback();},- }),- });+ });+ Object.defineProperty(stream, "columns", {+ configurable: true,+ get: () => output.columns,+ });+ return { input: stdin, output: stream };+ };return {isInteractive: () => stdin.isTTY === true && output.isTTY === true,@@ -343,16 +349,30 @@ function createTerminalPrompt(output: PromptOutput): BulkScanPrompt {confirm({ message, default: defaultValue }, context()),input: (message, defaultValue) =>input({ message, default: defaultValue }, context()),- select: (message, options) =>+ select: (message, options, presentation) =>search({message,+ ...(presentation?.header === undefined+ ? {}+ : {+ theme: {+ style: {+ searchTerm: (term: string) =>+ `${term}\n ${presentation.header}`,+ },+ },+ }),source: (term) =>options.filter(({ label }) =>label.toLowerCase().includes(term?.toLowerCase() ?? ""),)- .map(({ label, value }) => ({ name: label, value })),+ .map(({ label, value, short }) => ({+ name: label,+ value,+ ...(short === undefined ? {} : { short }),+ })),},context(),),diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex f1b79d6ba..5c3f774ce 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -33,6 +33,7 @@ import { cwd } from "node:process";import { createInterface } from "node:readline";import { Readable, Writable as NodeWritable } from "node:stream";import { pipeline } from "node:stream/promises";+import { stripVTControlCharacters } from "node:util";import { fileURLToPath, pathToFileURL } from "node:url";import { Cli, z } from "incur";import { parse as parseToml } from "smol-toml";@@ -82,7 +83,11 @@ import {} from "./errors.js";import type { SeverityLevel } from "./models.js";import { runMultiscan } from "./multiscan.js";-import { publishScan } from "./publish.js";+import {+ publishScan,+ type PublishScanProgress,+ type PublishScanResult,+} from "./publish.js";import type { ScanResult } from "./result.js";import {bundledPluginRoot,@@ -101,6 +106,7 @@ import {type matchScanFindings,type ScanComparisonInput,} from "./scan-comparison.js";+import { scanActivitiesFromEvent } from "./scan-activity.js";import { readScanLogs } from "./scan-logs.js";import {renderScanHistory,@@ -134,6 +140,9 @@ const SCAN_HISTORY_OUTPUT_OPTION =const HIDE_CURSOR = "\u001B[?25l";const SHOW_CURSOR = "\u001B[?25h";const CHILD_TERMINATION_GRACE_MS = 1_000;+const PUBLICATION_GRAPHEME_SEGMENTER = new Intl.Segmenter(undefined, {+ granularity: "grapheme",+});type Writable = Pick<NodeJS.WriteStream, "write"> & {on?(event: "error", listener: (error: Error) => void): unknown;@@ -225,6 +234,278 @@ function optionValue(flag: string) {return z.string().min(1, `${flag} must not be empty.`);}+function publicationScanAge(timestamp: string, now: number): string {+ const completedAt = Date.parse(timestamp);+ if (!Number.isFinite(completedAt)) return "unknown";++ const elapsed = Math.max(0, now - completedAt);+ const units = [+ ["year", 365 * 24 * 60 * 60 * 1_000],+ ["month", 30 * 24 * 60 * 60 * 1_000],+ ["week", 7 * 24 * 60 * 60 * 1_000],+ ["day", 24 * 60 * 60 * 1_000],+ ["hour", 60 * 60 * 1_000],+ ["minute", 60 * 1_000],+ ["second", 1_000],+ ] as const;++ for (const [unit, duration] of units) {+ const count = Math.floor(elapsed / duration);+ if (count > 0) {+ return `${count} ${unit}${count === 1 ? "" : "s"} ago`;+ }+ }+ return "just now";+}++function publicationDisplayWidth(value: string): number {+ const segments = PUBLICATION_GRAPHEME_SEGMENTER.segment(+ stripVTControlCharacters(value),+ );+ let width = 0;++ for (const { segment } of segments) {+ if (/^[\p{Mark}\p{Cf}]+$/u.test(segment)) continue;+ width +=+ /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Emoji_Presentation}\p{Regional_Indicator}\u3000-\u303F\uFF01-\uFF60\uFFE0-\uFFE6\u20E3\uFE0F]/u.test(+ segment,+ )+ ? 2+ : 1;+ }++ return width;+}++function padPublicationColumn(value: string, width: number): string {+ return `${value}${" ".repeat(width - publicationDisplayWidth(value))}`;+}++function publicationIssueUrl(value: string | undefined): string | undefined {+ if (+ value === undefined ||+ value !== value.trim() ||+ value !== stripVTControlCharacters(value) ||+ /[\u0000-\u001F\u007F-\u009F\u2028\u2029]/u.test(value) ||+ safeErrorMessage(value) !== value+ ) {+ return undefined;+ }++ let url: URL;+ try {+ url = new URL(value);+ } catch {+ return undefined;+ }++ if (+ url.protocol !== "https:" ||+ (url.hostname !== "linear.app" && !url.hostname.endsWith(".linear.app")) ||+ url.username.length > 0 ||+ url.password.length > 0 ||+ url.search.length > 0 ||+ url.hash.length > 0+ ) {+ return undefined;+ }++ return value;+}++function renderPublicationSummary(+ result: PublishScanResult,+ color: boolean,+): string {+ const created = result.created.length;+ const failed = result.failed.length;+ const marker = failed === 0 ? "✓" : "!";+ const title =+ failed === 0+ ? "Linear publication complete"+ : "Linear publication completed with failures";+ const heading = color+ ? `\u001B[${failed === 0 ? "32" : "33"}m${marker}\u001B[39m \u001B[1m${title}\u001B[22m`+ : `${marker} ${title}`;+ const lines = [heading, ""];++ for (const issue of result.created.slice(0, 5)) {+ const identifier =+ stripVTControlCharacters(safeErrorMessage(issue.issueIdentifier))+ .replaceAll(/[\u0000-\u001F\u007F-\u009F\u2028\u2029]/gu, " ")+ .replace(/\s+/gu, " ")+ .trim() || "Unknown Linear issue";+ const url = publicationIssueUrl(issue.url);+ lines.push(` ${identifier}${url === undefined ? "" : ` ${url}`}`);+ }+ if (created > 5) lines.push(" ...");+ if (created > 0) lines.push("");++ lines.push(+ `${created} total issue${created === 1 ? "" : "s"} created`,+ `${failed} total issue${failed === 1 ? "" : "s"} failed`,+ );+ return `${lines.join("\n")}\n`;+}++class PublicationProgressPresenter {+ readonly #stream: Writable;+ readonly #dependencies: CliDependencies;+ readonly #repository: string;+ readonly #seenActivities = new Set<string>();+ #dashboard: ScanDashboard | null = null;++ public constructor(+ stream: Writable,+ dependencies: CliDependencies,+ repository: string,+ ) {+ this.#stream = stream;+ this.#dependencies = dependencies;+ this.#repository = repository;+ }++ public start(): void {+ if (+ this.#stream.isTTY !== true ||+ this.#dependencies.environment["CI"] !== undefined ||+ this.#dependencies.environment["TERM"] === "dumb"+ ) {+ return;+ }++ const dashboard = new ScanDashboard(this.#stream, {+ repository: this.#repository,+ presentation: "publication",+ clock: this.#dependencies,+ color: this.#dependencies.environment["NO_COLOR"] === undefined,+ sanitize: safeErrorMessage,+ });+ dashboard.setStage("Connecting to Linear");+ try {+ dashboard.start();+ this.#dashboard = dashboard;+ } catch {+ try {+ dashboard.stop();+ } catch {}+ this.#dashboard = null;+ }+ }++ public stop(): void {+ try {+ this.#dashboard?.stop();+ } catch {}+ this.#dashboard = null;+ }++ public observe(event: PublishScanProgress): void {+ if (event.type === "started") {+ if (this.#dashboard !== null) {+ this.#dashboard.setPublicationProgress(0, event.total);+ this.#dashboard.setStage(`Publishing findings · 0/${event.total}`);+ } else {+ this.#write(+ `Publishing ${event.total} finding${event.total === 1 ? "" : "s"} to Linear.`,+ );+ }+ return;+ }++ if (event.type === "codex_event") {+ if (+ typeof event.event !== "object" ||+ event.event === null ||+ Array.isArray(event.event)+ ) {+ return;+ }+ for (const activity of scanActivitiesFromEvent(+ event.event as Record<string, unknown>,+ this.#repository,+ )) {+ const item = (event.event as Record<string, unknown>)["item"];+ const tool =+ typeof item === "object" && item !== null && !Array.isArray(item)+ ? (item as Record<string, unknown>)["tool"]+ : undefined;+ const hidesShellCommand =+ activity.kind === "command" ||+ (activity.kind === "tool" &&+ typeof tool === "string" &&+ /^(?:exec|exec_command|shell_command|shell|apply_patch)$/u.test(+ tool,+ ));+ const visibleActivity = hidesShellCommand+ ? {+ ...activity,+ description: "Saving Linear publication results",+ paths: [],+ }+ : activity;+ if (this.#dashboard !== null) {+ this.#dashboard.record(visibleActivity);+ continue;+ }+ const key = `${visibleActivity.id}\0${visibleActivity.description}`;+ if (this.#seenActivities.has(key)) continue;+ this.#seenActivities.add(key);+ const label =+ visibleActivity.kind === "reasoning"+ ? "Codex"+ : visibleActivity.kind === "message"+ ? "Codex"+ : "Tool";+ this.#write(`${label}: ${visibleActivity.description}`, true);+ }+ return;+ }++ if (event.type === "issue_completed") {+ const detail =+ event.error === undefined+ ? `Created ${event.issueIdentifier ?? event.findingId}`+ : `Failed ${event.findingId}: ${event.error}`;+ if (this.#dashboard !== null) {+ this.#dashboard.setPublicationProgress(event.completed, event.total);+ this.#dashboard.setStage(+ `Publishing findings · ${event.completed}/${event.total}`,+ );+ this.#dashboard.note(detail);+ } else {+ this.#write(`[${event.completed}/${event.total}] ${detail}`, true);+ }+ return;+ }++ const summary = `Published ${event.created}/${event.total} finding${event.total === 1 ? "" : "s"}${event.failed === 0 ? "" : ` (${event.failed} failed)`}.`;+ if (this.#dashboard !== null) {+ this.#dashboard.setPublicationProgress(+ event.created + event.failed,+ event.total,+ );+ this.#dashboard.setStage(summary);+ } else {+ this.#write(summary);+ }+ }++ #write(message: string, compact = false): void {+ const sanitized = diagnosticValue(safeErrorMessage(message));+ if (!compact) {+ this.#stream.write(`${sanitized}\n`);+ return;+ }+ const width = Math.max(24, Math.min(this.#stream.columns ?? 120, 160));+ const visible =+ sanitized.length <= width+ ? sanitized+ : `${sanitized.slice(0, width - 1)}…`;+ this.#stream.write(`${visible}\n`);+ }+}+function effortOption() {return z.enum(MODEL_REASONING_EFFORTS, {@@ -798,6 +1079,7 @@ export async function main(let frameworkExit: number | undefined;let frameworkOutput = "";let renderedHistory: string | undefined;+ let renderedPublication: string | undefined;const history = async (args: readonly string[],select: (value: JsonObject) => JsonObject | Promise<JsonObject> = (value) =>@@ -1267,10 +1549,15 @@ export async function main(.describe("Preview the findings without creating Linear issues."),}),output: z.record(z.string(), z.unknown()).optional(),- async run({ args, options }) {+ async run({ args, format, formatExplicit, options }) {const controller = new AbortController();- const onInterrupt = (): void => controller.abort("SIGINT");- const onTerminate = (): void => controller.abort("SIGTERM");+ let presentation: PublicationProgressPresenter | undefined;+ const cancel = (signal: SignalName): void => {+ presentation?.stop();+ controller.abort(signal);+ };+ const onInterrupt = (): void => cancel("SIGINT");+ const onTerminate = (): void => cancel("SIGTERM");let observingSignals = false;try {const teamId =@@ -1291,6 +1578,8 @@ export async function main(undefined;let scanDir = args.scanDir;+ let publicationRepository =+ scanDir === undefined ? "scan" : basename(scanDir);if (scanDir === undefined) {const prompt =dependencies.publishPrompt ??@@ -1333,7 +1622,13 @@ export async function main(}),)).filter((scan): scan is JsonObject => scan !== undefined);- const choices = scans.flatMap((scan) => {+ const now = dependencies.now();+ const emphasizeRepository =+ errorOutput.isTTY === true &&+ dependencies.environment["NO_COLOR"] === undefined &&+ dependencies.environment["TERM"] !== "dumb";+ const repositories = new Map<string, string>();+ const rows = scans.flatMap((scan) => {if (!isJsonObject(scan)) return [];const progress = scan["progress"];const scanId = scan["scanId"];@@ -1351,12 +1646,16 @@ export async function main(}const targetSummary = scan["targetSummary"];const targetPath = scan["targetPath"];- const repository =+ const repository = stripVTControlCharacters(typeof targetSummary === "string" && targetSummary.trim()? targetSummary.trim(): typeof targetPath === "string" && targetPath.trim()? basename(targetPath)- : "unknown repository";+ : "unknown repository",+ )+ .replaceAll(/[\u0000-\u001F\u007F-\u009F]/gu, " ")+ .replace(/\s+/gu, " ")+ .trim();const completedAt = scan["completedAt"];const startedAt = scan["startedAt"];const updatedAt = scan["updatedAt"];@@ -1373,39 +1672,104 @@ export async function main(typeof findingCount === "number"? `${findingCount} finding${findingCount === 1 ? "" : "s"}`: "unknown findings";+ const shortScanId = `...${stripVTControlCharacters(scanId)+ .replaceAll(/[\u0000-\u001F\u007F-\u009F]/gu, " ")+ .replace(/\s+/gu, " ")+ .slice(-6)}`;+ repositories.set(directory, repository);return [{- label: `${repository} · ${scanId} · ${timestamp} · ${findings} · COMPLETE`,+ repository,+ findings,+ age: publicationScanAge(timestamp, now),+ scanId: shortScanId,value: directory,},];});- if (choices.length === 0) {+ if (rows.length === 0) {throw new CodexSecurityError("No completed Codex Security scans are available to publish.",);}+ const repositoryWidth = Math.max(+ publicationDisplayWidth("REPOSITORY"),+ ...rows.map(({ repository }) =>+ publicationDisplayWidth(repository),+ ),+ );+ const findingsWidth = Math.max(+ publicationDisplayWidth("FINDINGS"),+ ...rows.map(({ findings }) => publicationDisplayWidth(findings)),+ );+ const ageWidth = Math.max(+ publicationDisplayWidth("AGE"),+ ...rows.map(({ age }) => publicationDisplayWidth(age)),+ );+ const header = [+ padPublicationColumn("REPOSITORY", repositoryWidth),+ padPublicationColumn("FINDINGS", findingsWidth),+ padPublicationColumn("AGE", ageWidth),+ "SCAN ID",+ ].join(" ");+ const choices = rows.map((row) => {+ const repository = emphasizeRepository+ ? `\u001B[1m${row.repository}\u001B[22m`+ : row.repository;++ return {+ label: [+ padPublicationColumn(repository, repositoryWidth),+ padPublicationColumn(row.findings, findingsWidth),+ padPublicationColumn(row.age, ageWidth),+ row.scanId,+ ].join(" "),+ short: `${repository} · ${row.scanId}`,+ value: row.value,+ };+ });scanDir = await prompt.select("Which completed scan would you like to publish?",choices,+ { header },);+ publicationRepository =+ repositories.get(scanDir) ?? basename(scanDir);}+ const progress = new PublicationProgressPresenter(+ errorOutput,+ dependencies,+ publicationRepository,+ );+ presentation = progress;if (!options.dryRun) {dependencies.addSignalListener("SIGINT", onInterrupt);dependencies.addSignalListener("SIGTERM", onTerminate);observingSignals = true;+ progress.start();+ }+ let result;+ try {+ result = await (dependencies.publishScan ?? publishScan)(+ resolve(dependencies.currentDirectory(), scanDir),+ {+ destination: options.to,+ teamId,+ ...(projectId === undefined ? {} : { projectId }),+ dryRun: options.dryRun,+ ...(options.dryRun+ ? {}+ : {+ signal: controller.signal,+ onProgress: (event: PublishScanProgress) =>+ progress.observe(event),+ }),+ },+ );+ } finally {+ progress.stop();}- 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)) {@@ -1416,6 +1780,19 @@ export async function main();}}+ if (+ format === "toon" &&+ !formatExplicit &&+ !options.dryRun &&+ !argv.some((argument) => SCAN_HISTORY_OUTPUT_OPTION.test(argument))+ ) {+ renderedPublication = renderPublicationSummary(+ result,+ output.isTTY === true &&+ dependencies.environment["NO_COLOR"] === undefined &&+ dependencies.environment["TERM"] !== "dumb",+ );+ }return { ...result };} catch (error) {const signal = controller.signal.reason;@@ -2267,7 +2644,10 @@ export async function main(}if (frameworkOutput.length === 0) return exitCode;try {- await writeCliOutput(output, renderedHistory ?? frameworkOutput);+ await writeCliOutput(+ output,+ renderedPublication ?? renderedHistory ?? frameworkOutput,+ );return exitCode;} catch (error) {errorOutput.write(`codex-security: ${errorMessage(error)}\n`);diff --git a/sdk/typescript/src/scan-dashboard.ts b/sdk/typescript/src/scan-dashboard.tsindex 430a12fa4..2f6a8cf3e 100644--- a/sdk/typescript/src/scan-dashboard.ts+++ b/sdk/typescript/src/scan-dashboard.ts@@ -44,6 +44,7 @@ interface DashboardInput {interface ScanDashboardOptions {repository: string;+ presentation?: "scan" | "publication";mode?: ScanMode;model?: ScanModelConfiguration;maxCostUsd?: number;@@ -100,6 +101,7 @@ export class ScanDashboard {readonly #activities: TimedScanActivity[] = [];#stage = "Preparing scan";#files: ScanProgress | null = null;+ #publicationProgress: { completed: number; total: number } | null = null;#cost: Readonly<ScanCost> | null = null;#timer: NodeJS.Timeout | null = null;#scrollOffset = 0;@@ -226,6 +228,11 @@ export class ScanDashboard {this.#refresh();}+ public setPublicationProgress(completed: number, total: number): void {+ this.#publicationProgress = { completed, total };+ this.#refresh();+ }+public setCost(cost: Readonly<ScanCost>): void {this.#cost = cost;this.#refresh();@@ -293,6 +300,7 @@ export class ScanDashboard {}#render(): void {+ const publication = this.#options.presentation === "publication";const width = this.#width();const activityRows = this.#activityRows();const divider = ` ${"─".repeat(Math.max(0, width - 4))}`;@@ -326,7 +334,7 @@ export class ScanDashboard {const activity = history.slice(first, first + activityRows);if (activity.length === 0) {activity.push({- text: ` [${formatLocalTime(this.#options.clock.now())}] · Waiting for scan activity…`,+ text: ` [${formatLocalTime(this.#options.clock.now())}] · Waiting for ${publication ? "publication" : "scan"} activity…`,kind: "path",});}@@ -340,15 +348,22 @@ export class ScanDashboard {const model = this.#options.model;const lines = [- ` CODEX SECURITY · ${basename(this.#options.repository)}${model === undefined ? "" : ` · ${model.model} (${model.reasoningEffort})`}`,+ ` CODEX SECURITY · ${publication ? "PUBLISH · " : ""}${basename(this.#options.repository)}${model === undefined ? "" : ` · ${model.model} (${model.reasoningEffort})`}`,divider,...activity,divider,- ...(this.#options.mode === "deep"- ? []- : [` STAGE ${this.#stage}`, ` FILES ${files}`]),- ` TOKENS ${tokens}`,- ` COST ${cost}`,+ ...(publication+ ? [+ ` STAGE ${this.#stage}`,+ ` FINDINGS ${this.#publicationProgress === null ? "waiting for findings" : `${formatCount(this.#publicationProgress.completed)} / ${formatCount(this.#publicationProgress.total)} processed`}`,+ ]+ : [+ ...(this.#options.mode === "deep"+ ? []+ : [` STAGE ${this.#stage}`, ` FILES ${files}`]),+ ` TOKENS ${tokens}`,+ ` COST ${cost}`,+ ]),` TIME ${time} · ${scrollStatus}`,];@@ -397,7 +412,11 @@ export class ScanDashboard {1,(this.#stream.rows ?? 24) -FIXED_SCREEN_ROWS +- (this.#options.mode === "deep" ? 2 : 0),+ (this.#options.presentation === "publication"+ ? 2+ : this.#options.mode === "deep"+ ? 2+ : 0),);}diff --git a/sdk/typescript/tests-ts/cli-publish.test.ts b/sdk/typescript/tests-ts/cli-publish.test.tsindex 03b6b4a95..42c5a5888 100644--- a/sdk/typescript/tests-ts/cli-publish.test.ts+++ b/sdk/typescript/tests-ts/cli-publish.test.ts@@ -1,6 +1,7 @@import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";-import { join, resolve } from "node:path";+import { dirname, join, resolve } from "node:path";+import { stripVTControlCharacters } from "node:util";import { afterEach, describe, expect, test } from "bun:test";import { main } from "../src/cli.js";import { capture, dependencies, FakeSignals } from "./cli-fixtures.js";@@ -31,6 +32,18 @@ async function publicationDirectory(): Promise<string> {return directory;}+async function publicationScanDirectories(count: number): Promise<string[]> {+ const root = await mkdtemp(join(tmpdir(), "codex-security-publish-picker-"));+ temporaryDirectories.push(root);+ return Promise.all(+ Array.from({ length: count }, async (_, index) => {+ const directory = join(root, `scan-${index}`);+ await mkdir(directory, { mode: 0o700 });+ return directory;+ }),+ );+}+function publicationResult(failed: { findingId: string; error: string }[] = [],) {@@ -98,6 +111,7 @@ describe("publish scan", () => {projectId: "project-from-flags",dryRun: false,signal: expect.any(AbortSignal),+ onProgress: expect.any(Function),},});expect(JSON.parse(stdout.text())).toEqual(publicationResult());@@ -212,15 +226,435 @@ describe("publish scan", () => {}});+ test("prints the first five persisted Linear issues and database-backed totals", async () => {+ const stdout = capture();+ const stderr = capture();+ const result = publicationResult();+ result.created = Array.from({ length: 7 }, (_, index) => ({+ findingId: `private-finding-${index + 1}`,+ occurrenceId: `private-occurrence-${index + 1}`,+ issueIdentifier: `SEC-${200 + index}`,+ url: `https://linear.app/example/issue/SEC-${200 + index}`,+ }));+ result.counts.findings = 999;+ result.counts.created = 999;+ result.counts.failed = 999;+ const deps = dependencies();+ deps.publishScan = async () => result;++ expect(+ await main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);++ expect(stdout.text()).toBe(+ [+ "✓ Linear publication complete",+ "",+ " SEC-200 https://linear.app/example/issue/SEC-200",+ " SEC-201 https://linear.app/example/issue/SEC-201",+ " SEC-202 https://linear.app/example/issue/SEC-202",+ " SEC-203 https://linear.app/example/issue/SEC-203",+ " SEC-204 https://linear.app/example/issue/SEC-204",+ " ...",+ "",+ "7 total issues created",+ "0 total issues failed",+ "",+ ].join("\n"),+ );+ for (const privateValue of [+ "scan-123",+ "uploadId",+ "team-from-flags",+ "project-from-flags",+ "private-finding-",+ "private-occurrence-",+ "SEC-205",+ "SEC-206",+ "999",+ ]) {+ expect(stdout.text()).not.toContain(privateValue);+ }+ expect(stderr.text()).toBe("");+ });++ test("reports sanitized receipt warnings after terminal restoration without contaminating publication output", async () => {+ const warning =+ "Could not save the publication receipt: [redacted]. Linear issues were already created; do not retry publication.";+ const unsafeWarning = "Injected\u001B[31m\nsecond line\u0007";+ for (const { json, tty, failed } of [+ { json: false, tty: false, failed: false },+ { json: true, tty: false, failed: false },+ { json: true, tty: true, failed: false },+ { json: false, tty: true, failed: true },+ ]) {+ const stdout = capture();+ const stderr = capture(tty);+ const result = {+ ...publicationResult(+ failed ? [{ findingId: "finding-2", error: "Private details" }] : [],+ ),+ warnings: [warning, unsafeWarning],+ };+ const deps = dependencies();+ deps.publishScan = async () => result;++ expect(+ await main(+ [+ "publish",+ "scan",+ "completed-scan",+ ...DESTINATION_OPTIONS,+ ...(json ? ["--json"] : []),+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(failed ? 2 : 0);++ expect(stderr.text()).toContain(`codex-security: ${warning}\n`);+ expect(stderr.text()).toContain(+ "codex-security: Injected [31m second line \n",+ );+ expect(stderr.text()).not.toContain("\nsecond line");+ expect(stderr.text()).not.toContain("\u0007");+ if (tty) {+ expect(stderr.text().indexOf("\u001B[?25h\u001B[?1049l")).toBeLessThan(+ stderr.text().indexOf(`codex-security: ${warning}`),+ );+ }+ if (json) {+ expect(JSON.parse(stdout.text())).toEqual(result);+ expect(stdout.text()).not.toContain("\u001B");+ } else {+ expect(stdout.text()).toContain("Linear publication");+ expect(stdout.text()).not.toContain("publication receipt");+ expect(stdout.text()).not.toContain("Injected");+ }+ }+ });++ test("omits the issue-list ellipsis when zero to five issues were created", async () => {+ for (const total of [0, 1, 5]) {+ const stdout = capture();+ const stderr = capture();+ const result = publicationResult();+ result.created = Array.from({ length: total }, (_, index) => ({+ findingId: `finding-${index + 1}`,+ occurrenceId: `occurrence-${index + 1}`,+ issueIdentifier: `SEC-${300 + index}`,+ url: `https://linear.app/example/issue/SEC-${300 + index}`,+ }));+ result.counts.findings = total;+ result.counts.created = total;+ const deps = dependencies();+ deps.publishScan = async () => result;++ expect(+ await main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(stdout.text()).not.toContain("\n ...\n");+ expect(stdout.text()).toContain(+ `${total} total issue${total === 1 ? "" : "s"} created\n`,+ );+ expect(stdout.text()).toContain("0 total issues failed\n");+ expect(+ stdout.text().match(/https:\/\/linear\.app\//gu) ?? [],+ ).toHaveLength(total);+ if (total === 0) {+ expect(stdout.text()).toBe(+ "✓ Linear publication complete\n\n0 total issues created\n0 total issues failed\n",+ );+ }+ }+ });++ test("renders partial failures without exposing finding errors or changing exit codes", async () => {+ const stdout = capture();+ const stderr = capture();+ const failures = [+ {+ findingId: "private-finding-2",+ error: "PRIVATE_CONNECTOR_FAILURE_DETAILS",+ },+ ];+ const result = publicationResult(failures);+ result.counts.created = 100;+ result.counts.failed = 200;+ const deps = dependencies();+ deps.publishScan = async () => result;++ expect(+ await main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);+ expect(stdout.text()).toBe(+ [+ "! Linear publication completed with failures",+ "",+ " SEC-123 https://linear.app/example/issue/SEC-123",+ "",+ "1 total issue created",+ "1 total issue failed",+ "",+ ].join("\n"),+ );+ expect(stdout.text()).not.toContain("private-finding-2");+ expect(stdout.text()).not.toContain("PRIVATE_CONNECTOR_FAILURE_DETAILS");+ expect(stdout.text()).not.toContain("100");+ expect(stdout.text()).not.toContain("200");+ expect(stderr.text()).toBe("");+ });++ test("omits missing or unsafe issue links and sanitizes issue identifiers", async () => {+ const stdout = capture();+ const stderr = capture();+ const initial = publicationResult();+ const base = initial.created[0]!;+ const { url: _unusedUrl, ...withoutUrl } = base;+ const created = [+ {+ ...base,+ issueIdentifier: "\u001B[31mSEC-400\u001B[0m\n\u009Fsafe",+ url: "javascript:alert(1)",+ },+ {+ ...base,+ issueIdentifier: "SEC-401",+ url: "https://user:[email protected]/example/issue/SEC-401",+ },+ {+ ...base,+ issueIdentifier: "SEC-402",+ url: "https://linear.app/example/issue/SEC-402?token=PRIVATE_TOKEN",+ },+ {+ ...base,+ issueIdentifier: "SEC-403",+ url: "https://unsafe.example/issue/SEC-403",+ },+ { ...withoutUrl, issueIdentifier: "SEC-404" },+ ];+ const result = {+ ...initial,+ created,+ counts: { findings: created.length, created: created.length, failed: 0 },+ };+ const deps = dependencies();+ deps.publishScan = async () => result;++ expect(+ await main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(stdout.text()).toContain(" SEC-400\n");+ for (const identifier of ["SEC-401", "SEC-402", "SEC-403", "SEC-404"]) {+ expect(stdout.text()).toContain(` ${identifier}\n`);+ }+ expect(stdout.text()).not.toContain("javascript:");+ expect(stdout.text()).not.toContain("PRIVATE_PASSWORD");+ expect(stdout.text()).not.toContain("PRIVATE_TOKEN");+ expect(stdout.text()).not.toContain("unsafe.example");+ expect(stdout.text()).not.toContain("\u001B");+ expect(stdout.text()).not.toContain("\u009F");+ expect(stdout.text()).toContain("5 total issues created\n");+ expect(stdout.text()).not.toContain("\n ...\n");+ });++ test("colors publication headings only for color-enabled stdout terminals", async () => {+ const scenarios = [+ { interactive: false, environment: {}, color: false },+ { interactive: true, environment: {}, color: true },+ { interactive: true, environment: { NO_COLOR: "1" }, color: false },+ { interactive: true, environment: { TERM: "dumb" }, color: false },+ ] as const;++ for (const scenario of scenarios) {+ const stdout = capture(scenario.interactive);+ const stderr = capture();+ const deps = dependencies({ environment: scenario.environment });+ deps.publishScan = async () => publicationResult();++ expect(+ await main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(stripVTControlCharacters(stdout.text())).toContain(+ "✓ Linear publication complete\n",+ );+ if (scenario.color) {+ expect(stdout.text()).toContain("\u001B[32m✓\u001B[39m");+ expect(stdout.text()).toContain(+ "\u001B[1mLinear publication complete\u001B[22m",+ );+ } else {+ expect(stdout.text()).not.toContain("\u001B");+ }+ }+ });++ test("preserves explicit structured output formats and prepared dry-run previews", async () => {+ for (const format of [+ { flags: ["--format", "json"], json: true },+ { flags: ["--format", "toon"], json: false },+ { flags: ["--full-output"], json: false },+ ] as const) {+ const stdout = capture();+ const stderr = capture();+ const result = publicationResult();+ const deps = dependencies();+ deps.publishScan = async () => result;++ expect(+ await main(+ [+ "publish",+ "scan",+ "completed-scan",+ ...DESTINATION_OPTIONS,+ ...format.flags,+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ if (format.json) {+ expect(JSON.parse(stdout.text())).toEqual(result);+ } else {+ expect(stdout.text()).toContain("scanId: scan-123");+ expect(stdout.text()).toContain("uploadId: scan-123");+ }+ expect(stdout.text()).not.toContain("Linear publication complete");+ }++ const stdout = capture();+ const stderr = capture(true);+ const deps = dependencies();+ let observedSignals = false;+ deps.addSignalListener = () => {+ observedSignals = true;+ };+ deps.publishScan = async (_scanDirectory, options) => {+ expect(options.onProgress).toBeUndefined();+ return { ...publicationResult(), dryRun: true, issues: [] };+ };++ expect(+ await main(+ [+ "publish",+ "scan",+ "completed-scan",+ ...DESTINATION_OPTIONS,+ "--dry-run",+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);+ expect(stdout.text()).toContain("dryRun: true");+ expect(stdout.text()).not.toContain("Linear publication complete");+ expect(stderr.text()).toBe("");+ expect(observedSignals).toBe(false);+ });++ test("reports every created Linear issue with a successful exit code", async () => {+ const stdout = capture();+ const stderr = capture();+ const result = publicationResult();+ result.created.push({+ findingId: "finding-2",+ occurrenceId: "occurrence-2",+ issueIdentifier: "SEC-124",+ url: "https://linear.app/example/issue/SEC-124",+ });+ result.counts.findings = result.created.length;+ result.counts.created = result.created.length;+ const deps = dependencies();+ deps.publishScan = async (_scanDirectory, options) => {+ options.onProgress?.({+ type: "started",+ scanId: result.scanId,+ total: result.created.length,+ });+ for (const [index, issue] of result.created.entries()) {+ options.onProgress?.({+ type: "issue_completed",+ findingId: issue.findingId,+ issueIdentifier: issue.issueIdentifier,+ completed: index + 1,+ total: result.created.length,+ });+ }+ options.onProgress?.({+ type: "completed",+ created: result.created.length,+ failed: 0,+ total: result.created.length,+ });+ return 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()).toContain("[1/2] Created SEC-123\n");+ expect(stderr.text()).toContain("[2/2] Created SEC-124\n");+ expect(stderr.text()).toContain("Published 2/2 findings.\n");+ });+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 directories = await publicationScanDirectories(2);+ const firstDirectory = directories[0]!;+ const selectedDirectory = directories[1]!;+ const root = dirname(firstDirectory);+ const missingDirectory = join(root, "missing-scan");+ const replacedDirectory = join(root, "replaced-scan");+ const linkedDirectory = join(root, "linked-scan");+ await writeFile(replacedDirectory, "this scan is now a regular file");+ await symlink(+ firstDirectory,+ linkedDirectory,+ process.platform === "win32" ? "junction" : "dir",+ );const stdout = capture();const stderr = capture(true);let question = "";- let choices: readonly { label: string; value: string }[] = [];+ let choices: readonly { label: string; short?: string; value: string }[] =+ [];+ let header: string | undefined;let workbenchArguments: readonly string[] | undefined;let publishedDirectory: string | undefined;const deps = dependencies({@@ -228,8 +662,18 @@ describe("publish scan", () => {workbenchArguments = args;return {scans: [+ ...[missingDirectory, replacedDirectory, linkedDirectory].map(+ (scanDir, index) => ({+ scanId: `unavailable-scan-${index}`,+ scanDir,+ targetSummary: "unavailable-repository-must-not-expand-columns",+ completedAt: "2026-08-15T01:05:00Z",+ findingCount: 999,+ progress: { status: "complete" },+ }),+ ),{- scanId: "first-scan",+ scanId: "11111111-2222-3333-4444-555555abc123",scanDir: firstDirectory,targetPath: join(tmpdir(), "first-repository"),startedAt: "2026-08-15T01:00:00Z",@@ -239,7 +683,7 @@ describe("publish scan", () => {progress: { status: "complete" },},{- scanId: "second-scan",+ scanId: "66666666-7777-8888-9999-000000def456",scanDir: selectedDirectory,targetPath: join(tmpdir(), "second-repository"),startedAt: null,@@ -262,14 +706,17 @@ describe("publish scan", () => {};},});+ deps.now = () => Date.parse("2026-08-15T02:17:00Z");deps.publishPrompt = {isInteractive: () => true,select: async <Value extends string>(message: string,- options: readonly { label: string; value: Value }[],+ options: readonly { label: string; short?: string; value: Value }[],+ presentation?: { header?: string },): Promise<Value> => {question = message;choices = options;+ header = presentation?.header;return options[1]!.value;},};@@ -289,18 +736,724 @@ describe("publish scan", () => {expect(workbenchArguments).toEqual(["list-scans", "--status", "complete"]);expect(question).toBe("Which completed scan would you like to publish?");expect(choices).toHaveLength(2);+ expect(header).toContain("REPOSITORY");+ expect(header).toContain("SCAN ID");+ expect(header).not.toContain("unavailable");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("...abc123");+ expect(choices[0]!.label).toContain("1 hour ago");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("...def456");+ expect(choices[1]!.label).toContain("2 minutes ago");expect(choices[1]!.label).toContain("3 findings");- expect(choices[1]!.label).toContain("COMPLETE");+ expect(stripVTControlCharacters(choices[1]!.short!)).toBe(+ "second-repository · ...def456",+ );+ expect(choices[0]!.label).not.toContain("11111111-2222-3333");+ expect(choices[1]!.label).not.toContain("2026-08-15T02:15:00Z");+ expect(choices[1]!.label).not.toContain("COMPLETE");+ expect(choices.every((choice) => !choice.label.includes("\n"))).toBe(true);+ expect(+ choices.every((choice) => !choice.label.includes("unavailable")),+ ).toBe(true);expect(publishedDirectory).toBe(selectedDirectory);expect(JSON.parse(stdout.text())).toEqual(publicationResult());- expect(stderr.text()).toBe("");+ expect(stderr.text()).toContain("\u001B[?1049h\u001B[?25l");+ expect(stripVTControlCharacters(stderr.text())).toContain(+ "CODEX SECURITY · PUBLISH · second-repository",+ );+ expect(stderr.text()).toContain("\u001B[?25h\u001B[?1049l");+ expect(stderr.text()).not.toContain("66666666-7777-8888-9999");+ });++ test("aligns repository, findings, age, and scan ID columns by visible terminal width", async () => {+ const currentTime = Date.parse("2030-01-01T12:00:00Z");+ const scans = [+ {+ repository: "tiny",+ width: 4,+ findingCount: 1,+ elapsed: 60_000,+ age: "1 minute ago",+ },+ {+ repository: "service-alpha",+ width: 13,+ findingCount: 120,+ elapsed: 4 * 24 * 60 * 60_000,+ age: "4 days ago",+ },+ {+ repository: "服务",+ width: 4,+ findingCount: 22,+ elapsed: 30_000,+ age: "30 seconds ago",+ },+ {+ repository: "cafe\u0301",+ width: 4,+ findingCount: 3,+ elapsed: 2 * 60 * 60_000,+ age: "2 hours ago",+ },+ {+ repository: "👩💻-api",+ width: 6,+ findingCount: 9,+ elapsed: 0,+ age: "just now",+ },+ {+ repository: "🇺🇸-edge",+ width: 7,+ findingCount: 0,+ elapsed: 8 * 24 * 60 * 60_000,+ age: "1 week ago",+ },+ {+ repository: "1️⃣-key",+ width: 6,+ findingCount: 44,+ elapsed: 32 * 24 * 60 * 60_000,+ age: "1 month ago",+ },+ {+ repository: "♥-text",+ width: 6,+ findingCount: 8,+ elapsed: 366 * 24 * 60 * 60_000,+ age: "1 year ago",+ },+ {+ repository: "♥️-emoji",+ width: 8,+ findingCount: 7,+ elapsed: -30_000,+ age: "just now",+ },+ {+ repository: "invalid-age",+ width: 11,+ findingCount: 2,+ elapsed: Number.NaN,+ age: "unknown",+ },+ ] as const;+ const repositoryWidth = Math.max(+ "REPOSITORY".length,+ ...scans.map(({ width }) => width),+ );+ const findingsWidth = Math.max(+ "FINDINGS".length,+ ...scans.map(+ ({ findingCount }) =>+ `${findingCount} finding${findingCount === 1 ? "" : "s"}`.length,+ ),+ );+ const ageWidth = Math.max(+ "AGE".length,+ ...scans.map(({ age }) => age.length),+ );+ const expectedHeader = [+ "REPOSITORY".padEnd(repositoryWidth),+ "FINDINGS".padEnd(findingsWidth),+ "AGE".padEnd(ageWidth),+ "SCAN ID",+ ].join(" ");+ const directories = await publicationScanDirectories(scans.length);++ for (const color of [true, false]) {+ let header: string | undefined;+ let choices: readonly { label: string; short?: string; value: string }[] =+ [];+ const deps = dependencies({+ environment: color ? {} : { NO_COLOR: "1" },+ onWorkbench: () => ({+ scans: scans.map(({ repository, findingCount, elapsed }, index) => ({+ scanId: `synthetic-scan-${String(index).padStart(6, "0")}`,+ scanDir: directories[index]!,+ targetSummary: repository,+ completedAt: Number.isNaN(elapsed)+ ? "not-a-timestamp"+ : new Date(currentTime - elapsed).toISOString(),+ findingCount,+ progress: { status: "complete" },+ })),+ }),+ });+ deps.now = () => currentTime;+ deps.publishPrompt = {+ isInteractive: () => true,+ select: async <Value extends string>(+ _message: string,+ options: readonly { label: string; short?: string; value: Value }[],+ presentation?: { header?: string },+ ): Promise<Value> => {+ header = presentation?.header;+ choices = options;+ return options[0]!.value;+ },+ };+ deps.publishScan = async () => publicationResult();++ expect(+ await main(+ ["publish", "scan", ...DESTINATION_OPTIONS, "--json"],+ capture().stream,+ capture(true).stream,+ deps,+ ),+ ).toBe(0);+ expect(header).toBe(expectedHeader);+ expect(header).not.toContain("\u001B");++ for (const [index, scan] of scans.entries()) {+ const findings = `${scan.findingCount} finding${scan.findingCount === 1 ? "" : "s"}`;+ const expectedRow = [+ `${scan.repository}${" ".repeat(repositoryWidth - scan.width)}`,+ findings.padEnd(findingsWidth),+ scan.age.padEnd(ageWidth),+ `...${String(index).padStart(6, "0")}`,+ ].join(" ");+ const label = choices[index]!.label;+ const selected = choices[index]!.short!;++ expect(stripVTControlCharacters(label)).toBe(expectedRow);+ expect(stripVTControlCharacters(selected)).toBe(+ `${scan.repository} · ...${String(index).padStart(6, "0")}`,+ );+ expect(selected).not.toContain("finding");+ expect(selected).not.toContain(" ago");+ expect(label).not.toContain("\n");+ expect(label).not.toContain(" · ");+ expect(label).not.toContain("ran ");+ if (color) {+ expect(label).toStartWith(`\u001B[1m${scan.repository}\u001B[22m`);+ expect(selected).toStartWith(`\u001B[1m${scan.repository}\u001B[22m`);+ } else {+ expect(label).not.toContain("\u001B");+ expect(selected).not.toContain("\u001B");+ }+ }+ }+ });++ test("shows actual Codex reasoning and Linear activity in a full-screen publication dashboard", async () => {+ const stdout = capture();+ const stderr = capture(true);+ const deps = dependencies();+ deps.publishScan = async (_scanDirectory, options) => {+ options.onProgress?.({ type: "started", scanId: "scan-123", total: 2 });+ options.onProgress?.({+ type: "codex_event",+ event: {+ type: "item.completed",+ item: {+ id: "reasoning-1",+ type: "reasoning",+ text: "Checking the connected Linear project.",+ },+ },+ });+ options.onProgress?.({+ type: "codex_event",+ event: {+ type: "item.started",+ item: {+ id: "linear-team",+ type: "mcp_tool_call",+ server: "codex_apps",+ tool: "linear_get_team",+ arguments: { query: "team-from-flags" },+ },+ },+ });+ options.onProgress?.({+ type: "issue_completed",+ findingId: "finding-1",+ issueIdentifier: "SEC-123",+ completed: 1,+ total: 2,+ });+ options.onProgress?.({+ type: "completed",+ created: 1,+ failed: 1,+ total: 2,+ });+ return publicationResult();+ };++ expect(+ await main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS, "--json"],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);++ const text = stripVTControlCharacters(stderr.text());+ expect(stderr.text()).toContain("\u001B[?1049h\u001B[?25l");+ expect(text).toContain("CODEX SECURITY · PUBLISH · completed-scan");+ expect(text).toContain("Checking the connected Linear project.");+ expect(text).toContain("linear_get_team");+ expect(text).toContain("Created SEC-123");+ expect(text).toContain("FINDINGS 1 / 2 processed");+ expect(text).toContain("Published 1/2 findings (1 failed).");+ expect(text).not.toContain("FILES");+ expect(text).not.toContain("TOKENS");+ expect(text).not.toContain("COST");+ expect(stderr.text()).toContain("\u001B[?25h\u001B[?1049l");+ expect(JSON.parse(stdout.text())).toEqual(publicationResult());+ expect(stdout.text()).not.toContain("\u001B");+ });++ test("removes repository-controlled terminal escapes while retaining intentional choice emphasis", async () => {+ const directory = (await publicationScanDirectories(1))[0]!;+ for (const color of [true, false]) {+ let choice = "";+ const deps = dependencies({+ environment: color ? {} : { NO_COLOR: "1" },+ onWorkbench: () => ({+ scans: [+ {+ scanId: "prefix-\u001B[31m\u0007def456",+ scanDir: directory,+ targetSummary: "payments\u001B[2J-api\u0007\nservice\u0008",+ completedAt: "2026-08-15T01:00:00Z",+ findingCount: 1,+ progress: { status: "complete" },+ },+ ],+ }),+ });+ deps.now = () => Date.parse("2026-08-15T01:01:00Z");+ deps.publishPrompt = {+ isInteractive: () => true,+ select: async <Value extends string>(+ _message: string,+ options: readonly { label: string; value: Value }[],+ ): Promise<Value> => {+ choice = options[0]!.label;+ return options[0]!.value;+ },+ };+ deps.publishScan = async () => publicationResult();++ expect(+ await main(+ ["publish", "scan", ...DESTINATION_OPTIONS],+ capture().stream,+ capture(true).stream,+ deps,+ ),+ ).toBe(0);++ expect(stripVTControlCharacters(choice)).toContain(+ "payments-api service 1 finding 1 minute ago ...def456",+ );+ expect(choice).not.toContain("\u001B[2J");+ expect(choice).not.toContain("\u001B[31m");+ expect(choice).not.toContain("\u0007");+ expect(choice).not.toContain("\u0008");+ if (color) {+ expect(choice).toStartWith("\u001B[1mpayments-api service\u001B[22m");+ } else {+ expect(choice).not.toContain("\u001B");+ }+ }+ });++ test("streams sanitized Codex progress to noninteractive stderr without terminal controls", async () => {+ const stdout = capture();+ const stderr = capture();+ const deps = dependencies();+ deps.publishScan = async (_scanDirectory, options) => {+ options.onProgress?.({ type: "started", scanId: "scan-123", total: 1 });+ const reasoning = {+ type: "item.completed",+ item: {+ id: "reasoning-1",+ type: "reasoning",+ text: "Preparing the Linear issue.\u001B[31m",+ },+ };+ options.onProgress?.({ type: "codex_event", event: reasoning });+ options.onProgress?.({ type: "codex_event", event: reasoning });+ options.onProgress?.({+ type: "codex_event",+ event: {+ type: "item.started",+ item: {+ id: "linear-create",+ type: "mcp_tool_call",+ server: "codex_apps",+ tool: "linear_save_issue",+ arguments: {+ description: "PRIVATE_SOURCE_SNIPPET_MUST_NOT_BE_LOGGED",+ },+ },+ },+ });+ options.onProgress?.({+ type: "issue_completed",+ findingId: "finding-1",+ issueIdentifier: "SEC-123",+ completed: 1,+ total: 1,+ });+ options.onProgress?.({+ type: "completed",+ created: 1,+ failed: 0,+ total: 1,+ });+ return publicationResult();+ };++ expect(+ await main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS, "--json"],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);++ expect(stderr.text()).toContain("Publishing 1 finding to Linear.\n");+ expect(stderr.text()).toContain("Codex: Preparing the Linear issue.");+ expect(stderr.text()).toContain("Tool: linear_save_issue\n");+ expect(stderr.text()).toContain("[1/1] Created SEC-123\n");+ expect(stderr.text()).toContain("Published 1/1 finding.\n");+ expect(stderr.text().match(/Preparing the Linear issue/gu)).toHaveLength(1);+ expect(stderr.text()).not.toContain(+ "PRIVATE_SOURCE_SNIPPET_MUST_NOT_BE_LOGGED",+ );+ expect(stderr.text()).not.toContain("\u001B");+ expect(JSON.parse(stdout.text())).toEqual(publicationResult());+ });++ test("hides source-bearing handoff commands in plain and full-screen progress", async () => {+ for (const interactive of [false, true]) {+ const stdout = capture();+ const stderr = capture(interactive);+ const deps = dependencies();+ deps.publishScan = async (_scanDirectory, options) => {+ options.onProgress?.({ type: "started", scanId: "scan-123", total: 1 });+ options.onProgress?.({+ type: "codex_event",+ event: {+ type: "item.completed",+ item: {+ id: "reasoning-1",+ type: "reasoning",+ text: "Saving the verified Linear issue.",+ },+ },+ });+ options.onProgress?.({+ type: "codex_event",+ event: {+ type: "item.started",+ item: {+ id: "handoff-command",+ type: "command_execution",+ command:+ "python -c 'write(\"PRIVATE_SOURCE_SNIPPET_MUST_NOT_BE_LOGGED\")'",+ },+ },+ });+ options.onProgress?.({+ type: "codex_event",+ event: {+ type: "item.started",+ item: {+ id: "handoff-tool",+ type: "mcp_tool_call",+ server: "local-tools",+ tool: "exec",+ arguments: {+ cmd: "append PRIVATE_ISSUE_DESCRIPTION_MUST_NOT_BE_LOGGED",+ },+ },+ },+ });+ options.onProgress?.({+ type: "codex_event",+ event: {+ type: "item.started",+ item: {+ id: "linear-create",+ type: "mcp_tool_call",+ server: "codex_apps",+ tool: "linear.save_issue",+ arguments: {+ description: "PRIVATE_LINEAR_ARGUMENT_MUST_NOT_BE_LOGGED",+ },+ },+ },+ });+ options.onProgress?.({+ type: "issue_completed",+ findingId: "finding-1",+ issueIdentifier: "SEC-123",+ completed: 1,+ total: 1,+ });+ options.onProgress?.({+ type: "completed",+ created: 1,+ failed: 0,+ total: 1,+ });+ return publicationResult();+ };++ expect(+ await main(+ [+ "publish",+ "scan",+ "completed-scan",+ ...DESTINATION_OPTIONS,+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);++ const progress = stripVTControlCharacters(stderr.text());+ expect(progress).toContain("Saving the verified Linear issue.");+ expect(progress).toContain("Saving Linear publication results");+ expect(progress).toContain("linear.save_issue");+ expect(progress).toContain("Created SEC-123");+ expect(progress).not.toContain("PRIVATE_SOURCE_SNIPPET");+ expect(progress).not.toContain("PRIVATE_ISSUE_DESCRIPTION");+ expect(progress).not.toContain("PRIVATE_LINEAR_ARGUMENT");+ expect(JSON.parse(stdout.text())).toEqual(publicationResult());+ expect(stdout.text()).not.toContain("PRIVATE_");+ }+ });++ test("restores the publication screen before reporting publisher failures", async () => {+ const stdout = capture();+ const stderr = capture(true);+ const deps = dependencies();+ deps.publishScan = async (_scanDirectory, options) => {+ options.onProgress?.({ type: "started", scanId: "scan-123", total: 1 });+ throw new Error("Linear publication stopped unexpectedly.");+ };++ expect(+ await main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(2);++ const restored = stderr.text().lastIndexOf("\u001B[?25h\u001B[?1049l");+ const error = stderr+ .text()+ .lastIndexOf("Linear publication stopped unexpectedly.");+ expect(restored).toBeGreaterThan(-1);+ expect(error).toBeGreaterThan(restored);+ expect(stdout.text()).toBe("");+ });++ test("uses plain progress in CI and dumb terminals even when stderr is a TTY", async () => {+ for (const environment of [{ CI: "1" }, { TERM: "dumb" }]) {+ const stdout = capture();+ const stderr = capture(true);+ const deps = dependencies({ environment });+ deps.publishScan = async (_scanDirectory, options) => {+ options.onProgress?.({ type: "started", scanId: "scan-123", total: 1 });+ options.onProgress?.({+ type: "completed",+ created: 1,+ failed: 0,+ total: 1,+ });+ return publicationResult();+ };++ expect(+ await main(+ [+ "publish",+ "scan",+ "completed-scan",+ ...DESTINATION_OPTIONS,+ "--json",+ ],+ stdout.stream,+ stderr.stream,+ deps,+ ),+ ).toBe(0);++ expect(stderr.text()).toContain("Publishing 1 finding to Linear.");+ expect(stderr.text()).toContain("Published 1/1 finding.");+ expect(stderr.text()).not.toContain("\u001B");+ expect(JSON.parse(stdout.text())).toEqual(publicationResult());+ }+ });++ test("restores the terminal before cancellation and waits for publication recovery", async () => {+ for (const interactive of [true, false]) {+ 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 captured = capture(interactive);+ const events: string[] = [];+ const stderr = {+ isTTY: interactive,+ write(value: string | Uint8Array): boolean {+ if (value.toString().includes("\u001B[?25h\u001B[?1049l")) {+ events.push("restored terminal");+ }+ return captured.stream.write(value);+ },+ };+ const listeners = new Map<string, () => void>();+ const removed: 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();+ deps.addSignalListener = (name, listener) => {+ listeners.set(name, listener);+ };+ deps.removeSignalListener = (name, listener) => {+ if (listeners.get(name) === listener) listeners.delete(name);+ removed.push(name);+ };+ deps.forceExit = (name) => events.push(`forced ${name}`);+ deps.publishScan = async (_scanDirectory, options) => {+ expect(options.signal).toBeInstanceOf(AbortSignal);+ options.signal?.addEventListener("abort", () => {+ events.push(`aborted ${String(options.signal?.reason)}`);+ });+ options.onProgress?.({+ type: "started",+ scanId: "scan-123",+ total: 1,+ });+ listeners.get(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,+ ...(signal === "SIGINT" ? ["--json"] : []),+ ],+ stdout.stream,+ stderr,+ deps,+ ).then((status) => {+ finished = true;+ return status;+ });+ await publicationStarted;+ expect(finished).toBe(false);+ expect(listeners.size).toBe(2);+ expect(events).toEqual(+ interactive+ ? ["restored terminal", `aborted ${signal}`]+ : [`aborted ${signal}`],+ );+ expect(captured.text()).not.toContain(expectedMessage);+ expect(stdout.text()).toBe("");+ finishRecovery();++ expect(await publishing).toBe(expectedCode);+ expect(events).toEqual(+ interactive+ ? [+ "restored terminal",+ `aborted ${signal}`,+ "recovered created issues",+ ]+ : [`aborted ${signal}`, "recovered created issues"],+ );+ expect(captured.text()).toContain(expectedMessage);+ expect(captured.text()).toContain("recover it before retrying");+ expect(stdout.text()).toBe("");+ expect(removed).toEqual(["SIGINT", "SIGTERM"]);+ expect(listeners.size).toBe(0);+ if (interactive) {+ expect(captured.text()).toContain("\u001B[?25h\u001B[?1049l");+ } else {+ expect(captured.text()).not.toContain("\u001B");+ }+ }+ }+ });++ test("falls back to plain progress if the full-screen dashboard cannot start", async () => {+ const stdout = capture();+ const output: string[] = [];+ let failed = false;+ const stderr = {+ isTTY: true,+ write(chunk: string | Uint8Array): boolean {+ const value = chunk.toString();+ if (!failed && value.includes("\u001B[?1049h")) {+ failed = true;+ throw new Error("The terminal cannot enter full-screen mode.");+ }+ output.push(value);+ return true;+ },+ };+ const deps = dependencies();+ deps.publishScan = async (_scanDirectory, options) => {+ options.onProgress?.({ type: "started", scanId: "scan-123", total: 1 });+ options.onProgress?.({+ type: "completed",+ created: 1,+ failed: 0,+ total: 1,+ });+ return publicationResult();+ };++ expect(+ await main(+ ["publish", "scan", "completed-scan", ...DESTINATION_OPTIONS, "--json"],+ stdout.stream,+ stderr,+ deps,+ ),+ ).toBe(0);++ expect(failed).toBe(true);+ expect(output.join("")).toContain("Publishing 1 finding to Linear.");+ expect(output.join("")).toContain("Published 1/1 finding.");+ expect(JSON.parse(stdout.text())).toEqual(publicationResult());});test("omits deleted, replaced, and linked scan directories without changing valid scan order", async () => {@@ -382,7 +1535,10 @@ describe("publish scan", () => {]);expect(publishedDirectory).toBe(selectedDirectory);expect(JSON.parse(stdout.text())).toEqual(publicationResult());- expect(stderr.text()).toBe("");+ expect(stripVTControlCharacters(stderr.text())).toContain(+ "CODEX SECURITY · PUBLISH · selected-scan",+ );+ expect(stderr.text()).toContain("\u001B[?25h\u001B[?1049l");});test("requires an interactive terminal when no scan directory is supplied", async () => {@@ -634,8 +1790,7 @@ describe("publish scan", () => {const stdout = capture();const stderr = capture();let dryRun: boolean | undefined;- const signals = new FakeSignals();- const deps = dependencies({ signals });+ const deps = dependencies();deps.publishScan = async (_scanDirectory, options) => {dryRun = options.dryRun;return { ...publicationResult(), dryRun: true, issues: [] };@@ -664,7 +1819,6 @@ describe("publish scan", () => {issues: [],});expect(stderr.text()).toBe("");- expect(signals.listeners.size).toBe(0);});test("surfaces receipt warnings without changing published issues or JSON output", async () => {diff --git a/sdk/typescript/tests-ts/publication-integration.test.ts b/sdk/typescript/tests-ts/publication-integration.test.tsindex 1b43b675b..816dc69ba 100644--- a/sdk/typescript/tests-ts/publication-integration.test.ts+++ b/sdk/typescript/tests-ts/publication-integration.test.ts@@ -432,6 +432,7 @@ describe("database-backed Linear publication integration", () => {failed: 0,total: 23,});+ expect(stderr.text()).toContain("Published 23/23 findings.");expect(await artifactDigests(completed.scanDirectory)).toEqual(sealed);expect(await readFile(handoffFile).then(@@ -526,6 +527,7 @@ describe("database-backed Linear publication integration", () => {expect(JSON.parse(await readFile(receiptPath(completed), "utf8"))).toEqual(result,);+ expect(stderr.text()).toContain("Published 21/22 findings (1 failed).");expect(await artifactDigests(completed.scanDirectory)).toEqual(sealed);});diff --git a/sdk/typescript/tests-ts/scan-dashboard.test.ts b/sdk/typescript/tests-ts/scan-dashboard.test.tsindex 6b1a73bcc..012afc595 100644--- a/sdk/typescript/tests-ts/scan-dashboard.test.ts+++ b/sdk/typescript/tests-ts/scan-dashboard.test.ts@@ -40,6 +40,45 @@ class DashboardTestInput extends EventEmitter {}describe("live scan dashboard", () => {+ test("renders publication progress without scan-only inventory and cost fields", () => {+ const stderr = capture(true);+ const dashboard = new ScanDashboard(+ { ...stderr.stream, columns: 100, rows: 18 },+ {+ repository: "/synthetic/payments-api",+ presentation: "publication",+ color: false,+ clock: fakeClock(),+ },+ );++ dashboard.setStage("Connecting to Linear");+ dashboard.start();+ let text = stripVTControlCharacters(stderr.text());+ expect(text).toContain("CODEX SECURITY · PUBLISH · payments-api");+ expect(text).toContain("Waiting for publication activity");+ expect(text).toContain("FINDINGS waiting for findings");+ expect(text).not.toContain("FILES");+ expect(text).not.toContain("TOKENS");+ expect(text).not.toContain("COST");++ dashboard.setPublicationProgress(2, 5);+ dashboard.setStage("Publishing findings · 2/5");+ dashboard.record({+ id: "publication-reasoning",+ kind: "reasoning",+ status: "completed",+ description: "Preparing the next Linear issue.",+ paths: [],+ });+ text = stripVTControlCharacters(stderr.text());+ expect(text).toContain("FINDINGS 2 / 5 processed");+ expect(text).toContain("Publishing findings · 2/5");+ expect(text).toContain("Preparing the next Linear issue.");+ dashboard.stop();+ expect(stderr.text()).toContain("\u001B[?25h\u001B[?1049l");+ });+test("restores terminal state when dashboard initialization fails", () => {const input = new DashboardTestInput();const output: string[] = [];