Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

fix: stream workbench payloads through stdin (#587)

faizan-oai1bf8c8e6e0bf
diff --git a/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-000 b/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-000
index 4f8c6872d..0d8b425ad 100644
Binary files a/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-000 and b/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-000 differ
diff --git a/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-001 b/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-001
index 14aedb294..d43827a78 100644
Binary files a/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-001 and b/sdk/typescript/_bundled_plugin/mcp/server.mjs.br.part-001 differ
diff --git a/sdk/typescript/_bundled_plugin/scripts/deep_scan_workbench.py b/sdk/typescript/_bundled_plugin/scripts/deep_scan_workbench.py
index 6a486ba72..4aabe29ce 100644
--- a/sdk/typescript/_bundled_plugin/scripts/deep_scan_workbench.py
+++ b/sdk/typescript/_bundled_plugin/scripts/deep_scan_workbench.py
@@ -26,7 +26,7 @@ from workbench_target import (
git_revision,
worktree_content_digest,
)
-from workbench_validation import optional_text, require_uuid, user_text
+from workbench_validation import optional_text, require_uuid, user_context_argument
DEEP_SCAN_WORKER_KINDS = ("setup", "discovery", "dedup")
DEEP_SCAN_WORKER_STATUSES = ("queued", "running", "succeeded", "failed", "canceled")
@@ -48,7 +48,9 @@ def register_subcommands(subparsers: Any, positive_int: Callable[[str], int]) ->
begin_target.add_argument("--scan-id")
begin_target.add_argument("--target-path")
begin_deep_scan.add_argument("--scope", default=".")
- begin_deep_scan.add_argument("--user-context")
+ begin_user_context = begin_deep_scan.add_mutually_exclusive_group()
+ begin_user_context.add_argument("--user-context")
+ begin_user_context.add_argument("--user-context-stdin", action="store_true")
begin_deep_scan.add_argument("--scan-root")
begin_deep_scan.add_argument("--claim-token")
begin_deep_scan.add_argument("--model")
@@ -795,7 +797,7 @@ def begin_deep_scan_for_target(
if target_root == target or target in target_root.parents:
raise SystemExit("The scan artifact directory must be outside the selected target.")
target_root.mkdir(parents=True, exist_ok=True)
- user_context = user_text(args.user_context)
+ user_context = user_context_argument(args)
model = optional_text(args.model, maximum=200)
reasoning_effort = optional_text(args.reasoning_effort, maximum=32)
workspace_id = str(uuid.uuid4())
@@ -884,7 +886,7 @@ def begin_deep_scan(connection: sqlite3.Connection, args: argparse.Namespace) ->
if thread_id is None:
raise SystemExit("thread-id is required.")
if args.scan_id:
- if args.user_context is not None or args.scope != ".":
+ if args.user_context is not None or args.user_context_stdin or args.scope != ".":
raise SystemExit("scan-id cannot be combined with target setup fields.")
return begin_deep_scan_for_scan(connection, args.scan_id, thread_id, args)
if args.claim_token is not None:
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py b/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py
index 2fc1c8f86..a3e14f7e7 100644
--- a/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py
+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_cli.py
@@ -24,6 +24,12 @@ from workbench_constants import (
)
+def add_user_context(parser: argparse.ArgumentParser, *, required: bool = False) -> None:
+ context = parser.add_mutually_exclusive_group(required=required)
+ context.add_argument("--user-context")
+ context.add_argument("--user-context-stdin", action="store_true")
+
+
def parse_args(description: str) -> argparse.Namespace:
parser = argparse.ArgumentParser(description=description)
subparsers = parser.add_subparsers(dest="command", required=True)
@@ -34,7 +40,7 @@ def parse_args(description: str) -> argparse.Namespace:
create_workspace.add_argument("--target-path")
create_workspace.add_argument("--target-title")
create_workspace.add_argument("--target-summary")
- create_workspace.add_argument("--user-context")
+ add_user_context(create_workspace)
create_workspace.add_argument("--scope")
create_workspace.add_argument("--mode", choices=MODES, default="standard")
create_workspace.add_argument("--diff-target-kind", choices=DIFF_TARGET_KINDS)
@@ -64,7 +70,7 @@ def parse_args(description: str) -> argparse.Namespace:
save_workspace.add_argument("--scope", required=True)
save_workspace.add_argument("--mode", choices=MODES, required=True)
save_workspace.add_argument("--target-summary")
- save_workspace.add_argument("--user-context")
+ add_user_context(save_workspace)
save_workspace.add_argument("--diff-target-kind", choices=DIFF_TARGET_KINDS)
save_workspace.add_argument("--diff-base-revision")
save_workspace.add_argument("--diff-head-revision")
@@ -82,7 +88,7 @@ def parse_args(description: str) -> argparse.Namespace:
start_prompt_only_scan.add_argument("--scope", required=True)
start_prompt_only_scan.add_argument("--mode", choices=("diff", "standard"), required=True)
start_prompt_only_scan.add_argument("--target-summary")
- start_prompt_only_scan.add_argument("--user-context")
+ add_user_context(start_prompt_only_scan)
start_prompt_only_scan.add_argument("--diff-target-kind", choices=DIFF_TARGET_KINDS)
start_prompt_only_scan.add_argument("--diff-base-revision")
start_prompt_only_scan.add_argument("--diff-head-revision")
@@ -96,7 +102,7 @@ def parse_args(description: str) -> argparse.Namespace:
start_headless_standard_scan.add_argument("--target-path", required=True)
start_headless_standard_scan.add_argument("--scope", required=True)
start_headless_standard_scan.add_argument("--target-summary")
- start_headless_standard_scan.add_argument("--user-context")
+ add_user_context(start_headless_standard_scan)
start_headless_standard_scan.add_argument("--scan-root")
start_headless_standard_scan.add_argument("--model")
start_headless_standard_scan.add_argument("--reasoning-effort")
@@ -119,7 +125,7 @@ def parse_args(description: str) -> argparse.Namespace:
update_scan_context = subparsers.add_parser("update-scan-context")
update_scan_context.add_argument("--scan-id", required=True)
- update_scan_context.add_argument("--user-context", required=True)
+ add_user_context(update_scan_context, required=True)
update_scan_context_owner = update_scan_context.add_mutually_exclusive_group(required=True)
update_scan_context_owner.add_argument("--workspace-id")
update_scan_context_owner.add_argument("--thread-id")
@@ -142,7 +148,9 @@ def parse_args(description: str) -> argparse.Namespace:
register_cli_scan = subparsers.add_parser("register-cli-scan")
register_cli_scan.add_argument("--scan-dir", required=True)
register_cli_scan.add_argument("--repository", required=True)
- register_cli_scan.add_argument("--recipe-json", required=True)
+ recipe = register_cli_scan.add_mutually_exclusive_group(required=True)
+ recipe.add_argument("--recipe-json")
+ recipe.add_argument("--recipe-json-stdin", action="store_true")
register_cli_scan.add_argument("--parent-scan-id")
register_cli_scan.add_argument("--archive-existing", action="store_true")
register_cli_scan.add_argument("--archived-scan-dir")
@@ -163,7 +171,9 @@ def parse_args(description: str) -> argparse.Namespace:
save_scan_comparison = subparsers.add_parser("save-scan-comparison")
save_scan_comparison.add_argument("--before-scan-id", required=True)
save_scan_comparison.add_argument("--after-scan-id", required=True)
- save_scan_comparison.add_argument("--matches-json", required=True)
+ matches = save_scan_comparison.add_mutually_exclusive_group(required=True)
+ matches.add_argument("--matches-json")
+ matches.add_argument("--matches-json-stdin", action="store_true")
list_global_findings = subparsers.add_parser("list-global-findings")
list_global_findings.add_argument("--query")
@@ -193,7 +203,9 @@ def parse_args(description: str) -> argparse.Namespace:
update_progress.add_argument("--phase-items-total", type=non_negative_int)
update_progress.add_argument("--phase-items-completed", type=non_negative_int)
update_progress.add_argument("--phase-progress-unit", choices=PHASE_PROGRESS_UNITS)
- update_progress.add_argument("--preflight-issues-json")
+ preflight_issues = update_progress.add_mutually_exclusive_group()
+ preflight_issues.add_argument("--preflight-issues-json")
+ preflight_issues.add_argument("--preflight-issues-json-stdin", action="store_true")
update_progress.add_argument("--review-items-total", type=non_negative_int)
update_progress.add_argument("--review-items-completed", type=non_negative_int)
update_progress.add_argument("--reportable-findings-count", type=non_negative_int)
@@ -309,13 +321,7 @@ def parse_args(description: str) -> argparse.Namespace:
publication.add_argument("--input-file", required=True)
subparsers.add_parser("database-info")
- arguments = sys.argv[1:]
- if "--user-context-stdin" in arguments:
- if arguments.count("--user-context-stdin") != 1 or "--user-context" in arguments:
- parser.error("pass exactly one user-context transport")
- index = arguments.index("--user-context-stdin")
- arguments[index : index + 1] = ["--user-context", sys.stdin.read()]
- return parser.parse_args(arguments)
+ return parser.parse_args()
def non_negative_int(value: str) -> int:
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
index dbf1320e1..746c75a82 100644
--- a/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_db.py
@@ -128,7 +128,7 @@ from workbench_validation import (
require_occurrence,
require_uuid,
sqlite_busy,
- user_text,
+ user_context_argument,
)
FINDING_ARTIFACT_DIRECTORIES_LIMIT = 80
@@ -715,7 +715,7 @@ def create_workspace(connection: sqlite3.Connection, args: argparse.Namespace) -
optional_text(args.target_summary, maximum=2400),
default_scope,
args.mode,
- user_text(args.user_context),
+ user_context_argument(args),
diff_target_kind,
diff_base_revision,
diff_head_revision,
@@ -774,7 +774,7 @@ def save_workspace(connection: sqlite3.Connection, args: argparse.Namespace) ->
target_summary,
scope,
args.mode,
- user_text(args.user_context),
+ user_context_argument(args),
diff_target["kind"] if diff_target else None,
diff_target["baseRevision"] if diff_target else None,
diff_target["headRevision"] if diff_target else None,
@@ -939,7 +939,7 @@ def _start_prompt_driven_scan(
target_path = str(target)
scope = inspected["scope"]
diff_target = inspected["diffTarget"]
- user_context = user_text(args.user_context)
+ user_context = user_context_argument(args)
target_summary = optional_text(args.target_summary, maximum=2400)
if diff_target is not None and not target_summary:
target_summary = diff_target_summary(diff_target)
@@ -1605,7 +1605,8 @@ def register_cli_scan(connection: sqlite3.Connection, args: argparse.Namespace)
if next(scan_dir.iterdir(), None) is not None:
raise SystemExit("The scan artifact directory must be empty before the scan starts.")
- recipe = parse_scan_recipe(args.recipe_json, repository)
+ recipe_json = sys.stdin.read() if args.recipe_json_stdin else args.recipe_json
+ recipe = parse_scan_recipe(recipe_json, repository)
requested_target = recipe["target"]
paths = requested_target["paths"]
scope = paths[0] if len(paths) == 1 else "."
@@ -3807,6 +3808,8 @@ def reject_non_finite_json(value: str) -> None:
def main() -> None:
+ # Workbench callers send UTF-8 even when Windows uses a legacy code page.
+ sys.stdin.reconfigure(encoding="utf-8")
args = parse_args(__doc__)
deep_scan.configure(
deep_scan.DeepScanDependencies(
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_progress.py b/sdk/typescript/_bundled_plugin/scripts/workbench_progress.py
index da0c1147c..fb1b5303c 100644
--- a/sdk/typescript/_bundled_plugin/scripts/workbench_progress.py
+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_progress.py
@@ -11,7 +11,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
from deep_scan_workbench import require_current_coordinator
from workbench.handoff import require_current_continuation
from workbench_constants import PHASES
-from workbench_validation import optional_text, require_uuid, user_text
+from workbench_validation import optional_text, require_uuid, user_context_argument
MAX_PREFLIGHT_ISSUES = 32
@@ -83,7 +83,7 @@ def update_context(
scan_context: Callable[[sqlite3.Connection, str], dict[str, Any]],
) -> dict[str, Any]:
scan_id = require_uuid(args.scan_id, "scan-id")
- context = user_text(args.user_context)
+ context = user_context_argument(args)
connection.execute("BEGIN IMMEDIATE")
try:
scan = require_scan(connection, scan_id)
@@ -164,7 +164,10 @@ def update_progress(
scan_id = require_uuid(args.scan_id, "scan-id")
model = optional_text(args.model, maximum=200)
reasoning_effort = optional_text(args.reasoning_effort, maximum=32)
- serialized_preflight_issues = preflight_issues_json(args.preflight_issues_json)
+ preflight_issues = (
+ sys.stdin.read() if args.preflight_issues_json_stdin else args.preflight_issues_json
+ )
+ serialized_preflight_issues = preflight_issues_json(preflight_issues)
connection.execute("BEGIN IMMEDIATE")
try:
timestamp = now()
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_scan_history.py b/sdk/typescript/_bundled_plugin/scripts/workbench_scan_history.py
index abf18b626..f231f0d74 100644
--- a/sdk/typescript/_bundled_plugin/scripts/workbench_scan_history.py
+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_scan_history.py
@@ -470,8 +470,9 @@ def save_scan_comparison(
read_coverage(after)
before_findings = _scan_findings(connection, before["id"])
after_findings = _scan_findings(connection, after["id"])
+ matches_json = sys.stdin.read() if args.matches_json_stdin else args.matches_json
try:
- payload = json.loads(args.matches_json)
+ payload = json.loads(matches_json)
except (TypeError, ValueError) as exc:
raise SystemExit("Scan comparison matches must be a valid JSON object.") from exc
if not isinstance(payload, dict) or set(payload) != {"matches", "uncertain"}:
diff --git a/sdk/typescript/_bundled_plugin/scripts/workbench_validation.py b/sdk/typescript/_bundled_plugin/scripts/workbench_validation.py
index a01d979e0..608ede87a 100644
--- a/sdk/typescript/_bundled_plugin/scripts/workbench_validation.py
+++ b/sdk/typescript/_bundled_plugin/scripts/workbench_validation.py
@@ -57,6 +57,15 @@ def user_text(value: str | None) -> str | None:
return optional_text(value)
+def user_context_argument(args: argparse.Namespace) -> str | None:
+ value = (
+ sys.stdin.read()
+ if getattr(args, "user_context_stdin", False)
+ else args.user_context
+ )
+ return user_text(value)
+
+
def reject_nonstandard_json_number(value: str) -> None:
raise ValueError(f"invalid JSON number {value}")
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index 8331229f3..a06e48046 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -346,7 +346,6 @@ const DEEP_SCAN_SETTINGS = [
["maxDiscoveryRuns", "max_discovery_runs", 1],
["maxTimeHours", "max_time_hours", 0],
] as const;
-
export class CodexSecurity {
public readonly config: Readonly<CodexSecurityConfig>;
public readonly metadata: CodexSecurityMetadata = {
@@ -751,22 +750,25 @@ export class CodexSecurity {
signal,
failureMessage: "Could not save the Codex Security scan",
};
- const registration = await workbench(workbenchOptions, [
- "register-cli-scan",
- "--repository",
- repo,
- "--scan-dir",
- scanDir,
- "--recipe-json",
+ const registration = await workbench(
+ workbenchOptions,
+ [
+ "register-cli-scan",
+ "--repository",
+ repo,
+ "--scan-dir",
+ scanDir,
+ "--recipe-json-stdin",
+ ...(options.archiveExisting === true ? ["--archive-existing"] : []),
+ ...(archivedScanDir === null
+ ? []
+ : ["--archived-scan-dir", archivedScanDir]),
+ ...(options.parentScanId === undefined
+ ? []
+ : ["--parent-scan-id", options.parentScanId]),
+ ],
JSON.stringify(recipe),
- ...(options.archiveExisting === true ? ["--archive-existing"] : []),
- ...(archivedScanDir === null
- ? []
- : ["--archived-scan-dir", archivedScanDir]),
- ...(options.parentScanId === undefined
- ? []
- : ["--parent-scan-id", options.parentScanId]),
- ]);
+ );
const scanId = registration["scanId"];
const targetId = registration["targetId"];
const contract = registration["contract"];
@@ -1159,8 +1161,8 @@ export class CodexSecurity {
}
}
try {
- const runWorkbench = (args: readonly string[]) =>
- workbench(workbenchOptions, args);
+ const runWorkbench = (args: readonly string[], input?: string) =>
+ workbench(workbenchOptions, args, input);
const previousFindings = await listRepositoryFindings(
runWorkbench,
targetId,
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index c7549bb79..ecb7ce4af 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -973,7 +973,7 @@ interface CliDependencies {
): Promise<string>;
bulkScan?: BulkScanDiscoveryDependencies;
linearClient?: LinearClientFactory;
- runWorkbench(args: readonly string[]): Promise<JsonObject>;
+ runWorkbench(args: readonly string[], input?: string): Promise<JsonObject>;
matchFindings: typeof matchScanFindings;
checkForUpdate(signal: AbortSignal): Promise<UpdateNotice | undefined>;
}
@@ -1118,7 +1118,7 @@ const DEFAULT_DEPENDENCIES: CliDependencies = {
}
return undefined;
},
- runWorkbench: async (args) => {
+ runWorkbench: async (args, input) => {
const environment = {
...exportEnvironment(),
CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(),
@@ -1132,6 +1132,7 @@ const DEFAULT_DEPENDENCIES: CliDependencies = {
failureMessage: "Could not read Codex Security scan history",
},
args,
+ input,
);
},
matchFindings: (input, options) =>
@@ -1442,19 +1443,21 @@ export async function main(
],
async ({ matchingCached, matchingInputs, ...comparison }) => {
if (matchingCached && !force) return comparison;
- return await dependencies.runWorkbench([
- "save-scan-comparison",
- "--before-scan-id",
- beforeId,
- "--after-scan-id",
- afterId,
- "--matches-json",
+ return await dependencies.runWorkbench(
+ [
+ "save-scan-comparison",
+ "--before-scan-id",
+ beforeId,
+ "--after-scan-id",
+ afterId,
+ "--matches-json-stdin",
+ ],
JSON.stringify(
await dependencies.matchFindings(
matchingInputs as JsonObject & ScanComparisonInput,
),
),
- ]);
+ );
},
);
const presentHistory = (
@@ -3777,15 +3780,17 @@ async function matchAllScans(
return { scanId, matches, uncertain };
});
for (const { scanId, matches, uncertain } of comparisons) {
- await dependencies.runWorkbench([
- "save-scan-comparison",
- "--before-scan-id",
- scanId,
- "--after-scan-id",
- afterScanId,
- "--matches-json",
+ await dependencies.runWorkbench(
+ [
+ "save-scan-comparison",
+ "--before-scan-id",
+ scanId,
+ "--after-scan-id",
+ afterScanId,
+ "--matches-json-stdin",
+ ],
JSON.stringify({ matches, uncertain }),
- ]);
+ );
matchedPairs += 1;
findingMatches += matches.reduce(
(count, { beforeOccurrenceIds, afterOccurrenceIds }) =>
diff --git a/sdk/typescript/src/scan-comparison.ts b/sdk/typescript/src/scan-comparison.ts
index 20614c39d..60caca544 100644
--- a/sdk/typescript/src/scan-comparison.ts
+++ b/sdk/typescript/src/scan-comparison.ts
@@ -51,7 +51,10 @@ interface CompletedScanMatchingOptions
previousFindings: readonly Record<string, unknown>[];
falsePositives: readonly Record<string, unknown>[];
findings: readonly Finding[];
- workbench(args: readonly string[]): Promise<Record<string, unknown>>;
+ workbench(
+ args: readonly string[],
+ input?: string,
+ ): Promise<Record<string, unknown>>;
matchFindings?: typeof matchScanFindings;
}
@@ -259,15 +262,17 @@ export async function matchCompletedScan(
!matchedAfter.has(afterOccurrenceId),
) ?? [];
if (semanticComparison === undefined && scanMatches.length === 0) continue;
- await options.workbench([
- "save-scan-comparison",
- "--before-scan-id",
- scanId,
- "--after-scan-id",
- options.scanId,
- "--matches-json",
+ await options.workbench(
+ [
+ "save-scan-comparison",
+ "--before-scan-id",
+ scanId,
+ "--after-scan-id",
+ options.scanId,
+ "--matches-json-stdin",
+ ],
JSON.stringify({ matches: scanMatches, uncertain: scanUncertain }),
- ]);
+ );
}
}
diff --git a/sdk/typescript/tests-ts/api-surface.test.ts b/sdk/typescript/tests-ts/api-surface.test.ts
index 86d11320e..dc4072d47 100644
--- a/sdk/typescript/tests-ts/api-surface.test.ts
+++ b/sdk/typescript/tests-ts/api-surface.test.ts
@@ -39,8 +39,11 @@ async function scanResponseSurface(runtimeOptions?: {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options: unknown, args: readonly string[]) =>
- mockWorkbench(args),
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ) => mockWorkbench(args, input),
createCodex: (options: CodexOptions) => {
codexOptions = options;
return {
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index a6ecd98bd..10d656c42 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -133,7 +133,6 @@ const BEDROCK_AUTHENTICATION_CASES = [
],
["default AWS credential chain", {}, "default_credential_chain"],
] as const;
-
function nodeCodex(script: string): {
command: { command: string };
environment: Record<string, string>;
@@ -226,11 +225,15 @@ describe("CodexSecurity orchestration", () => {
prepareRuntime: async () => preparedRuntime(codexHome),
resolvePluginPython: async () => "/managed/python",
repositoryRevision: async () => null,
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
if (args[0] === "register-cli-scan") {
- recipe = JSON.parse(args[args.indexOf("--recipe-json") + 1]!);
+ recipe = JSON.parse(input!);
}
- return mockWorkbench(args);
+ return mockWorkbench(args, input);
},
createCodex: () => ({
startThread: (options: Record<string, unknown>) => {
@@ -1071,11 +1074,15 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
if (args[0] === "register-cli-scan") {
- savedRecipe = JSON.parse(args[args.indexOf("--recipe-json") + 1]!);
+ savedRecipe = JSON.parse(input!);
}
- return mockWorkbench(args);
+ return mockWorkbench(args, input);
},
resolveCodexCommand: () => {
throw new Error("The Bedrock profile must not sign in to OpenAI");
@@ -1358,7 +1365,11 @@ describe("CodexSecurity orchestration", () => {
prepareRuntime: async () => preparedRuntime(codexHome),
resolvePluginPython: async () => "/managed/python",
repositoryRevision: async () => null,
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
if (args[0] === "get-scan-feedback") {
return {
scanId: "scan_example_001",
@@ -1368,7 +1379,7 @@ describe("CodexSecurity orchestration", () => {
}
if (args[0] !== "register-cli-scan") return {};
registration = args;
- return mockScanRegistration(args);
+ return mockScanRegistration(args, input);
},
createCodex: () => ({
startThread: () => ({
@@ -1777,6 +1788,7 @@ describe("CodexSecurity orchestration", () => {
const warningDetails: Array<{ kind: "target_changed" } | undefined> = [];
const reconnects: Array<[number, number]> = [];
const commands: Array<readonly string[]> = [];
+ let registrationInput: string | undefined;
const completionWarning =
"Repository HEAD changed while the scan was running; results were saved for the original revision.";
const recoveryWarning =
@@ -1808,10 +1820,15 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
commands.push(args);
if (args[0] === "register-cli-scan") {
- return mockScanRegistration(args);
+ registrationInput = input;
+ return mockScanRegistration(args, input);
}
if (args[0] === "get-scan-feedback") {
return {
@@ -1963,9 +1980,8 @@ describe("CodexSecurity orchestration", () => {
"Additional scan instructions:\nFocus on authentication and authorization.",
);
expect(followUpPrompt).toBe("Draft fixes for confirmed findings.");
- expect(
- JSON.parse(commands[0]![commands[0]!.indexOf("--recipe-json") + 1]!),
- ).toMatchObject({
+ expect(commands[0]).toContain("--recipe-json-stdin");
+ expect(JSON.parse(registrationInput!)).toMatchObject({
repository,
target: { kind: "repository", paths: [] },
mode: "standard",
@@ -2016,10 +2032,14 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
if (args[0] === "register-cli-scan") {
return {
- ...mockScanRegistration(args),
+ ...mockScanRegistration(args, input),
targetRevision: "cafebabe",
contract: {
target: {
@@ -2096,7 +2116,11 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
if (args[0] !== "register-cli-scan") {
return {
scanId: "scan_example_001",
@@ -2104,8 +2128,8 @@ describe("CodexSecurity orchestration", () => {
falsePositives: [],
};
}
- recipe = JSON.parse(args[args.indexOf("--recipe-json") + 1]!);
- return mockScanRegistration(args);
+ recipe = JSON.parse(input!);
+ return mockScanRegistration(args, input);
},
createCodex: () => ({
startThread: () => ({
@@ -2384,10 +2408,14 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> =>
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> =>
args[0] === "register-cli-scan"
? {
- ...mockScanRegistration(args),
+ ...mockScanRegistration(args, input),
contract: { target: { allowedKinds: [] } },
}
: {},
@@ -2421,10 +2449,14 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
commands.push(args[0]!);
if (args[0] === "register-cli-scan") {
- return mockScanRegistration(args);
+ return mockScanRegistration(args, input);
}
if (args[0] === "get-scan-feedback") {
return {
@@ -2485,9 +2517,13 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
commands.push(args[0]!);
- return mockWorkbench(args);
+ return mockWorkbench(args, input);
},
createCodex: () => ({
startThread: () => ({
@@ -2537,10 +2573,14 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> =>
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> =>
args[0] === "register-cli-scan"
- ? { ...mockScanRegistration(args), scopeFileCount: 4_207 }
- : mockWorkbench(args),
+ ? { ...mockScanRegistration(args, input), scopeFileCount: 4_207 }
+ : mockWorkbench(args, input),
createCodex: () => ({
startThread: () => ({
id: null,
@@ -2615,10 +2655,14 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> =>
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> =>
args[0] === "register-cli-scan"
- ? { ...mockScanRegistration(args), scopeFileCount: 1_258 }
- : mockWorkbench(args),
+ ? { ...mockScanRegistration(args, input), scopeFileCount: 1_258 }
+ : mockWorkbench(args, input),
createCodex: () => ({
startThread: () => ({
id: null,
@@ -2753,10 +2797,14 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
commands.push(args);
if (args[0] === "register-cli-scan") {
- return mockScanRegistration(args);
+ return mockScanRegistration(args, input);
}
if (args[0] === "get-scan-feedback") {
return {
@@ -2861,10 +2909,14 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
commands.push(args[0]!);
return args[0] === "register-cli-scan"
- ? mockScanRegistration(args)
+ ? mockScanRegistration(args, input)
: {};
},
},
@@ -2902,9 +2954,13 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
if (args[0] === "register-cli-scan") {
- return { ...mockScanRegistration(args), scanId };
+ return { ...mockScanRegistration(args, input), scanId };
}
if (args[0] === "get-scan-feedback") {
return {
@@ -2990,6 +3046,7 @@ describe("CodexSecurity orchestration", () => {
const commands: (readonly string[])[] = [];
let modelCalled = false;
let matched = false;
+ let savedComparisonInput: string | undefined;
const client = new TestClient(
{},
{
@@ -2998,7 +3055,11 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
commands.push(args);
if (args[0] === "get-scan-feedback") {
return {
@@ -3036,8 +3097,11 @@ describe("CodexSecurity orchestration", () => {
: [{ findingId: "another-open-finding" }],
};
}
- if (args[0] === "save-scan-comparison") matched = true;
- return mockWorkbench(args);
+ if (args[0] === "save-scan-comparison") {
+ matched = true;
+ savedComparisonInput = input;
+ }
+ return mockWorkbench(args, input);
},
async matchFindings() {
modelCalled = true;
@@ -3092,6 +3156,17 @@ describe("CodexSecurity orchestration", () => {
expect(
commands.some(([command]) => command === "list-global-findings"),
).toBe(true);
+ if (failure === "dismissed") {
+ expect(JSON.parse(savedComparisonInput!)).toMatchObject({
+ matches: [
+ {
+ beforeOccurrenceIds: [previous.occurrenceId],
+ afterOccurrenceIds: [current.occurrenceId],
+ },
+ ],
+ uncertain: [],
+ });
+ }
await client.close();
},
);
@@ -3127,9 +3202,13 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
if (args[0] === "register-cli-scan") {
- return mockScanRegistration(args);
+ return mockScanRegistration(args, input);
}
return args[0] === "get-scan-feedback" ? feedback : {};
},
@@ -3193,10 +3272,14 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
commands.push(args);
if (args[0] === "register-cli-scan") {
- return mockScanRegistration(args);
+ return mockScanRegistration(args, input);
}
if (args[0] === "get-scan-feedback") {
return {
@@ -3259,9 +3342,13 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
commands.push(args);
- return mockWorkbench(args);
+ return mockWorkbench(args, input);
},
createCodex: () => ({
startThread: () => ({
@@ -3426,10 +3513,14 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
commands.push(args);
if (args[0] === "register-cli-scan") {
- return mockScanRegistration(args);
+ return mockScanRegistration(args, input);
}
if (args[0] === "get-scan-feedback") {
return {
@@ -3555,10 +3646,14 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
commands.push(args);
if (args[0] !== "complete-budget-exhausted-scan") {
- return mockWorkbench(args);
+ return mockWorkbench(args, input);
}
if (completion === "unavailable") {
throw new Error("Deep Scan discovery has not completed.");
@@ -3687,10 +3782,14 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
commands.push(args);
if (args[0] === "register-cli-scan") {
- return mockScanRegistration(args);
+ return mockScanRegistration(args, input);
}
if (args[0] === "get-scan-feedback") {
return {
@@ -3771,7 +3870,11 @@ describe("CodexSecurity orchestration", () => {
resolvePluginPython: async () => "/managed/python",
prepareOutputDir: async () => scanDir,
repositoryRevision: async () => "deadbeef",
- runWorkbench: async (_options, args): Promise<JsonObject> => {
+ runWorkbench: async (
+ _options: unknown,
+ args: readonly string[],
+ input?: string,
+ ): Promise<JsonObject> => {
if (args[0] === "get-scan-feedback") {
return {
scanId: "scan_example_001",
@@ -3780,8 +3883,8 @@ describe("CodexSecurity orchestration", () => {
};
}
if (args[0] !== "register-cli-scan") return {};
- recipe = JSON.parse(args[args.indexOf("--recipe-json") + 1]!);
- return mockScanRegistration(args);
+ recipe = JSON.parse(input!);
+ return mockScanRegistration(args, input);
},
createCodex: (options: CodexOptions) => ({
startThread: () => ({
@@ -3894,9 +3997,10 @@ describe("CodexSecurity orchestration", () => {
runWorkbench: async (
options: Parameters<typeof runWorkbench>[0],
args: readonly string[],
+ input?: string,
): Promise<JsonObject> => {
commands.push(args);
- const result = await runWorkbench(options, args);
+ const result = await runWorkbench(options, args, input);
if (args[0] === "fail-scan") {
throw new Error("failure recording also failed");
}
@@ -3972,9 +4076,10 @@ describe("CodexSecurity orchestration", () => {
runWorkbench: async (
options: Parameters<typeof runWorkbench>[0],
args: readonly string[],
+ input?: string,
): Promise<JsonObject> => {
commands.push(args);
- return await runWorkbench(options, args);
+ return await runWorkbench(options, args, input);
},
createCodex: () => ({
startThread: () => ({
diff --git a/sdk/typescript/tests-ts/cli-fixtures.ts b/sdk/typescript/tests-ts/cli-fixtures.ts
index cf693bbe3..175bbda29 100644
--- a/sdk/typescript/tests-ts/cli-fixtures.ts
+++ b/sdk/typescript/tests-ts/cli-fixtures.ts
@@ -198,7 +198,10 @@ export function dependencies(
...arguments_: Parameters<MainDependencies["runRepositoryCommand"]>
) => string | Promise<string>;
bulkScan?: MainDependencies["bulkScan"];
- onWorkbench?: (args: readonly string[]) => JsonObject | Promise<JsonObject>;
+ onWorkbench?: (
+ args: readonly string[],
+ input?: string,
+ ) => JsonObject | Promise<JsonObject>;
onMatch?: MainDependencies["matchFindings"];
onUpdateCheck?: (signal: AbortSignal) => Promise<UpdateNotice | undefined>;
currentDirectory?: string;
@@ -266,8 +269,8 @@ export function dependencies(
...(options.linearClient === undefined
? {}
: { linearClient: options.linearClient }),
- runWorkbench: async (args) =>
- (await options.onWorkbench?.(args)) ?? { scans: [] },
+ runWorkbench: async (args, input) =>
+ (await options.onWorkbench?.(args, input)) ?? { scans: [] },
matchFindings: async (input) =>
(await options.onMatch?.(input)) ?? { matches: [], uncertain: [] },
exportFindings: async (arguments_) =>
diff --git a/sdk/typescript/tests-ts/cli-workbench.test.ts b/sdk/typescript/tests-ts/cli-workbench.test.ts
index ef869db2e..87aae64c9 100644
--- a/sdk/typescript/tests-ts/cli-workbench.test.ts
+++ b/sdk/typescript/tests-ts/cli-workbench.test.ts
@@ -418,6 +418,7 @@ describe("CLI workbench", () => {
["compare", ["baseline-scan"], "baseline-scan", "latest-scan"],
] as const) {
const calls: Array<readonly string[]> = [];
+ let comparisonInput: string | undefined;
const stdout = capture();
expect(
@@ -426,13 +427,14 @@ describe("CLI workbench", () => {
stdout.stream,
capture().stream,
dependencies({
- onWorkbench: (args): JsonObject => {
+ onWorkbench: (args, input): JsonObject => {
calls.push(args);
if (args[0] === "list-scans") {
return {
scans: [{ scanId: "latest-scan" }, { scanId: "older-scan" }],
};
}
+ if (args[0] === "save-scan-comparison") comparisonInput = input;
return args[0] === "compare-scans"
? { matchingCached: false, matchingInputs: { before, after } }
: { summary: { persisting: 1 } };
@@ -452,7 +454,9 @@ describe("CLI workbench", () => {
const comparison = calls.find((args) => args[0] === "compare-scans")!;
expect(comparison[2]).toBe(expectedBefore);
expect(comparison[4]).toBe(expectedAfter);
- expect(JSON.parse(calls.at(-1)![6]!)).toEqual(matching);
+ const save = calls.find((args) => args[0] === "save-scan-comparison")!;
+ expect(save.at(-1)).toBe("--matches-json-stdin");
+ expect(JSON.parse(comparisonInput!)).toEqual(matching);
expect(JSON.parse(stdout.text())).toEqual({ summary: { persisting: 1 } });
}
});
@@ -521,6 +525,7 @@ describe("CLI workbench", () => {
},
];
const calls: Array<readonly string[]> = [];
+ const inputs: Array<string | undefined> = [];
let matcherCalls = 0;
const stdout = capture();
@@ -530,8 +535,9 @@ describe("CLI workbench", () => {
stdout.stream,
capture().stream,
dependencies({
- onWorkbench: (args): JsonObject => {
+ onWorkbench: (args, input): JsonObject => {
calls.push(args);
+ inputs.push(input);
return args[0] === "list-unmatched-scan-pairs"
? {
repository: "/current/repository",
@@ -591,10 +597,10 @@ describe("CLI workbench", () => {
"--force",
]);
expect(
- calls.slice(1).map((args) => ({
+ calls.slice(1).map((args, index) => ({
before: args[2],
after: args[4],
- result: JSON.parse(args[6]!),
+ result: JSON.parse(inputs[index + 1]!),
})),
).toMatchObject([
{ before: "scan-a", after: "scan-b" },
@@ -630,9 +636,11 @@ describe("CLI workbench", () => {
test("saves empty comparisons without starting Codex", async () => {
const calls: Array<readonly string[]> = [];
+ let comparisonInput: string | undefined;
const deps = dependencies({
- onWorkbench: (args): JsonObject => {
+ onWorkbench: (args, input): JsonObject => {
calls.push(args);
+ if (args[0] === "save-scan-comparison") comparisonInput = input;
return args[0] === "list-unmatched-scan-pairs"
? {
repository: "/repo",
@@ -667,7 +675,11 @@ describe("CLI workbench", () => {
deps,
),
).toBe(0);
- expect(JSON.parse(calls[1]![6]!)).toEqual({ matches: [], uncertain: [] });
+ expect(calls[1]!.at(-1)).toBe("--matches-json-stdin");
+ expect(JSON.parse(comparisonInput!)).toEqual({
+ matches: [],
+ uncertain: [],
+ });
});
test("does not save conflicting confirmed and uncertain matches", async () => {
diff --git a/sdk/typescript/tests-ts/compact-diff-scan.test.ts b/sdk/typescript/tests-ts/compact-diff-scan.test.ts
index 5407c0cd8..106fd38e5 100644
--- a/sdk/typescript/tests-ts/compact-diff-scan.test.ts
+++ b/sdk/typescript/tests-ts/compact-diff-scan.test.ts
@@ -417,6 +417,92 @@ describe("compact diff scan", () => {
expect(escaped.stderr).toContain("in-scope file row 1");
});
+ test("streams maximum-size preflight checks through the MCP workbench", async () => {
+ const { root, repository } = createRepository();
+ writeSource(repository, "src/handler.py", "value = 1\n");
+ mkdirSync(join(root, "scans"));
+ mkdirSync(join(root, "state"));
+ const client = await startMcp(root);
+ const owner = "preflight-stdin-owner";
+
+ try {
+ const started = await client.call(
+ "start_codex_security_prompt_only_scan",
+ { mode: "standard", targetPath: repository, scope: "." },
+ owner,
+ );
+ const scanId = (started["scan"] as JsonObject)["scanId"] as string;
+ const preflightChecks = Array.from({ length: 32 }, (_, index) => ({
+ capability: `windows_process_boundary_${index}`,
+ reason: "é".repeat(1_200),
+ severity: "warn",
+ status: "fail",
+ }));
+ expect(JSON.stringify(preflightChecks).length).toBeGreaterThan(
+ 32 * 1_024,
+ );
+
+ await client.call(
+ "update_codex_security_scan_progress",
+ { scanId, phase: "preflight", preflightChecks },
+ owner,
+ );
+ } finally {
+ await client.close();
+ }
+ });
+
+ test("streams oversized option-like user context through the MCP workbench", async () => {
+ const { root, repository } = createRepository();
+ writeSource(repository, "src/handler.py", "value = 1\n");
+ mkdirSync(join(root, "scans"));
+ mkdirSync(join(root, "state"));
+ const client = await startMcp(root);
+ const userContext = `--${"é".repeat(64 * 1_024)}`;
+
+ try {
+ const selection = {
+ mode: "standard",
+ targetPath: repository,
+ scope: ".",
+ userContext,
+ };
+ const opened = await client.call(
+ "open_codex_security_workspace",
+ selection,
+ "user-context-stdin-owner",
+ );
+ expect((opened["workspace"] as JsonObject)["userContext"]).toBe(
+ userContext,
+ );
+ const sessionId = (opened["workspace"] as JsonObject)["id"] as string;
+ const saved = await client.call(
+ "submit_codex_security_setup",
+ { ...selection, sessionId },
+ "user-context-stdin-owner",
+ );
+ expect((saved["workspace"] as JsonObject)["userContext"]).toBe(
+ userContext,
+ );
+
+ const started = await client.call(
+ "start_codex_security_prompt_only_scan",
+ selection,
+ "user-context-stdin-owner",
+ );
+ const scan = started["scan"] as JsonObject;
+ expect(scan["userContext"]).toBe(userContext);
+ const updated = await client.call(
+ "update_codex_security_scan_context",
+ { scanId: scan["scanId"], userContext: "" },
+ "user-context-stdin-owner",
+ );
+ expect((updated["scan"] as JsonObject)["userContext"]).toBeNull();
+ } finally {
+ await client.close();
+ }
+ }, 30_000);
+
test.each(["object", "Markdown"])("MCP diff retains %s", async (format) => {
const { root, repository } = createRepository();
writeSource(repository, "src/guard.py", "allowed = True\n");
diff --git a/sdk/typescript/tests-ts/deep-scan-workbench.test.ts b/sdk/typescript/tests-ts/deep-scan-workbench.test.ts
index 5b00da0af..179156e49 100644
--- a/sdk/typescript/tests-ts/deep-scan-workbench.test.ts
+++ b/sdk/typescript/tests-ts/deep-scan-workbench.test.ts
@@ -187,6 +187,53 @@ test("recovers an interrupted copied Deep Scan publication", async () => {
});
describe("deep scan workbench ownership", () => {
+ test("starts a Deep Scan with oversized stdin user context", async () => {
+ const root = await realpath(
+ await mkdtemp(join(tmpdir(), "codex-security-deep-context-stdin-")),
+ );
+ temporaryDirectories.push(root);
+ const repository = join(root, "repository");
+ const stateDir = join(root, "state");
+ await mkdir(repository);
+ await writeFile(join(repository, "source.py"), "# source fixture\n");
+ const python = Bun.which("python3") ?? Bun.which("python");
+ expect(python).not.toBeNull();
+ const userContext = "deep security focus".repeat(4_000);
+
+ const result = Bun.spawnSync(
+ [
+ python!,
+ "-I",
+ "-B",
+ join(PLUGIN_ROOT, "scripts", "workbench_db.py"),
+ "begin-deep-scan",
+ "--thread-id",
+ "deep-context-stdin-owner",
+ "--target-path",
+ repository,
+ "--scope",
+ ".",
+ "--user-context-stdin",
+ "--scan-root",
+ join(root, "scans"),
+ "--available-parallelism",
+ "4",
+ ],
+ {
+ env: { ...process.env, CODEX_SECURITY_STATE_DIR: stateDir },
+ stdin: Buffer.from(userContext),
+ stdout: "pipe",
+ stderr: "pipe",
+ },
+ );
+
+ expect(result.exitCode, new TextDecoder().decode(result.stderr)).toBe(0);
+ const started = JSON.parse(
+ new TextDecoder().decode(result.stdout),
+ ) as Record<string, Record<string, unknown>>;
+ expect(started["deepScan"]?.["userContext"]).toBe(userContext);
+ }, 30_000);
+
test("rejects completion before an SDK-created Deep Scan finishes", async () => {
const root = await realpath(
await mkdtemp(join(tmpdir(), "codex-security-deep-completion-guard-")),
diff --git a/sdk/typescript/tests-ts/mcp-launcher.test.ts b/sdk/typescript/tests-ts/mcp-launcher.test.ts
index 281a2e442..047c5e2ed 100644
--- a/sdk/typescript/tests-ts/mcp-launcher.test.ts
+++ b/sdk/typescript/tests-ts/mcp-launcher.test.ts
@@ -60,7 +60,9 @@ test("starts the packaged MCP server with managed Node and an empty PATH", async
CODEX_MCP_NODE_PATH: managedNode,
},
encoding: "utf8",
- timeout: 10_000,
+ // Bun 1.3.14 can report an immediate ETIMEDOUT for synchronous
+ // Windows .cmd launches. The enclosing test timeout still bounds it.
+ ...(windows ? {} : { timeout: 10_000 }),
windowsHide: true,
windowsVerbatimArguments: windows,
input:
diff --git a/sdk/typescript/tests-ts/repository-findings.test.ts b/sdk/typescript/tests-ts/repository-findings.test.ts
index e2656e854..dbf4219be 100644
--- a/sdk/typescript/tests-ts/repository-findings.test.ts
+++ b/sdk/typescript/tests-ts/repository-findings.test.ts
@@ -1,7 +1,6 @@
-import { spawnSync } from "node:child_process";
import { join } from "node:path";
import { expect, test } from "bun:test";
-import { resolvePluginPython } from "../src/runtime.js";
+import { resolvePluginPython, runCodexCommand } from "../src/runtime.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
test("combines repository findings without reviving dismissed aliases", async () => {
@@ -62,14 +61,14 @@ result["ordered"] = findings("first")
print(json.dumps(result))
`;
- const execution = spawnSync(
- python,
+ const execution = await runCodexCommand(
+ { command: python },
["-I", "-B", "-", join(PLUGIN_ROOT, "scripts")],
- { input: probe, encoding: "utf8", timeout: 10_000, windowsHide: true },
- );
- expect(execution.status, execution.stderr || execution.error?.message).toBe(
- 0,
+ process.env,
+ probe,
+ AbortSignal.timeout(10_000),
);
+ expect(execution.exitCode, execution.stderr).toBe(0);
const result = JSON.parse(execution.stdout) as Record<
string,
diff --git a/sdk/typescript/tests-ts/scan-comparison.test.ts b/sdk/typescript/tests-ts/scan-comparison.test.ts
index 29f11bef5..fe0154829 100644
--- a/sdk/typescript/tests-ts/scan-comparison.test.ts
+++ b/sdk/typescript/tests-ts/scan-comparison.test.ts
@@ -341,7 +341,7 @@ describe("semantic scan comparison", () => {
const open = { findingId: "open", occurrenceId: "old-open" };
const dismissed = { findingId: "dismissed", occurrenceId: "old-dismissed" };
const after = { findingId: "renamed", occurrenceId: "new-renamed" };
- const commands: (readonly string[])[] = [];
+ const commands: Array<{ args: readonly string[]; input?: string }> = [];
let input: ScanComparisonInput | undefined;
await matchCompletedScan({
scanId: "current",
@@ -354,8 +354,8 @@ describe("semantic scan comparison", () => {
CODEX_SECURITY_SCAN_ID: "current",
FIREWORKS_API_KEY: "synthetic-provider-key",
},
- async workbench(args) {
- commands.push(args);
+ async workbench(args, commandInput) {
+ commands.push({ args, input: commandInput });
return args[0] === "list-unmatched-scan-pairs"
? {
batches: [
@@ -402,11 +402,12 @@ describe("semantic scan comparison", () => {
},
});
expect(input).toEqual({ before: [open, dismissed], after: [after] });
- expect(commands.map(([command]) => command)).toEqual([
+ expect(commands.map(({ args: [command] }) => command)).toEqual([
"list-unmatched-scan-pairs",
"save-scan-comparison",
]);
- const saved = JSON.parse(commands[1]!.at(-1)!) as ScanComparisonResult;
+ expect(commands[1]!.args.at(-1)).toBe("--matches-json-stdin");
+ const saved = JSON.parse(commands[1]!.input!) as ScanComparisonResult;
expect(
saved.matches.map(({ beforeOccurrenceIds }) => beforeOccurrenceIds),
).toEqual([["old-dismissed"]]);
diff --git a/sdk/typescript/tests-ts/scan-recovery.test.ts b/sdk/typescript/tests-ts/scan-recovery.test.ts
index e6709d55d..59466b894 100644
--- a/sdk/typescript/tests-ts/scan-recovery.test.ts
+++ b/sdk/typescript/tests-ts/scan-recovery.test.ts
@@ -102,7 +102,11 @@ async function writeJson(path: string, value: unknown): Promise<void> {
await writeFile(path, `${JSON.stringify(value)}\n`);
}
-async function workbench(fixture: ScanFixture, args: readonly string[]) {
+async function workbench(
+ fixture: ScanFixture,
+ args: readonly string[],
+ input?: string,
+) {
return runWorkbench(
{
python: fixture.python,
@@ -113,20 +117,26 @@ async function workbench(fixture: ScanFixture, args: readonly string[]) {
},
},
args,
+ input,
);
}
async function startDraftScan(
repositoryKind: "directory" | "clean" | "dirty" | "nested" = "directory",
+ recipeFromStdin = false,
): Promise<ScanFixture> {
const root = await realpath(
await mkdtemp(join(tmpdir(), "codex-security-scan-recovery-")),
);
temporaryDirectories.push(root);
- const python = Bun.which("python3") ?? Bun.which("python");
+ const python =
+ process.env["PYTHON"] ?? Bun.which("python3") ?? Bun.which("python");
expect(python).not.toBeNull();
- const target = join(root, "repository");
+ const target = join(
+ root,
+ recipeFromStdin ? "répository-日本語" : "repository",
+ );
const scanDir = join(root, "scan");
await mkdir(join(target, "src"), { recursive: true });
await writeFile(join(target, "src", "extract.py"), "# fixture\n");
@@ -174,20 +184,26 @@ async function startDraftScan(
scanId: "",
registration: {},
};
- const registration = await workbench(fixture, [
- "register-cli-scan",
- "--repository",
- target,
- "--scan-dir",
- scanDir,
- "--recipe-json",
- JSON.stringify({
- config: {},
- mode: "standard",
- repository: target,
- target: { kind: "repository", paths: [] },
- }),
- ]);
+ const recipe = JSON.stringify({
+ config: {},
+ mode: "standard",
+ repository: target,
+ target: { kind: "repository", paths: [] },
+ });
+ const registration = await workbench(
+ fixture,
+ [
+ "register-cli-scan",
+ "--repository",
+ target,
+ "--scan-dir",
+ scanDir,
+ ...(recipeFromStdin
+ ? ["--recipe-json-stdin"]
+ : ["--recipe-json", recipe]),
+ ],
+ recipeFromStdin ? recipe : undefined,
+ );
fixture.scanId = String(registration["scanId"]);
fixture.registration = registration;
@@ -234,9 +250,24 @@ async function completeScan(fixture: ScanFixture): Promise<ScanSummary> {
}
describe("malformed scan artifact recovery", () => {
- test("rejoins a headless scan after its running context changes", async () => {
+ test("registers a Unicode scan recipe delivered through stdin", async () => {
+ const fixture = await startDraftScan("directory", true);
+ expect(fixture.registration).toMatchObject({
+ scanDir: fixture.scanDir,
+ targetRevision: "unversioned",
+ });
+ const saved = await workbench(fixture, [
+ "get-scan-recipe",
+ "--scan-id",
+ fixture.scanId,
+ ]);
+ expect(saved["recipe"]).toMatchObject({ repository: fixture.repository });
+ });
+
+ test("rejoins a headless scan after its stdin context is cleared", async () => {
const fixture = await startDraftScan();
const threadId = "context-rejoin-regression";
+ const originalContext = "original security focus".repeat(3_000);
const startArguments = [
"start-headless-standard-scan",
"--thread-id",
@@ -245,42 +276,46 @@ describe("malformed scan artifact recovery", () => {
fixture.repository,
"--scope",
".",
- "--user-context",
- "original security focus",
+ "--user-context-stdin",
];
- const created = await workbench(fixture, startArguments);
+ const created = await workbench(fixture, startArguments, originalContext);
const scan = created["scan"] as {
scanId: string;
handoffClaimToken: string;
userContext: string;
};
- const updated = await workbench(fixture, [
- "update-scan-context",
- "--scan-id",
- scan.scanId,
- "--user-context",
- "updated security focus",
- "--thread-id",
- threadId,
- "--claim-token",
- scan.handoffClaimToken,
- ]);
+ expect(scan.userContext).toBe(originalContext);
+
+ const updated = await workbench(
+ fixture,
+ [
+ "update-scan-context",
+ "--scan-id",
+ scan.scanId,
+ "--user-context-stdin",
+ "--thread-id",
+ threadId,
+ "--claim-token",
+ scan.handoffClaimToken,
+ ],
+ "",
+ );
expect(updated["scan"]).toMatchObject({
scanId: scan.scanId,
- userContext: "updated security focus",
+ userContext: null,
});
expect(updated["workspace"]).toMatchObject({
- userContext: "updated security focus",
+ userContext: null,
});
- const retried = await workbench(fixture, startArguments);
+ const retried = await workbench(fixture, startArguments, originalContext);
expect(retried["startDisposition"]).toBe("joined");
expect(retried["scan"]).toMatchObject({
scanId: scan.scanId,
- userContext: "updated security focus",
+ userContext: null,
});
- });
+ }, 30_000);
test("returns the authoritative directory snapshot contract at registration", async () => {
const fixture = await startDraftScan();
diff --git a/sdk/typescript/tests-ts/support/api-client.ts b/sdk/typescript/tests-ts/support/api-client.ts
index 79e3b595c..da00b6a88 100644
--- a/sdk/typescript/tests-ts/support/api-client.ts
+++ b/sdk/typescript/tests-ts/support/api-client.ts
@@ -5,8 +5,14 @@ type ClientArguments = ConstructorParameters<typeof CodexSecurity>;
export const TEST_SNAPSHOT_DIGEST = `codex-security-snapshot/v1:sha256:${"a".repeat(64)}`;
-export function mockScanRegistration(args: readonly string[]) {
- const recipe = JSON.parse(args[args.indexOf("--recipe-json") + 1]!) as {
+export function mockScanRegistration(
+ args: readonly string[],
+ input?: string,
+): JsonObject {
+ if (!args.includes("--recipe-json-stdin") || input === undefined) {
+ throw new Error("missing stdin scan recipe");
+ }
+ const recipe = JSON.parse(input) as {
repositoryRevision?: string;
target: { kind: string };
};
@@ -33,8 +39,13 @@ export function mockScanRegistration(args: readonly string[]) {
};
}
-export function mockWorkbench(args: readonly string[]): JsonObject {
- if (args[0] === "register-cli-scan") return mockScanRegistration(args);
+export function mockWorkbench(
+ args: readonly string[],
+ input?: string,
+): JsonObject {
+ if (args[0] === "register-cli-scan") {
+ return mockScanRegistration(args, input);
+ }
if (args[0] === "get-scan-feedback") {
return {
scanId: "scan_example_001",
@@ -57,7 +68,8 @@ export class TestClient extends CodexSecurity {
throw new Error("Unexpected Codex invocation in test");
},
environment: {},
- runWorkbench: async (_options, args) => mockWorkbench(args),
+ runWorkbench: async (_options, args, input) =>
+ mockWorkbench(args, input),
...dependencies,
},
{ surface: "sdk" },
diff --git a/sdk/typescript/tests-ts/workbench-progress.test.ts b/sdk/typescript/tests-ts/workbench-progress.test.ts
index 75c9868aa..1702ba46d 100644
--- a/sdk/typescript/tests-ts/workbench-progress.test.ts
+++ b/sdk/typescript/tests-ts/workbench-progress.test.ts
@@ -3,9 +3,10 @@ import { join } from "node:path";
import { describe, expect, test } from "bun:test";
import { PLUGIN_ROOT } from "./plugin-root.js";
-function validatePreflightIssues(issues: object[]) {
+function validatePreflightIssues(issues: object[], stdin = false) {
const python = Bun.which("python3") ?? Bun.which("python");
expect(python).not.toBeNull();
+ const serialized = JSON.stringify(issues);
return spawnSync(
python!,
[
@@ -18,17 +19,19 @@ function validatePreflightIssues(issues: object[]) {
"from workbench_cli import parse_args",
"from workbench_progress import preflight_issues_json",
"args = parse_args('Synthetic workbench progress')",
- "issues = json.loads(preflight_issues_json(args.preflight_issues_json))",
+ "payload = sys.stdin.read() if args.preflight_issues_json_stdin else args.preflight_issues_json",
+ "issues = json.loads(preflight_issues_json(payload))",
"print(json.dumps({'count': len(issues), 'reasonLength': len(issues[0]['reason'])}))",
].join("\n"),
join(PLUGIN_ROOT, "scripts"),
"update-progress",
"--scan-id",
"00000000-0000-4000-8000-000000000000",
- "--preflight-issues-json",
- JSON.stringify(issues),
+ ...(stdin
+ ? ["--preflight-issues-json-stdin"]
+ : ["--preflight-issues-json", serialized]),
],
- { encoding: "utf8" },
+ { encoding: "utf8", input: stdin ? serialized : undefined },
);
}
@@ -57,6 +60,19 @@ describe("workbench preflight progress", () => {
});
});
+ test("accepts the declared maximum through stdin", () => {
+ const issues = Array.from({ length: 32 }, () => issue("x".repeat(1_200)));
+ expect(JSON.stringify(issues).length).toBeGreaterThan(32 * 1024);
+
+ const result = validatePreflightIssues(issues, true);
+
+ expect(result.status, result.stderr).toBe(0);
+ expect(JSON.parse(result.stdout)).toEqual({
+ count: 32,
+ reasonLength: 1_200,
+ });
+ });
+
test("preserves upstream issue-count and reason-length limits", () => {
const excessIssues = validatePreflightIssues(
Array.from({ length: 33 }, () => issue()),
diff --git a/sdk/typescript/tests-ts/workbench-scan-history.test.ts b/sdk/typescript/tests-ts/workbench-scan-history.test.ts
index 57ad27e7d..7ce34afbb 100644
--- a/sdk/typescript/tests-ts/workbench-scan-history.test.ts
+++ b/sdk/typescript/tests-ts/workbench-scan-history.test.ts
@@ -62,3 +62,47 @@ test("loads each scan's matching findings once across historical batches", async
},
});
});
+
+test("loads oversized comparison matches from stdin", async () => {
+ const python = await resolvePluginPython();
+
+ const probe = [
+ "import argparse, io, json, sqlite3, sys",
+ "sys.path.insert(0, sys.argv[1])",
+ "import workbench_scan_history as history",
+ "connection = sqlite3.connect(':memory:')",
+ "connection.row_factory = sqlite3.Row",
+ "connection.executescript('''",
+ "CREATE TABLE scan_comparisons (before_scan_id TEXT, after_scan_id TEXT, result_json TEXT, created_at TEXT, updated_at TEXT);",
+ "CREATE TABLE scan_comparison_matches (before_scan_id TEXT, after_scan_id TEXT, before_occurrence_id TEXT, after_occurrence_id TEXT, reason TEXT);",
+ "''')",
+ "scans = {'before': {'id': 'before', 'status': 'complete', 'target_id': 'target', 'target_path': '/repo'}, 'after': {'id': 'after', 'status': 'complete', 'target_id': 'target', 'target_path': '/repo'}}",
+ "findings = {'before': {'old': {'id': 'old'}}, 'after': {'new': {'id': 'new'}}}",
+ "history._scan_findings = lambda _connection, scan_id: findings[scan_id]",
+ "history.compare_scans = lambda *_args, **_kwargs: {'saved': True}",
+ "payload = sys.stdin.read()",
+ "sys.stdin = io.StringIO(payload)",
+ "result = history.save_scan_comparison(connection, argparse.Namespace(before_scan_id='before', after_scan_id='after', matches_json=None, matches_json_stdin=True), now=lambda: 'now', require_scan=lambda _connection, scan_id: scans[scan_id], read_coverage=lambda _scan: {})",
+ "print(json.dumps(result))",
+ ].join("\n");
+ const payload = JSON.stringify({
+ matches: [
+ {
+ beforeOccurrenceIds: ["old"],
+ afterOccurrenceIds: ["new"],
+ reason: "x".repeat(64 * 1024),
+ },
+ ],
+ uncertain: [],
+ });
+
+ const result = spawnSync(
+ python,
+ ["-I", "-B", "-c", probe, join(PLUGIN_ROOT, "scripts")],
+ { encoding: "utf8", input: payload, timeout: 10_000, windowsHide: true },
+ );
+
+ expect(result.status, result.stderr || result.error?.message).toBe(0);
+ expect(result.stderr).toBe("");
+ expect(JSON.parse(result.stdout)).toEqual({ saved: true });
+});