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 a feedback command (#854)
ianw-oai094f643d9e72
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex f12ab1062..4c7de4b89 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -1165,6 +1165,25 @@ once before they can be reused.Pass `signal` to cancel any classification operation. Keep human overrides in thecalling workflow or issue tracker; assessments remain separate recommendations.+### Feedback++Send a problem report to OpenAI and share the returned feedback ID with support:++```sh+codex-security feedback --reason "The scan stopped before it finished"+codex-security feedback SCAN_ID --reason "The scan stopped before it finished" --include-logs+```++Without an ID, `feedback` selects the most recently started scan in the current+repository, including active or failed scans. If there are no saved scans, it sends+a general report. The report includes your description, version details, and the selected+scan and session IDs. Add `--json` for structured output.++Logs are off by default. `--include-logs` uploads Codex diagnostics and saved scan+and worker activity. These can contain source code, prompts, findings, tool+output, and other sensitive data. Only include logs you can share with OpenAI.+The command uses Codex's feedback service and respects `feedback.enabled = false`.+### Scan history and rerunsCommands default to the current repository. Select scans by full ID or adiff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjsindex 7cb1eb76d..a1f0a601d 100644--- a/sdk/typescript/scripts/check-package.mjs+++ b/sdk/typescript/scripts/check-package.mjs@@ -184,6 +184,7 @@ const distFiles = new Set("custom-publish","deep-progress","errors",+ "feedback","finding-catalogue","findings-import","github",diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 5aaea2107..f5192f289 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -169,7 +169,8 @@ import {CODEX_SECURITY_THREAD_SOURCES,type CodexSecurityThreadSource,} from "./thread-source.js";-import { readScanLogs } from "./scan-logs.js";+import { readSavedScanLogs, type ScanLogSource } from "./scan-logs.js";+import { sendFeedback } from "./feedback.js";import {renderScanHistory,type HistoryCommand,@@ -1160,6 +1161,7 @@ interface CliDependencies {publishFindingsCsvToCloud?: typeof publishFindingsCsvToCloud;publishScanToCloud?: typeof publishScanToCloud;publishScanToCustom?: typeof publishScanToCustom;+ sendFeedback?: typeof sendFeedback;confirmPatchReview?: (question: string) => Promise<boolean>;patchEditor?: (repository: string,@@ -1988,35 +1990,11 @@ export async function main(if (scanId === undefined) return;return await history(["get-scan", "--scan-id", scanId],- async (value) => {- const scan = value["scan"] as {- scanId: string;- continuationThreadId?: string;- mode?: string;- progress?: { status?: string; updatedAt?: string };- scanDir?: string;- };- const threadId = scan.continuationThreadId;- if (!threadId) {- throw new CodexSecurityError(- `No session is associated with scan ${scan.scanId}.`,- );- }- return (await readScanLogs({- scanId: scan.scanId,- threadId,- codexHome: codexSecurityCredentialHome(dependencies.environment),- scanDirectory: scan.mode === "deep" ? scan.scanDir : undefined,- completedAt:- scan.progress?.status === "running"- ? null- : scan.progress?.status === "complete" ||- scan.progress?.status === "failed" ||- scan.progress?.status === "canceled"- ? scan.progress.updatedAt ?? ""- : "",- })) as unknown as JsonObject;- },+ async (value) =>+ (await readSavedScanLogs(+ value["scan"] as ScanLogSource,+ codexSecurityCredentialHome(dependencies.environment),+ )) as unknown as JsonObject,);},})@@ -4882,6 +4860,80 @@ export async function main(}},})+ .command("feedback", {+ description: "Send feedback to OpenAI and return a feedback ID.",+ destructive: true,+ mcp: false,+ args: z.object({+ scanId: z+ .string()+ .min(1)+ .optional()+ .describe(+ "Scan ID or unique prefix (default: most recently started scan in the current repository).",+ ),+ }),+ options: z.object({+ reason: z.string().trim().min(1).describe("Describe the problem."),+ includeLogs: z+ .boolean()+ .default(false)+ .describe(+ "Upload diagnostic logs, including scan and worker conversations and tool output. Defaults to off.",+ ),+ }),+ output: z.object({+ feedbackId: z.string(),+ scanId: z.string().nullable(),+ includedLogs: z.boolean(),+ }),+ async run({ args, options }) {+ let scanId = args.scanId;+ if (scanId === undefined) {+ const value = await history([+ "list-scans",+ "--repository",+ dependencies.currentDirectory(),+ ]);+ const scans = value["scans"] as {+ scanId: string;+ startedAt: string;+ }[];+ scanId = scans.toSorted((a, b) =>+ b.startedAt.localeCompare(a.startedAt),+ )[0]?.scanId;+ }+ const scan =+ scanId === undefined+ ? undefined+ : ((await history(["get-scan", "--scan-id", scanId]))[+ "scan"+ ] as ScanLogSource);+ const controller = new AbortController();+ const onInterrupt = () => controller.abort("SIGINT");+ const onTerminate = () => controller.abort("SIGTERM");+ dependencies.addSignalListener("SIGINT", onInterrupt);+ dependencies.addSignalListener("SIGTERM", onTerminate);+ try {+ return await (dependencies.sendFeedback ?? sendFeedback)({+ ...options,+ scan,+ environment: dependencies.environment,+ workingDirectory: dependencies.currentDirectory(),+ signal: controller.signal,+ });+ } catch (error) {+ if (controller.signal.aborted) {+ exitCode = controller.signal.reason === "SIGINT" ? 130 : 143;+ errorOutput.write("codex-security: Feedback upload canceled.\n");+ }+ throw error;+ } finally {+ dependencies.removeSignalListener("SIGINT", onInterrupt);+ dependencies.removeSignalListener("SIGTERM", onTerminate);+ }+ },+ }).command("info", {description: "Show read-only SDK and bundled-plugin metadata.",mcp: {@@ -5335,6 +5387,7 @@ function validateCliArguments("login","logout","serve",+ "feedback","info",].includes(command)) {diff --git a/sdk/typescript/src/feedback.ts b/sdk/typescript/src/feedback.tsnew file mode 100644index 000000000..8d5ad22e6--- /dev/null+++ b/sdk/typescript/src/feedback.ts@@ -0,0 +1,161 @@+import {+ spawn,+ type ChildProcessWithoutNullStreams,+ type SpawnOptionsWithoutStdio,+} from "node:child_process";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { createInterface } from "node:readline";+import { readCodexHomeConfig } from "./auth.js";+import { CodexSecurityError } from "./errors.js";+import {+ codexSecurityCredentialHome,+ executablePathForSpawn,+ resolveCodexCommand,+} from "./runtime.js";+import { readSavedScanLogs, type ScanLogSource } from "./scan-logs.js";+import {+ BUNDLED_PLUGIN_VERSION,+ CODEX_EXECUTABLE_VERSION,+ CODEX_SDK_VERSION,+ VERSION,+} from "./version.js";++interface FeedbackOptions {+ reason: string;+ includeLogs: boolean;+ scan?: ScanLogSource;+ environment: NodeJS.ProcessEnv;+ workingDirectory: string;+ signal?: AbortSignal;+}++type StartCodex = (+ command: string,+ args: readonly string[],+ options: SpawnOptionsWithoutStdio & { stdio: ["pipe", "pipe", "pipe"] },+) => ChildProcessWithoutNullStreams;++export async function sendFeedback(+ options: FeedbackOptions,+ startCodex: StartCodex = spawn,+) {+ const { scan, environment, includeLogs } = options;+ options.signal?.throwIfAborted();+ const codexHome = codexSecurityCredentialHome(environment);+ const config = await readCodexHomeConfig(environment);+ const feedback = config["feedback"] as { enabled?: boolean } | undefined;+ if (feedback?.enabled === false) {+ throw new CodexSecurityError(+ "Sending feedback is disabled by configuration.",+ );+ }++ let directory: string | undefined;+ try {+ const extraLogFiles: string[] = [];+ if (includeLogs && scan !== undefined) {+ const logs = await readSavedScanLogs(scan, codexHome);+ directory = await mkdtemp(join(tmpdir(), "codex-security-feedback-"));+ const path = join(directory, "scan-logs.json");+ await writeFile(path, JSON.stringify(logs), { mode: 0o600 });+ extraLogFiles.push(path);+ }++ const command = resolveCodexCommand(environment);+ const child = startCodex(+ executablePathForSpawn(command.command),+ ["app-server", "--stdio"],+ {+ cwd: options.workingDirectory,+ env: { ...environment, CODEX_HOME: codexHome },+ stdio: ["pipe", "pipe", "pipe"],+ windowsHide: true,+ signal: options.signal,+ },+ );+ const uploaded = Promise.withResolvers<string>();+ const closed = new Promise<void>((resolve) => {+ child.once("close", () => {+ uploaded.reject(+ new CodexSecurityError("Codex exited before feedback was uploaded."),+ );+ resolve();+ });+ });+ child.once("error", uploaded.reject);+ child.stdin.on("error", uploaded.reject);+ child.stderr.resume();+ const send = (message: object) =>+ child.stdin.write(`${JSON.stringify(message)}\n`);+ const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });+ lines.on("line", (line) => {+ try {+ const message = JSON.parse(line) as {+ id?: number;+ method?: string;+ error?: { message: string };+ result?: { threadId?: string };+ };+ if (message.method !== undefined || message.id === undefined) return;+ if (message.error) throw new CodexSecurityError(message.error.message);+ if (message.id === 1) {+ send({ method: "initialized" });+ send({+ id: 2,+ method: "feedback/upload",+ params: {+ classification: "bug",+ reason: options.reason,+ threadId: scan?.continuationThreadId,+ includeLogs,+ extraLogFiles,+ tags: {+ codex_security_version: VERSION,+ codex_security_plugin_version: BUNDLED_PLUGIN_VERSION,+ codex_security_codex_version: CODEX_EXECUTABLE_VERSION,+ codex_security_sdk_version: CODEX_SDK_VERSION,+ ...(scan === undefined+ ? {}+ : { codex_security_scan_id: scan.scanId }),+ },+ },+ });+ } else if (message.id === 2) {+ const feedbackId = message.result?.threadId;+ if (!feedbackId)+ throw new CodexSecurityError("Codex did not return a feedback ID.");+ uploaded.resolve(feedbackId);+ }+ } catch (error) {+ uploaded.reject(error);+ }+ });+ try {+ send({+ id: 1,+ method: "initialize",+ params: { clientInfo: { name: "codex-security", version: VERSION } },+ });+ return {+ feedbackId: await uploaded.promise,+ scanId: scan?.scanId ?? null,+ includedLogs: includeLogs,+ };+ } finally {+ lines.close();+ child.stdin.end();+ child.kill();+ const timer = setTimeout(() => child.kill("SIGKILL"), 1_000);+ try {+ await closed;+ } finally {+ clearTimeout(timer);+ }+ }+ } finally {+ if (directory !== undefined)+ await rm(directory, { recursive: true, force: true });+ }+}diff --git a/sdk/typescript/src/scan-logs.ts b/sdk/typescript/src/scan-logs.tsindex 97d6a7edb..40def7bb2 100644--- a/sdk/typescript/src/scan-logs.ts+++ b/sdk/typescript/src/scan-logs.ts@@ -3,6 +3,7 @@ import { basename, dirname, join, relative } from "node:path";import { createInterface } from "node:readline";import { sessionFiles } from "./cost.js";import { CodexSecurityError } from "./errors.js";+import type { JsonObject } from "./config.js";import {isScanArtifactDirectory,sessionParentThreadId,@@ -17,6 +18,37 @@ interface ScanLogOptions {completedAt?: string | null;}+export type ScanLogSource = JsonObject & {+ scanId: string;+ continuationThreadId?: string;+ mode?: string;+ scanDir?: string;+ progress?: { status?: string; updatedAt?: string };+};++export function readSavedScanLogs(scan: ScanLogSource, codexHome: string) {+ const threadId = scan.continuationThreadId;+ if (!threadId) {+ throw new CodexSecurityError(+ `No session is associated with scan ${scan.scanId}.`,+ );+ }+ return readScanLogs({+ scanId: scan.scanId,+ threadId,+ codexHome,+ scanDirectory: scan.mode === "deep" ? scan.scanDir : undefined,+ completedAt:+ scan.progress?.status === "running"+ ? null+ : scan.progress?.status === "complete" ||+ scan.progress?.status === "failed" ||+ scan.progress?.status === "canceled"+ ? scan.progress.updatedAt ?? ""+ : "",+ });+}+interface SessionLog {threadId: string;parentThreadId: string | null;diff --git a/sdk/typescript/tests-ts/cli-feedback.test.ts b/sdk/typescript/tests-ts/cli-feedback.test.tsnew file mode 100644index 000000000..e66c7975f--- /dev/null+++ b/sdk/typescript/tests-ts/cli-feedback.test.ts@@ -0,0 +1,215 @@+import { spawnSync } from "node:child_process";+import { mkdir, mkdtemp, realpath, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { expect, mock, test } from "bun:test";+import { main } from "../src/cli.js";+import type { JsonObject } from "../src/config.js";+import { resolvePluginPython, runWorkbench } from "../src/runtime.js";+import { capture, dependencies, FakeSignals } from "./cli-fixtures.js";+import { PLUGIN_ROOT } from "./plugin-root.js";++async function run(args: string[], deps = dependencies()) {+ const stdout = capture();+ const stderr = capture();+ const code = await main(+ ["feedback", ...args],+ stdout.stream,+ stderr.stream,+ deps,+ );+ return { code, stdout: stdout.text(), stderr: stderr.text() };+}++test("feedback selects the newest saved scan when an older scan is still running", async () => {+ const root = await realpath(+ await mkdtemp(join(tmpdir(), "feedback-history-")),+ );+ try {+ const python = await resolvePluginPython();+ const repository = join(root, "repository");+ const environment = {+ PATH: process.env["PATH"],+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ };+ const workbench = (args: readonly string[]) =>+ runWorkbench({ python, pluginRoot: PLUGIN_ROOT, environment }, args);+ const scans: { scanId: string; status: string; startedAt: string }[] = [];+ for (const [index, status] of ["running", "failed", "running"].entries()) {+ const target = index === 2 ? join(root, "other-repository") : repository;+ const scanDir = join(root, `scan-${index}`);+ await mkdir(target, { recursive: true });+ await mkdir(scanDir, { mode: 0o700 });+ const registered = await workbench([+ "register-cli-scan",+ "--repository",+ target,+ "--scan-dir",+ scanDir,+ "--recipe-json",+ JSON.stringify({+ config: {},+ mode: "standard",+ repository: target,+ target: { kind: "repository", paths: [] },+ }),+ ]);+ scans.push({+ scanId: registered["scanId"] as string,+ status,+ startedAt: `2026-01-0${index + 1}T00:00:00Z`,+ });+ }+ const seeded = spawnSync(+ python,+ [+ "-c",+ `import json, sqlite3, sys+with sqlite3.connect(sys.argv[1]) as connection:+ for scan in json.loads(sys.argv[2]):+ connection.execute("UPDATE scans SET started_at = ?, status = ? WHERE id = ?", (scan["startedAt"], scan["status"], scan["scanId"]))`,+ join(environment.CODEX_SECURITY_STATE_DIR, "workbench.sqlite3"),+ JSON.stringify(scans),+ ],+ { encoding: "utf8" },+ );+ expect(seeded.stderr).toBe("");+ expect(seeded.status).toBe(0);+ const history = await workbench(["list-scans", "--repository", repository]);+ expect(+ (history["scans"] as JsonObject[]).map((scan) => scan["scanId"]),+ ).toEqual([scans[0]!.scanId, scans[1]!.scanId]);+ const deps = dependencies({+ currentDirectory: repository,+ environment,+ onWorkbench: workbench,+ });+ deps.sendFeedback = async ({ scan }) => {+ expect(scan?.scanId).toBe(scans[1]!.scanId);+ return {+ feedbackId: "feedback-1",+ scanId: scan!.scanId,+ includedLogs: true,+ };+ };+ const result = await run(+ ["--reason", "Scan stopped", "--include-logs", "--json"],+ deps,+ );+ expect(result.code).toBe(0);+ expect(result.stderr).toBe("");+ expect(JSON.parse(result.stdout).scanId).toBe(scans[1]!.scanId);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("feedback selects a scan prefix", async () => {+ const calls: string[][] = [];+ const scan = { scanId: "scan-prefix-full", progress: { status: "failed" } };+ const deps = dependencies({+ onWorkbench: (args): JsonObject => {+ calls.push([...args]);+ return { scan };+ },+ });+ const report = {+ feedbackId: "feedback-1",+ scanId: scan.scanId,+ includedLogs: true,+ };+ deps.sendFeedback = async (options) => {+ expect(options).toMatchObject({+ reason: "Scan stopped",+ includeLogs: true,+ scan,+ });+ return report;+ };+ const result = await run(+ ["scan-pre", "--reason", "Scan stopped", "--include-logs", "--json"],+ deps,+ );+ expect(result.code).toBe(0);+ expect(result.stderr).toBe("");+ expect(JSON.parse(result.stdout)).toEqual(report);+ expect(calls).toEqual([["get-scan", "--scan-id", "scan-pre"]]);+});++test("feedback without saved scans sends a general report with logs off", async () => {+ const deps = dependencies();+ deps.sendFeedback = async (options) => {+ expect(options.scan).toBeUndefined();+ expect(options.includeLogs).toBe(false);+ return { feedbackId: "feedback-2", scanId: null, includedLogs: false };+ };+ const result = await run(["--reason", "Install failed", "--json"], deps);+ expect(result.code).toBe(0);+ expect(JSON.parse(result.stdout).feedbackId).toBe("feedback-2");+});++test("Ctrl-C cancels feedback and removes signal listeners", async () => {+ const signals = new FakeSignals();+ const deps = dependencies({ signals });+ deps.sendFeedback = async ({ signal }) => {+ signals.emit("SIGINT");+ signal!.throwIfAborted();+ throw new Error("Must be canceled");+ };+ const result = await run(["--reason", "Problem"], deps);+ expect(result.code).toBe(130);+ expect(result.stderr).toContain("Feedback upload canceled");+ expect(signals.listeners.get("SIGINT")?.size).toBe(0);+ expect(signals.listeners.get("SIGTERM")?.size).toBe(0);+});++for (const args of [+ [],+ ["--reason", " "],+ ["extra", "scan", "--reason", "Problem"],+]) {+ test(`feedback rejects invalid arguments ${JSON.stringify(args)}`, async () => {+ const deps = dependencies({+ onWorkbench: () => {+ throw new Error("Must not read scans");+ },+ });+ deps.sendFeedback = async () => {+ throw new Error("Must not upload");+ };+ const result = await run(args, deps);+ expect(result.code).toBe(2);+ expect(result.stdout).toBe("");+ expect(result.stderr).not.toContain("Must not");+ });+}++for (const missingScan of [false, true]) {+ test(`feedback reports ${missingScan ? "scan lookup" : "upload"} failures without a success ID`, async () => {+ const deps = dependencies({+ onWorkbench: () => {+ if (missingScan) throw new Error("Scan not found");+ return { scans: [] };+ },+ });+ const upload = mock(async () => {+ throw new Error("Upload failed");+ });+ deps.sendFeedback = upload;+ const result = await run(+ [+ ...(missingScan ? ["unknown-scan"] : []),+ "--reason",+ "Problem",+ "--json",+ ],+ deps,+ );+ expect(result.code).toBe(2);+ expect(result.stdout).toBe("");+ expect(upload).toHaveBeenCalledTimes(missingScan ? 0 : 1);+ expect(result.stderr).toContain(+ missingScan ? "Scan not found" : "Upload failed",+ );+ });+}diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex ff8e6438b..0817379fe 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -269,6 +269,7 @@ describe("CLI", () => {["patch"],["login"],["logout"],+ ["feedback"],["info"],["install-hook"],["scans", "list"],diff --git a/sdk/typescript/tests-ts/feedback.test.ts b/sdk/typescript/tests-ts/feedback.test.tsnew file mode 100644index 000000000..b3246b44b--- /dev/null+++ b/sdk/typescript/tests-ts/feedback.test.ts@@ -0,0 +1,200 @@+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { existsSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, toNamespacedPath } from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, expect, test } from "bun:test";+import { sendFeedback } from "../src/feedback.js";+import { codexSecurityCredentialHome } from "../src/runtime.js";+import { VERSION, BUNDLED_PLUGIN_VERSION } from "../src/version.js";++const fixture = fileURLToPath(+ new URL("fixtures/feedback.mjs", import.meta.url),+);+const directories: string[] = [];+afterEach(async () => {+ for (const directory of directories.splice(0))+ await rm(directory, { recursive: true, force: true });+});++async function setup() {+ const directory = await mkdtemp(join(tmpdir(), "feedback-test-"));+ directories.push(directory);+ const environment = {+ CODEX_HOME: join(directory, "ambient"),+ CODEX_SECURITY_STATE_DIR: join(directory, "state"),+ CODEX_CLI_PATH: process.execPath,+ FEEDBACK_REQUEST_FILE: join(directory, "requests.json"),+ FEEDBACK_SCENARIO: "success",+ };+ const home = codexSecurityCredentialHome(environment);+ await mkdir(join(home, "sessions"), { recursive: true });+ const root = { type: "session_meta", payload: { id: "thread-1" } };+ const worker = {+ type: "session_meta",+ payload: {+ id: "worker-1",+ source: { subagent: { thread_spawn: { parent_thread_id: "thread-1" } } },+ },+ };+ await writeFile(+ join(home, "sessions", "rollout-root.jsonl"),+ JSON.stringify(root),+ );+ await writeFile(+ join(home, "sessions", "rollout-worker.jsonl"),+ JSON.stringify(worker),+ );+ await writeFile(+ join(home, "sessions", "rollout-unrelated.jsonl"),+ JSON.stringify({ type: "session_meta", payload: { id: "unrelated" } }),+ );+ let child: ChildProcessWithoutNullStreams | undefined;+ const startCodex: NonNullable<Parameters<typeof sendFeedback>[1]> = (+ command,+ args,+ options,+ ) => {+ expect(command).toBe(toNamespacedPath(process.execPath));+ expect(args).toEqual(["app-server", "--stdio"]);+ expect(options.env?.["CODEX_HOME"]).toBe(home);+ child = spawn(process.execPath, [fixture], options);+ return child;+ };+ return {+ directory,+ environment,+ home,+ startCodex,+ options: {+ reason: "Scan stopped",+ includeLogs: true,+ scan: { scanId: "scan-1", continuationThreadId: "thread-1" },+ environment,+ workingDirectory: directory,+ },+ transcript: async () =>+ JSON.parse(await readFile(environment.FEEDBACK_REQUEST_FILE, "utf8")),+ expectClosed: () =>+ expect(child!.exitCode !== null || child!.signalCode !== null).toBe(true),+ };+}++test("uploads selected scan and worker logs through Codex and removes temporary files", async () => {+ const context = await setup();+ expect(await sendFeedback(context.options, context.startCodex)).toEqual({+ feedbackId: "feedback-1",+ scanId: "scan-1",+ includedLogs: true,+ });+ const { requests, attachments } = await context.transcript();+ expect(requests.map((request: { method: string }) => request.method)).toEqual(+ ["initialize", "initialized", "feedback/upload"],+ );+ expect(requests[2].params).toMatchObject({+ classification: "bug",+ reason: "Scan stopped",+ threadId: "thread-1",+ includeLogs: true,+ tags: {+ codex_security_version: VERSION,+ codex_security_plugin_version: BUNDLED_PLUGIN_VERSION,+ codex_security_scan_id: "scan-1",+ },+ });+ expect(attachments).toHaveLength(1);+ expect(+ JSON.parse(attachments[0].content).sessions.map(+ (session: { threadId: string }) => session.threadId,+ ),+ ).toEqual(["thread-1", "worker-1"]);+ expect(existsSync(attachments[0].path)).toBe(false);+ context.expectClosed();+});++test("without log opt-in, does not read or attach saved sessions", async () => {+ const context = await setup();+ await rm(join(context.home, "sessions"), { recursive: true });+ expect(+ (+ await sendFeedback(+ { ...context.options, includeLogs: false },+ context.startCodex,+ )+ ).includedLogs,+ ).toBe(false);+ const { requests, attachments } = await context.transcript();+ expect(requests[2].params.includeLogs).toBe(false);+ expect(requests[2].params.extraLogFiles).toEqual([]);+ expect(attachments).toEqual([]);+});++for (const [scenario, message] of [+ ["error", "Upload failed"],+ ["exit", "Codex exited before feedback was uploaded"],+ ["missing-id", "Codex did not return a feedback ID"],+ ["malformed", "JSON"],+]) {+ test(`upload ${scenario} leaves no temporary logs or running child`, async () => {+ const context = await setup();+ context.environment.FEEDBACK_SCENARIO = scenario!;+ await expect(+ sendFeedback(context.options, context.startCodex),+ ).rejects.toThrow(message);+ const { attachments } = await context.transcript();+ expect(existsSync(attachments[0].path)).toBe(false);+ context.expectClosed();+ });+}++test("respects disabled feedback without starting Codex", async () => {+ const context = await setup();+ await mkdir(context.environment.CODEX_HOME);+ await writeFile(+ join(context.environment.CODEX_HOME, "config.toml"),+ "[feedback]\nenabled = false\n",+ );+ await expect(+ sendFeedback(context.options, () => {+ throw new Error("Must not start Codex");+ }),+ ).rejects.toThrow("disabled by configuration");+});++test("reports missing session logs without sending an incomplete log report", async () => {+ const context = await setup();+ await rm(join(context.home, "sessions"), { recursive: true });+ await expect(+ sendFeedback(context.options, () => {+ throw new Error("Must not start Codex");+ }),+ ).rejects.toThrow("No saved session logs");+});++test("reports failure to start Codex", async () => {+ const context = await setup();+ await expect(+ sendFeedback(+ { ...context.options, includeLogs: false },+ (_command, _args, options) =>+ spawn(join(context.directory, "missing-executable"), [], options),+ ),+ ).rejects.toThrow("ENOENT");+});++test("cancellation stops the Codex process", async () => {+ const context = await setup();+ const controller = new AbortController();+ await expect(+ sendFeedback(+ { ...context.options, signal: controller.signal },+ (...args) => {+ const child = context.startCodex(...args);+ child.stdout.once("data", () => controller.abort());+ return child;+ },+ ),+ ).rejects.toThrow("abort");+ context.expectClosed();+});diff --git a/sdk/typescript/tests-ts/fixtures/feedback.mjs b/sdk/typescript/tests-ts/fixtures/feedback.mjsnew file mode 100644index 000000000..09d025c95--- /dev/null+++ b/sdk/typescript/tests-ts/fixtures/feedback.mjs@@ -0,0 +1,48 @@+import { createInterface } from "node:readline";+import { readFile, writeFile } from "node:fs/promises";++const requests = [];+for await (const line of createInterface({ input: process.stdin })) {+ const request = JSON.parse(line);+ requests.push(request);+ if (request.method === "initialize") {+ console.log(JSON.stringify({ id: request.id, result: {} }));+ } else if (request.method === "feedback/upload") {+ const attachments = await Promise.all(+ request.params.extraLogFiles.map(async (path) => ({+ path,+ content: await readFile(path, "utf8"),+ })),+ );+ await writeFile(+ process.env.FEEDBACK_REQUEST_FILE,+ JSON.stringify({ requests, attachments }),+ );+ switch (process.env.FEEDBACK_SCENARIO) {+ case "error":+ console.log(+ JSON.stringify({+ id: request.id,+ error: { message: "Upload failed" },+ }),+ );+ break;+ case "exit":+ process.exit(1);+ break;+ case "missing-id":+ console.log(JSON.stringify({ id: request.id, result: {} }));+ break;+ case "malformed":+ console.log("not JSON");+ break;+ default:+ console.log(+ JSON.stringify({+ id: request.id,+ result: { threadId: "feedback-1" },+ }),+ );+ }+ }+}