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

refactor(sdk): consolidate helpers and adjacent tooling (#1194)

mldangelo-oai202a1022fb6b
diff --git a/plugins/codex-security/scripts/rank_preview.py b/plugins/codex-security/scripts/rank_preview.py
index 80d9a1de9..9484b95d6 100644
--- a/plugins/codex-security/scripts/rank_preview.py
+++ b/plugins/codex-security/scripts/rank_preview.py
@@ -866,14 +866,6 @@ def simple_language_outline(text: str, suffix: str) -> list[str]:
match = re.match(r"^class\s+([A-Za-z_]\w*)", line)
if match:
add(f"class {match.group(1)}")
- elif suffix == ".rb":
- match = re.match(r"^(class|module)\s+([A-Z]\w*(?:::[A-Z]\w*)*)", line)
- if match:
- add(f"{match.group(1)} {match.group(2)}")
- continue
- match = re.match(r"^def\s+(?:self\.)?([^\s(]+)", line)
- if match:
- add(f"function {match.group(1)}")
elif suffix in {".ex", ".exs"}:
match = re.match(r"^defmodule\s+([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)", line)
if match:
diff --git a/plugins/codex-security/scripts/workbench_cli.py b/plugins/codex-security/scripts/workbench_cli.py
index dc538fd41..f43a64673 100644
--- a/plugins/codex-security/scripts/workbench_cli.py
+++ b/plugins/codex-security/scripts/workbench_cli.py
@@ -10,6 +10,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import deep_scan_workbench as deep_scan
import workbench_remediation as remediation
+from deep_scan_workbench import non_negative_int
from workbench_constants import (
DIFF_TARGET_KINDS,
EXPORT_FORMATS,
@@ -395,13 +396,6 @@ def parse_args(description: str) -> argparse.Namespace:
return parser.parse_args(arguments)
-def non_negative_int(value: str) -> int:
- parsed = int(value)
- if parsed < 0:
- raise argparse.ArgumentTypeError("expected a non-negative integer")
- return parsed
-
-
def positive_int(value: str) -> int:
parsed = int(value)
if parsed < 1:
diff --git a/sdk/typescript/scripts/build-plugin.mjs b/sdk/typescript/scripts/build-plugin.mjs
index 7f8dbbbce..455c9147a 100644
--- a/sdk/typescript/scripts/build-plugin.mjs
+++ b/sdk/typescript/scripts/build-plugin.mjs
@@ -11,17 +11,13 @@ import {
import { dirname, join, posix, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { promisify } from "node:util";
+import { pluginContractFiles } from "./plugin-contract.mjs";
const scriptDirectory = dirname(fileURLToPath(import.meta.url));
const packageRoot = resolve(scriptDirectory, "..");
const repositoryRoot = resolve(packageRoot, "../..");
-const publicManifest = ".codex-plugin/plugin.json";
const execFileAsync = promisify(execFile);
-function sourcePath(root, relativePath) {
- return join(root, ...relativePath.split("/"));
-}
-
function validatePath(path) {
const parts = path.split("/");
if (
@@ -37,7 +33,7 @@ function validatePath(path) {
}
async function destinationFiles(root, prefix = "") {
- const entries = await readdir(sourcePath(root, prefix), {
+ const entries = await readdir(join(root, prefix), {
withFileTypes: true,
});
const files = [];
@@ -65,25 +61,7 @@ export async function buildBundledPlugin({
source = join(repositoryRoot, "plugins", "codex-security"),
} = {}) {
const contract = JSON.parse(await readFile(contractPath, "utf8"));
- const { externalOwnedExact, shippedExact } = contract;
- if (
- !Array.isArray(externalOwnedExact) ||
- !externalOwnedExact.every((path) => typeof path === "string") ||
- !Array.isArray(shippedExact) ||
- !shippedExact.every((path) => typeof path === "string")
- ) {
- throw new Error("Plugin projection contract contains invalid paths.");
- }
- if (!externalOwnedExact.includes(publicManifest)) {
- throw new Error(
- "Plugin projection contract must declare the public manifest as externally owned.",
- );
- }
-
- const files = [
- publicManifest,
- ...shippedExact.filter((path) => !path.startsWith("sdk/")),
- ];
+ const files = pluginContractFiles(contract);
files.forEach(validatePath);
if (new Set(files).size !== files.length) {
throw new Error("Plugin projection contract contains duplicate paths.");
@@ -92,7 +70,7 @@ export async function buildBundledPlugin({
const copiedPaths = files.filter((path) => !path.startsWith("mcp/"));
const sourceFiles = await Promise.all(
copiedPaths.map(async (path) => {
- const file = sourcePath(source, path);
+ const file = join(source, path);
let metadata;
try {
metadata = await lstat(file);
@@ -113,19 +91,19 @@ export async function buildBundledPlugin({
await rm(destination, { force: true, recursive: true });
if (files.some((path) => path.startsWith("mcp/"))) {
- const mcpApp = sourcePath(source, "mcp-app");
+ const mcpApp = join(source, "mcp-app");
await execFileAsync(
process.execPath,
[
- sourcePath(mcpApp, "scripts/build_mcp_app.mjs"),
+ join(mcpApp, "scripts/build_mcp_app.mjs"),
"--output",
- sourcePath(destination, "mcp"),
+ join(destination, "mcp"),
],
{ cwd: mcpApp, maxBuffer: 10 * 1024 * 1024 },
);
}
for (const { file, mode, path } of sourceFiles) {
- const output = sourcePath(destination, path);
+ const output = join(destination, path);
await mkdir(dirname(output), { recursive: true });
await copyFile(file, output);
await chmod(output, mode);
diff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjs
index 629e89096..0388a6414 100644
--- a/sdk/typescript/scripts/check-package.mjs
+++ b/sdk/typescript/scripts/check-package.mjs
@@ -10,6 +10,7 @@ import {
import { assertExpectedGitHead } from "./package-provenance.mjs";
import { packageSmokeTimeouts } from "./package-smoke-timeouts.mjs";
import { regularTarListingLines } from "./package-tar-listing.mjs";
+import { pluginContractFiles } from "./plugin-contract.mjs";
const PACKAGE_SMOKE_PROCESS_TIMEOUT_MS =
packageSmokeTimeouts().processTimeoutMs;
@@ -129,25 +130,7 @@ for (const file of required) {
}
const contract = JSON.parse(readFileSync(contractPath, "utf8"));
-const { externalOwnedExact, shippedExact } = contract;
-if (
- !Array.isArray(externalOwnedExact) ||
- !externalOwnedExact.every((path) => typeof path === "string") ||
- !Array.isArray(shippedExact) ||
- !shippedExact.every((path) => typeof path === "string")
-) {
- throw new Error("Plugin projection contract contains invalid paths.");
-}
-const publicManifest = ".codex-plugin/plugin.json";
-if (!externalOwnedExact.includes(publicManifest)) {
- throw new Error(
- "Plugin projection contract must declare the public manifest as externally owned.",
- );
-}
-const pluginPaths = [
- publicManifest,
- ...shippedExact.filter((path) => !path.startsWith("sdk/")),
-];
+const pluginPaths = pluginContractFiles(contract);
const pluginFiles = new Set(pluginPaths);
if (pluginFiles.size !== pluginPaths.length) {
throw new Error("Plugin projection contract contains duplicate paths.");
@@ -227,6 +210,7 @@ const distFiles = new Set(
"publication-store",
"publish",
"result",
+ "record",
"runtime",
"scan-activity",
"scan-comparison",
diff --git a/sdk/typescript/scripts/plugin-contract.mjs b/sdk/typescript/scripts/plugin-contract.mjs
new file mode 100644
index 000000000..3c0fdd2e3
--- /dev/null
+++ b/sdk/typescript/scripts/plugin-contract.mjs
@@ -0,0 +1,22 @@
+export function pluginContractFiles(contract) {
+ const publicManifest = ".codex-plugin/plugin.json";
+ const { externalOwnedExact, shippedExact } = contract;
+ if (
+ !Array.isArray(externalOwnedExact) ||
+ !externalOwnedExact.every((path) => typeof path === "string") ||
+ !Array.isArray(shippedExact) ||
+ !shippedExact.every((path) => typeof path === "string")
+ ) {
+ throw new Error("Plugin projection contract contains invalid paths.");
+ }
+ if (!externalOwnedExact.includes(publicManifest)) {
+ throw new Error(
+ "Plugin projection contract must declare the public manifest as externally owned.",
+ );
+ }
+
+ return [
+ publicManifest,
+ ...shippedExact.filter((path) => !path.startsWith("sdk/")),
+ ];
+}
diff --git a/sdk/typescript/scripts/release-automation.mjs b/sdk/typescript/scripts/release-automation.mjs
index 3c4e0b707..30664a9ec 100644
--- a/sdk/typescript/scripts/release-automation.mjs
+++ b/sdk/typescript/scripts/release-automation.mjs
@@ -1,4 +1,4 @@
-import { createHash, X509Certificate } from "node:crypto";
+import { X509Certificate, hash } from "node:crypto";
import { readFileSync } from "node:fs";
import { basename } from "node:path";
import { pathToFileURL } from "node:url";
@@ -509,8 +509,7 @@ export function verifyPublishedRelease(metadata, archive, expected) {
assertExpectedGitHead(metadata, expected.gitHead);
const integrity = metadata["dist.integrity"] ?? metadata.dist?.integrity;
- const expectedIntegrity =
- "sha512-" + createHash("sha512").update(archive).digest("base64");
+ const expectedIntegrity = "sha512-" + hash("sha512", archive, "base64");
if (integrity !== expectedIntegrity) {
throw new Error(
"Published npm integrity must match the verified release artifact.",
@@ -527,7 +526,7 @@ export function verifyPublishedRelease(metadata, archive, expected) {
version,
gitHead: expected.gitHead,
integrity: expectedIntegrity,
- sha256: createHash("sha256").update(archive).digest("hex"),
+ sha256: hash("sha256", archive),
};
}
@@ -538,7 +537,7 @@ export function verifyGitHubPublishedRelease(
provenance,
) {
const version = releaseVersion(metadata);
- const sha512 = createHash("sha512").update(archive).digest("hex");
+ const sha512 = hash("sha512", archive);
if (
provenance?.version !== version ||
provenance.gitHead !== expected.gitHead ||
@@ -631,7 +630,7 @@ export function verifySignatureAudit(report, archive, expected) {
throw new Error("The verified SLSA provenance statement is invalid.");
}
- const sha512 = createHash("sha512").update(archive).digest("hex");
+ const sha512 = hash("sha512", archive);
const expectedSubject = `pkg:npm/%40openai/codex-security@${version}`;
if (
!Array.isArray(statement.subject) ||
@@ -802,8 +801,7 @@ export function verifyGitHubRelease(
throw new Error("Existing GitHub Release must be published and stable.");
}
- const expectedDigest =
- "sha256:" + createHash("sha256").update(archive).digest("hex");
+ const expectedDigest = "sha256:" + hash("sha256", archive);
const asset = Array.isArray(release.assets)
? release.assets.find((candidate) => candidate?.name === assetName)
: undefined;
@@ -811,8 +809,7 @@ export function verifyGitHubRelease(
const downloadedDigest =
downloadedArchive === undefined
? undefined
- : "sha256:" +
- createHash("sha256").update(downloadedArchive).digest("hex");
+ : "sha256:" + hash("sha256", downloadedArchive);
if (
asset === undefined ||
(publishedDigest != null && publishedDigest !== expectedDigest) ||
diff --git a/sdk/typescript/scripts/release-pr.mjs b/sdk/typescript/scripts/release-pr.mjs
index cb899f773..1295ebe01 100644
--- a/sdk/typescript/scripts/release-pr.mjs
+++ b/sdk/typescript/scripts/release-pr.mjs
@@ -1,5 +1,5 @@
import { execFileSync } from "node:child_process";
-import { createHash } from "node:crypto";
+import { hash } from "node:crypto";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath, pathToFileURL } from "node:url";
import { isDeepStrictEqual } from "node:util";
@@ -114,10 +114,6 @@ function findSection(notes, id) {
return { start, end, text: notes.slice(start, end) };
}
-function hash(value) {
- return createHash("sha256").update(value).digest("hex");
-}
-
export function updateReleaseNotes(
version,
generated,
@@ -129,7 +125,10 @@ export function updateReleaseNotes(
if (previousSections === undefined) {
const blocks = sectionIds.map((id) => {
const block = sectionBlock(id, generated[id]);
- sections[id] = { generatedHash: hash(block), humanOwned: false };
+ sections[id] = {
+ generatedHash: hash("sha256", block),
+ humanOwned: false,
+ };
return block;
});
return { notes: `${header}\n\n${blocks.join("\n\n")}\n`, sections };
@@ -148,7 +147,7 @@ export function updateReleaseNotes(
previous?.reset !== true &&
(previous?.humanOwned !== false ||
block === null ||
- hash(block.text) !== previous.generatedHash);
+ hash("sha256", block.text) !== previous.generatedHash);
if (humanOwned) {
sections[id] = {
generatedHash: previous?.generatedHash ?? null,
@@ -162,7 +161,7 @@ export function updateReleaseNotes(
} else {
notes = notes.slice(0, block.start) + next + notes.slice(block.end);
}
- sections[id] = { generatedHash: hash(next), humanOwned: false };
+ sections[id] = { generatedHash: hash("sha256", next), humanOwned: false };
}
return { notes, sections };
}
@@ -475,8 +474,8 @@ async function ensurePullRequest(
};
}
const marker = `<!-- release-pr-head: ${headSha} -->`;
- const proposalMarker = `<!-- release-pr-proposal: ${hash(JSON.stringify(plan.files))} -->`;
- const suggestionsMarker = `<!-- release-pr-suggestions: ${hash(JSON.stringify(plan.generated))} -->`;
+ const proposalMarker = `<!-- release-pr-proposal: ${hash("sha256", JSON.stringify(plan.files))} -->`;
+ const suggestionsMarker = `<!-- release-pr-suggestions: ${hash("sha256", JSON.stringify(plan.generated))} -->`;
const comments = await github.list(
`issues/${current.number}/comments?per_page=100`,
);
diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.ts
index fe602fdf9..f7825cc00 100644
--- a/sdk/typescript/src/api.ts
+++ b/sdk/typescript/src/api.ts
@@ -30,6 +30,7 @@ import {
type TurnOptions,
} from "@openai/codex-sdk";
import { z } from "incur";
+import { isRecord } from "./record.js";
import {
CODEX_AUTH_CONFIG_KEYS,
NO_CREDENTIALS_MESSAGE,
@@ -4432,10 +4433,6 @@ function environmentApiKeyEntry(
return null;
}
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-
function reconnectAttempt(message: string): [number, number] | null {
const match =
/^Reconnecting(?:\.\.\.|…)[ \t]+([1-9]\d{0,2})\/([1-9]\d{0,2})(?=[ \t(]|$)/u.exec(
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index d7af73c9f..764304da7 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -74,6 +74,7 @@ import {
readCodexHomeConfig,
} from "./auth.js";
import { loadContract } from "./contract.js";
+import { isRecord as isJsonObject } from "./record.js";
import { suggestOwnersInternal } from "./suggest-owners.js";
import { parseImportedFindings } from "./findings-import.js";
import { publishScanToCustom } from "./custom-publish.js";
@@ -1809,10 +1810,7 @@ export async function main(
return 2;
}
const controller = new AbortController();
- const interrupt = () => controller.abort("SIGINT");
- const terminate = () => controller.abort("SIGTERM");
- dependencies.addSignalListener("SIGINT", interrupt);
- dependencies.addSignalListener("SIGTERM", terminate);
+ const removeSignals = listenForAbort(dependencies, controller);
let exitCode: number;
try {
const code = await runRecordsProtocol(
@@ -1827,8 +1825,7 @@ export async function main(
? 143
: code;
} finally {
- dependencies.removeSignalListener("SIGINT", interrupt);
- dependencies.removeSignalListener("SIGTERM", terminate);
+ removeSignals();
}
// Protocol writes have flushed or been canceled. Node's stdout ignores destroy().
if (output === process.stdout) process.exit(exitCode);
@@ -2384,7 +2381,6 @@ export async function main(
scanId,
]);
if (
- recipe !== undefined &&
isJsonObject(recipe) &&
recipe["import"] !== undefined &&
isJsonObject(recipe["import"])
@@ -2891,7 +2887,6 @@ export async function main(
scanId.length === 0 ||
typeof directory !== "string" ||
directory.length === 0 ||
- progress === undefined ||
!isJsonObject(progress) ||
progress["status"] !== "complete"
) {
@@ -3191,10 +3186,7 @@ export async function main(
output: z.record(z.string(), z.unknown()).optional(),
async run({ args, options }) {
const controller = new AbortController();
- const onInterrupt = (): void => controller.abort("SIGINT");
- const onTerminate = (): void => controller.abort("SIGTERM");
- dependencies.addSignalListener("SIGINT", onInterrupt);
- dependencies.addSignalListener("SIGTERM", onTerminate);
+ const removeSignals = listenForAbort(dependencies, controller);
try {
const result = await (
dependencies.checkScanPublication ?? checkScanPublication
@@ -3208,8 +3200,7 @@ export async function main(
reportPublicationError(error, controller.signal.reason);
return undefined;
} finally {
- dependencies.removeSignalListener("SIGINT", onInterrupt);
- dependencies.removeSignalListener("SIGTERM", onTerminate);
+ removeSignals();
}
},
});
@@ -3261,10 +3252,7 @@ export async function main(
.optional(),
async run({ args, options }) {
const controller = new AbortController();
- const onInterrupt = () => controller.abort("SIGINT");
- const onTerminate = () => controller.abort("SIGTERM");
- dependencies.addSignalListener("SIGINT", onInterrupt);
- dependencies.addSignalListener("SIGTERM", onTerminate);
+ const removeSignals = listenForAbort(dependencies, controller);
try {
return await (
dependencies.importGitHubAlerts ?? importGitHubCodeScanningAlerts
@@ -3294,8 +3282,7 @@ export async function main(
}
return undefined;
} finally {
- dependencies.removeSignalListener("SIGINT", onInterrupt);
- dependencies.removeSignalListener("SIGTERM", onTerminate);
+ removeSignals();
}
},
});
@@ -3875,10 +3862,7 @@ export async function main(
output: z.record(z.string(), z.unknown()).optional(),
async run({ args, options }) {
const controller = new AbortController();
- const onInterrupt = () => controller.abort("SIGINT");
- const onTerminate = () => controller.abort("SIGTERM");
- dependencies.addSignalListener("SIGINT", onInterrupt);
- dependencies.addSignalListener("SIGTERM", onTerminate);
+ const removeSignals = listenForAbort(dependencies, controller);
try {
const directory = dependencies.currentDirectory();
const repository = resolveCliPath(
@@ -3917,8 +3901,7 @@ export async function main(
exitCode = signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 2;
return undefined;
} finally {
- dependencies.removeSignalListener("SIGINT", onInterrupt);
- dependencies.removeSignalListener("SIGTERM", onTerminate);
+ removeSignals();
}
},
})
@@ -3965,10 +3948,7 @@ export async function main(
output: z.record(z.string(), z.unknown()).optional(),
async run({ options }) {
const controller = new AbortController();
- const onInterrupt = () => controller.abort("SIGINT");
- const onTerminate = () => controller.abort("SIGTERM");
- dependencies.addSignalListener("SIGINT", onInterrupt);
- dependencies.addSignalListener("SIGTERM", onTerminate);
+ const removeSignals = listenForAbort(dependencies, controller);
try {
if (
(options.scan === undefined) ===
@@ -4019,8 +3999,7 @@ export async function main(
exitCode = signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 2;
return undefined;
} finally {
- dependencies.removeSignalListener("SIGINT", onInterrupt);
- dependencies.removeSignalListener("SIGTERM", onTerminate);
+ removeSignals();
}
},
})
@@ -4089,10 +4068,7 @@ export async function main(
if (options.records)
throw new CodexSecurityError("Use dedupe --records alone.");
const controller = new AbortController();
- const onInterrupt = () => controller.abort("SIGINT");
- const onTerminate = () => controller.abort("SIGTERM");
- dependencies.addSignalListener("SIGINT", onInterrupt);
- dependencies.addSignalListener("SIGTERM", onTerminate);
+ const removeSignals = listenForAbort(dependencies, controller);
try {
if (options.findingsUrl === undefined)
throw new CodexSecurityError(
@@ -4149,8 +4125,7 @@ export async function main(
exitCode = signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 2;
return undefined;
} finally {
- dependencies.removeSignalListener("SIGINT", onInterrupt);
- dependencies.removeSignalListener("SIGTERM", onTerminate);
+ removeSignals();
}
},
})
@@ -4262,12 +4237,7 @@ export async function main(
};
const onInterrupt = (): void => controller.abort("SIGINT");
const onTerminate = (): void => controller.abort("SIGTERM");
- const interruptedExitCode = (): number | undefined =>
- controller.signal.reason === "SIGINT"
- ? 130
- : controller.signal.reason === "SIGTERM"
- ? 143
- : undefined;
+
dependencies.addSignalListener("SIGINT", onInterrupt);
dependencies.addSignalListener("SIGTERM", onTerminate);
try {
@@ -4411,7 +4381,7 @@ export async function main(
},
});
exitCode =
- interruptedExitCode() ??
+ interruptedExitCode(controller.signal) ??
(result.failed ||
result.incomplete ||
result.deduplication?.status === "incomplete"
@@ -4422,7 +4392,7 @@ export async function main(
return { ...result };
} catch (error) {
stopDashboard();
- exitCode = interruptedExitCode() ?? 2;
+ exitCode = interruptedExitCode(controller.signal) ?? 2;
errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
} finally {
stopDashboard();
@@ -4529,16 +4499,8 @@ export async function main(
output: z.record(z.string(), z.unknown()).optional(),
async run({ args, options }) {
const controller = new AbortController();
- const onInterrupt = (): void => controller.abort("SIGINT");
- const onTerminate = (): void => controller.abort("SIGTERM");
- const interruptedExitCode = (): number | undefined =>
- controller.signal.reason === "SIGINT"
- ? 130
- : controller.signal.reason === "SIGTERM"
- ? 143
- : undefined;
- dependencies.addSignalListener("SIGINT", onInterrupt);
- dependencies.addSignalListener("SIGTERM", onTerminate);
+
+ const removeSignals = listenForAbort(dependencies, controller);
try {
const currentDirectory = dependencies.currentDirectory();
if (options.recover && args.input === undefined) {
@@ -4743,7 +4705,7 @@ export async function main(
},
});
exitCode =
- interruptedExitCode() ??
+ interruptedExitCode(controller.signal) ??
(result.failed > 0 || result.incomplete > 0
? 2
: result.policyFailed
@@ -4752,14 +4714,13 @@ export async function main(
return { ...result };
} catch (error) {
exitCode =
- interruptedExitCode() ??
+ interruptedExitCode(controller.signal) ??
(error instanceof Error && error.name === "ExitPromptError"
? 130
: 2);
errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
} finally {
- dependencies.removeSignalListener("SIGINT", onInterrupt);
- dependencies.removeSignalListener("SIGTERM", onTerminate);
+ removeSignals();
}
},
})
@@ -5745,10 +5706,7 @@ export async function main(
"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);
+ const removeSignals = listenForAbort(dependencies, controller);
try {
return await (dependencies.sendFeedback ?? sendFeedback)({
...options,
@@ -5764,8 +5722,7 @@ export async function main(
}
throw error;
} finally {
- dependencies.removeSignalListener("SIGINT", onInterrupt);
- dependencies.removeSignalListener("SIGTERM", onTerminate);
+ removeSignals();
}
},
})
@@ -5991,10 +5948,7 @@ async function runScanImport(
dependencies: CliDependencies,
): Promise<ScanOutcome> {
const controller = new AbortController();
- const onInterrupt = () => controller.abort("SIGINT");
- const onTerminate = () => controller.abort("SIGTERM");
- dependencies.addSignalListener("SIGINT", onInterrupt);
- dependencies.addSignalListener("SIGTERM", onTerminate);
+ const removeSignals = listenForAbort(dependencies, controller);
try {
const result = await (dependencies.importScan ?? importScan)(
{ ...options, signal: controller.signal },
@@ -6020,8 +5974,7 @@ async function runScanImport(
error: message,
};
} finally {
- dependencies.removeSignalListener("SIGINT", onInterrupt);
- dependencies.removeSignalListener("SIGTERM", onTerminate);
+ removeSignals();
}
}
@@ -8347,11 +8300,7 @@ async function executeScan(
scanModelConfiguration(effectiveConfiguration));
const provider = scanModelProvider(effectiveConfiguration);
const analytics = effectiveConfiguration["analytics"];
- if (
- analytics !== undefined &&
- isJsonObject(analytics) &&
- analytics["enabled"] !== undefined
- ) {
+ if (isJsonObject(analytics) && analytics["enabled"] !== undefined) {
patchAnalyticsOverride = `analytics.enabled=${JSON.stringify(analytics["enabled"])}`;
}
auth =
@@ -9834,10 +9783,6 @@ function interruptedExit(
return ctrlC ? 130 : 143;
}
-function isJsonObject(value: JsonValue): value is JsonObject {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-
function invokedAsMain(): boolean {
const entrypoint = process.argv[1];
if (entrypoint === undefined) return false;
@@ -9849,6 +9794,13 @@ function invokedAsMain(): boolean {
}
}
+const interruptedExitCode = (signal: AbortSignal): number | undefined =>
+ signal.reason === "SIGINT"
+ ? 130
+ : signal.reason === "SIGTERM"
+ ? 143
+ : undefined;
+
if (invokedAsMain()) {
void main().then(
(exitCode) => {
@@ -9860,3 +9812,20 @@ if (invokedAsMain()) {
},
);
}
+
+function listenForAbort(
+ dependencies: Pick<
+ CliDependencies,
+ "addSignalListener" | "removeSignalListener"
+ >,
+ controller: AbortController,
+): () => void {
+ const onInterrupt = () => controller.abort("SIGINT");
+ const onTerminate = () => controller.abort("SIGTERM");
+ dependencies.addSignalListener("SIGINT", onInterrupt);
+ dependencies.addSignalListener("SIGTERM", onTerminate);
+ return () => {
+ dependencies.removeSignalListener("SIGINT", onInterrupt);
+ dependencies.removeSignalListener("SIGTERM", onTerminate);
+ };
+}
diff --git a/sdk/typescript/src/cloud-publish.ts b/sdk/typescript/src/cloud-publish.ts
index ca1be47a8..3244bb8a7 100644
--- a/sdk/typescript/src/cloud-publish.ts
+++ b/sdk/typescript/src/cloud-publish.ts
@@ -1,4 +1,4 @@
-import { createHash } from "node:crypto";
+import { hash } from "node:crypto";
import { existsSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
@@ -90,8 +90,9 @@ export async function publishFindingsCsvToCloud(
}
dependencies.signal?.throwIfAborted();
const rows = parseFindingsCsv(source);
- const digest = sha256(source);
- const scanId = `scan_csv_${sha256(
+ const digest = hash("sha256", source);
+ const scanId = `scan_csv_${hash(
+ "sha256",
["codex-security-csv-import/v1", VERSION, source].join("\0"),
).slice(0, 24)}`;
const findings = rows.map((row) => csvRowFinding(row, scanId));
@@ -143,12 +144,12 @@ export async function publishFindingsCsvToCloud(
artifacts: [
{
path: "findings.json",
- sha256: sha256(findingsDocument),
+ sha256: hash("sha256", findingsDocument),
mediaType: "application/json",
},
{
path: "coverage.json",
- sha256: sha256(coverageDocument),
+ sha256: hash("sha256", coverageDocument),
mediaType: "application/json",
},
{
@@ -161,10 +162,6 @@ export async function publishFindingsCsvToCloud(
return publishCloudPayload(scan, findings, dependencies);
}
-function sha256(value: string): string {
- return createHash("sha256").update(value, "utf8").digest("hex");
-}
-
async function publishCloudPayload(
scan: ScanManifest["scan"],
findings: Finding[],
diff --git a/sdk/typescript/src/config.ts b/sdk/typescript/src/config.ts
index 9d28e61df..199e0636d 100644
--- a/sdk/typescript/src/config.ts
+++ b/sdk/typescript/src/config.ts
@@ -133,7 +133,7 @@ export function resolveCommandAuthConfig(
config: JsonObject,
home: string,
): JsonObject {
- const resolved = cloneJson(config);
+ const resolved = structuredClone(config);
const providers = resolved["model_providers"];
if (isObject(providers)) {
for (const provider of Object.values(providers)) {
@@ -194,7 +194,7 @@ function selectedScanProfile(
export function resolveCodexProfile(config: JsonObject): JsonObject {
const resolved = deepMerge(
- cloneJson(config),
+ structuredClone(config),
selectedScanProfile(config) ?? {},
);
delete resolved["profile"];
@@ -209,7 +209,7 @@ export async function mergedCodexConfig(
throw new ConfigurationError("codexOverrides must be an object.");
}
validateOverrideKeys(config.codexOverrides ?? {});
- const overrides = cloneJson(config.codexOverrides ?? {});
+ const overrides = structuredClone(config.codexOverrides ?? {});
validateOverrides(overrides);
validateNativeMultiAgentV2Overrides(overrides);
normalizeLegacyWindowsSandboxOverride(overrides);
@@ -221,7 +221,7 @@ export async function mergedCodexConfig(
}
}
}
- const defaults: JsonObject = cloneJson(DEFAULT_CODEX_CONFIG);
+ const defaults: JsonObject = structuredClone(DEFAULT_CODEX_CONFIG);
if (scanModelProvider(overrides) === "amazon-bedrock") {
// Bedrock models can reject reasoning.summary before the scan starts.
defaults["model_reasoning_summary"] = "none";
@@ -360,14 +360,8 @@ function validateNativeMultiAgentV2Overrides(overrides: JsonObject): void {
"features.multi_agent_v2.max_concurrent_threads_per_session instead.",
);
}
- if ("features" in overrides) {
- const features = overrides["features"];
- if (!isObject(features)) {
- throw new ConfigurationError(
- "The selected Codex Security plugin requires native multi-agent v2; " +
- "features must remain a table containing features.multi_agent_v2.",
- );
- }
+ const features = overrides["features"];
+ if (isObject(features)) {
if ("multi_agent_v2" in features) {
const multiAgentV2 = features["multi_agent_v2"];
if (!isObject(multiAgentV2)) {
@@ -421,7 +415,7 @@ export function mergeCodexOverrides(
): JsonObject {
validateOverrideKeys(base);
validateOverrideKeys(overrides);
- return deepMerge(cloneJson(base), overrides);
+ return deepMerge(structuredClone(base), overrides);
}
/** @internal */
@@ -431,15 +425,11 @@ export function deepMerge(base: JsonObject, overrides: JsonObject): JsonObject {
base[key] =
isObject(value) && isObject(existing)
? deepMerge({ ...existing }, value)
- : cloneJson(value);
+ : structuredClone(value);
}
return base;
}
-function cloneJson<T extends JsonValue>(value: T): T {
- return structuredClone(value);
-}
-
function deepFreezeJson(value: JsonValue): void {
if (typeof value !== "object" || value === null || Object.isFrozen(value)) {
return;
diff --git a/sdk/typescript/src/contract.ts b/sdk/typescript/src/contract.ts
index de90a7966..483ea0d90 100644
--- a/sdk/typescript/src/contract.ts
+++ b/sdk/typescript/src/contract.ts
@@ -1,4 +1,4 @@
-import { createHash } from "node:crypto";
+import { createHash, hash } from "node:crypto";
import { constants, type BigIntStats, type Stats } from "node:fs";
import {
lstat,
@@ -9,7 +9,8 @@ import {
} from "node:fs/promises";
import { isAbsolute, join, posix, relative, resolve, sep } from "node:path";
import Ajv2020, { type ErrorObject } from "ajv/dist/2020.js";
-import { ContractValidationError } from "./errors.js";
+import { ContractValidationError, abortReason } from "./errors.js";
+import { isRecord as isJsonRecord } from "./record.js";
import type {
CoverageDocument,
FindingsDocument,
@@ -208,13 +209,6 @@ export async function loadContractWithScanDirectory(
};
}
-export async function requireCanonicalScanDirectory(
- scanDirectory: string,
- signal?: AbortSignal,
-): Promise<string> {
- return (await requireScanRoot(scanDirectory, signal)).path;
-}
-
type JsonRecord = Record<string, unknown>;
/** Normalize optional legacy details on a copy, without changing saved artifacts. */
@@ -295,7 +289,12 @@ export function normalizePersistedFindings(payload: unknown): unknown {
const validation = finding["validation"];
if (isJsonRecord(validation)) {
- normalizeLegacyStringOrList(validation, "evidence");
+ if (
+ typeof validation["evidence"] !== "string" ||
+ validation["evidence"].length === 0
+ ) {
+ normalizeLegacyStringLists(validation, ["evidence"]);
+ }
removeUnsupportedLegacyStrings(validation, ["method", "summary"]);
removeUnsupportedLegacyNullableStrings(validation, [
"status",
@@ -351,10 +350,6 @@ export function normalizePersistedFindings(payload: unknown): unknown {
return compatible;
}
-function isJsonRecord(value: unknown): value is JsonRecord {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-
function normalizeLegacyStringLists(
section: JsonRecord,
fields: string[],
@@ -374,23 +369,6 @@ function normalizeLegacyStringLists(
}
}
-function normalizeLegacyStringOrList(section: JsonRecord, field: string): void {
- if (!(field in section)) return;
- const value = section[field];
- if (typeof value === "string") {
- if (value.length === 0) delete section[field];
- return;
- }
- if (!Array.isArray(value)) {
- delete section[field];
- return;
- }
- const normalized = value.filter(
- (item): item is string => typeof item === "string" && item.length > 0,
- );
- section[field] = normalized;
-}
-
function removeUnsupportedLegacyStrings(
section: JsonRecord,
fields: string[],
@@ -492,7 +470,8 @@ function validateCanonicalContract(
}
}
- const fingerprint = `codex-security/v1:sha256:${sha256Text(
+ const fingerprint = `codex-security/v1:sha256:${hash(
+ "sha256",
[
"codex-security/v1",
manifest.scan.target.targetId,
@@ -501,8 +480,9 @@ function validateCanonicalContract(
finding.identity.instance ?? "",
].join("\0"),
)}`;
- const findingId = `csf_${sha256Text(fingerprint).slice(0, 24)}`;
- const occurrenceId = `occ_${sha256Text(
+ const findingId = `csf_${hash("sha256", fingerprint).slice(0, 24)}`;
+ const occurrenceId = `occ_${hash(
+ "sha256",
[manifest.scan.id, fingerprint].join("\0"),
).slice(0, 24)}`;
if (finding.findingId !== findingId) {
@@ -523,10 +503,6 @@ function validateCanonicalContract(
}
}
-function sha256Text(value: string): string {
- return createHash("sha256").update(value, "utf8").digest("hex");
-}
-
export async function requireScanFile(
scanDirectory: string,
relativePath: string,
@@ -936,10 +912,7 @@ async function readScanJson(
);
try {
const bytes = await file.readFile({ signal });
- documentDigests.set(
- relativePath,
- createHash("sha256").update(bytes).digest("hex"),
- );
+ documentDigests.set(relativePath, hash("sha256", bytes));
return parseJson(join(scanDir, relativePath), bytes);
} catch (error) {
throwIfAborted(signal);
@@ -991,7 +964,7 @@ function parseJson(path: string, bytes: Uint8Array): Record<string, unknown> {
{ cause: error },
);
}
- if (!isRecord(payload)) {
+ if (!isJsonRecord(payload)) {
throw new ContractValidationError(`${path}: expected a JSON object.`);
}
validateParsedJson(payload, path);
@@ -1026,7 +999,7 @@ function validateParsedJson(value: unknown, context: string): void {
}
return;
}
- if (isRecord(value)) {
+ if (isJsonRecord(value)) {
for (const [key, item] of Object.entries(value)) {
if (!isWellFormedUnicode(key)) {
throw new ContractValidationError(
@@ -1196,10 +1169,7 @@ export async function sameCheckedFileDevice(
function throwIfAborted(signal?: AbortSignal): void {
if (!signal?.aborted) return;
- throw (
- signal.reason ??
- new DOMException("The operation was aborted.", "AbortError")
- );
+ throw abortReason(signal);
}
function validRfc3339DateTime(value: string): boolean {
@@ -1298,10 +1268,6 @@ function isContained(root: string, candidate: string): boolean {
);
}
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-
function nodeErrorCode(error: unknown): string | undefined {
return typeof error === "object" && error !== null && "code" in error
? String(error.code)
diff --git a/sdk/typescript/src/cost-model.ts b/sdk/typescript/src/cost-model.ts
index b3adcbf49..15da70d17 100644
--- a/sdk/typescript/src/cost-model.ts
+++ b/sdk/typescript/src/cost-model.ts
@@ -1,3 +1,5 @@
+import { isRecord } from "./record.js";
+
export interface ScanCost {
model: string;
inputTokens: number;
@@ -341,7 +343,3 @@ export function formatUsd(value: number): string {
function isTokenCount(value: unknown): value is number {
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
diff --git a/sdk/typescript/src/cost.ts b/sdk/typescript/src/cost.ts
index 2263f136f..29cb3ebfd 100644
--- a/sdk/typescript/src/cost.ts
+++ b/sdk/typescript/src/cost.ts
@@ -1,5 +1,6 @@
import { open, readdir } from "node:fs/promises";
import { join } from "node:path";
+import { isRecord } from "./record.js";
import {
estimateScanCost,
tokenUsage,
@@ -183,10 +184,8 @@ export class ScanCostTracker {
}
public async stop(fallbackUsage?: unknown): Promise<ScanCostSnapshot> {
- if (this.#timer !== null) {
- clearInterval(this.#timer);
- this.#timer = null;
- }
+ clearInterval(this.#timer ?? undefined);
+ this.#timer = null;
if (fallbackUsage !== undefined) this.recordUsage(fallbackUsage);
await this.refresh();
if (this.#receipts.size > 0 || this.#snapshot.usage !== null)
@@ -836,10 +835,6 @@ function subtractTokenUsage(
});
}
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-
function isMissingFile(error: unknown): boolean {
return isRecord(error) && error["code"] === "ENOENT";
}
diff --git a/sdk/typescript/src/deduplication/records-protocol.ts b/sdk/typescript/src/deduplication/records-protocol.ts
index 7e01c08bc..80e9d8814 100644
--- a/sdk/typescript/src/deduplication/records-protocol.ts
+++ b/sdk/typescript/src/deduplication/records-protocol.ts
@@ -55,10 +55,8 @@ export async function runRecordsProtocol(
let pending:
| { id: string; resolve(value: unknown): void; reject(error: Error): void }
| undefined;
- let complete!: (code: number) => void;
- const completion = new Promise<number>((resolve) => {
- complete = resolve;
- });
+ const { promise: completion, resolve: complete } =
+ Promise.withResolvers<number>();
const lines = createInterface({
input,
crlfDelay: Infinity,
diff --git a/sdk/typescript/src/deduplication/records.ts b/sdk/typescript/src/deduplication/records.ts
index a45cd1f38..cd66d7c38 100644
--- a/sdk/typescript/src/deduplication/records.ts
+++ b/sdk/typescript/src/deduplication/records.ts
@@ -1,4 +1,4 @@
-import { createHash, randomUUID } from "node:crypto";
+import { randomUUID, hash } from "node:crypto";
import { z } from "incur";
import { DeduplicationReviewError } from "../errors.js";
import type { Finding } from "../models.js";
@@ -111,10 +111,7 @@ export async function deduplicateRecords(
if (observations.has(entry.id))
throw new Error(`Duplicate observation ID: ${entry.id}`);
// Original finding IDs can repeat across scans; host IDs identify observations.
- const findingId = `csf_${createHash("sha256")
- .update(entry.id)
- .digest("hex")
- .slice(0, 24)}`;
+ const findingId = `csf_${hash("sha256", entry.id).slice(0, 24)}`;
observations.set(entry.id, { ...entry.finding, findingId });
references.set(findingId, entry.id);
}
diff --git a/sdk/typescript/src/deep-progress.ts b/sdk/typescript/src/deep-progress.ts
index 08487c415..189a4b2ca 100644
--- a/sdk/typescript/src/deep-progress.ts
+++ b/sdk/typescript/src/deep-progress.ts
@@ -1,3 +1,5 @@
+import { isRecord } from "./record.js";
+
export interface DeepScanProgress {
completed: number;
active: number;
@@ -78,10 +80,8 @@ export class DeepScanProgressTracker {
public stop(): void {
if (this.#stopped) return;
this.#stopped = true;
- if (this.#timer !== null) {
- clearInterval(this.#timer);
- this.#timer = null;
- }
+ clearInterval(this.#timer ?? undefined);
+ this.#timer = null;
this.#abortController?.abort();
this.#abortController = null;
}
@@ -131,7 +131,3 @@ function isCount(value: unknown): value is number {
function isPositiveCount(value: unknown): value is number {
return isCount(value) && value > 0;
}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return value !== null && typeof value === "object" && !Array.isArray(value);
-}
diff --git a/sdk/typescript/src/errors.ts b/sdk/typescript/src/errors.ts
index 7314dd6d2..78ed49ca8 100644
--- a/sdk/typescript/src/errors.ts
+++ b/sdk/typescript/src/errors.ts
@@ -5,6 +5,13 @@ export function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
+export function abortReason(signal: AbortSignal): unknown {
+ return (
+ signal.reason ??
+ new DOMException("The operation was aborted.", "AbortError")
+ );
+}
+
/** Base error for Codex Security SDK failures. */
export class CodexSecurityError extends Error {
public constructor(message: string, options?: ErrorOptions) {
diff --git a/sdk/typescript/src/findings-import.ts b/sdk/typescript/src/findings-import.ts
index 6ca87b12b..1f2b70f21 100644
--- a/sdk/typescript/src/findings-import.ts
+++ b/sdk/typescript/src/findings-import.ts
@@ -1,4 +1,4 @@
-import { createHash } from "node:crypto";
+import { hash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { isAbsolute, join, posix } from "node:path";
import Ajv2020 from "ajv/dist/2020.js";
@@ -177,7 +177,8 @@ export function bindImportedFindings(
return findings.map((finding) => {
const ruleId = `import.${format}`;
const anchor = finding.occurrenceId;
- const fingerprint = `codex-security/v1:sha256:${sha256(
+ const fingerprint = `codex-security/v1:sha256:${hash(
+ "sha256",
["codex-security/v1", targetId, ruleId, anchor, ""].join("\0"),
)}`;
// A source report path names another scan's artifact. Preserve it as
@@ -185,8 +186,8 @@ export function bindImportedFindings(
const { writeup, ...content } = finding;
return {
...content,
- findingId: `csf_${sha256(fingerprint).slice(0, 24)}`,
- occurrenceId: `occ_${sha256([scanId, fingerprint].join("\0")).slice(0, 24)}`,
+ findingId: `csf_${hash("sha256", fingerprint).slice(0, 24)}`,
+ occurrenceId: `occ_${hash("sha256", [scanId, fingerprint].join("\0")).slice(0, 24)}`,
ruleId,
identity: { anchor },
fingerprints: {
@@ -282,14 +283,15 @@ function decodeExportedCsvCell(value: string): string {
export function csvRowFinding(row: CsvFindingRow, scanId: string): Finding {
const ruleId = "import.csv";
const anchor = row.finding_id;
- const fingerprint = `codex-security/v1:sha256:${sha256(
+ const fingerprint = `codex-security/v1:sha256:${hash(
+ "sha256",
["codex-security/v1", CSV_TARGET_ID, ruleId, anchor, ""].join("\0"),
)}`;
- const findingId = `csf_${sha256(fingerprint).slice(0, 24)}`;
- const occurrenceId = `occ_${sha256([scanId, fingerprint].join("\0")).slice(
- 0,
- 24,
- )}`;
+ const findingId = `csf_${hash("sha256", fingerprint).slice(0, 24)}`;
+ const occurrenceId = `occ_${hash(
+ "sha256",
+ [scanId, fingerprint].join("\0"),
+ ).slice(0, 24)}`;
return {
findingId,
occurrenceId,
@@ -368,7 +370,3 @@ function safeFindingPath(value: string): boolean {
function csvRowError(rowNumber: number, detail: string): CodexSecurityError {
return new CodexSecurityError(`Findings CSV row ${rowNumber} ${detail}.`);
}
-
-function sha256(value: string): string {
- return createHash("sha256").update(value, "utf8").digest("hex");
-}
diff --git a/sdk/typescript/src/publication-events.ts b/sdk/typescript/src/publication-events.ts
index bd38ad912..9cd80e9a1 100644
--- a/sdk/typescript/src/publication-events.ts
+++ b/sdk/typescript/src/publication-events.ts
@@ -1,4 +1,5 @@
import { isLinearIssueIdentifier, linearIssueReference } from "./linear.js";
+import { isRecord } from "./record.js";
import {
linearPublicationArguments,
type PreparedPublicationIssue,
@@ -361,7 +362,3 @@ function containsIdentifier(value: string, identifier: string): boolean {
const escaped = identifier.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
return new RegExp(`(?<![\\w-])${escaped}(?![\\w-])`, "u").test(value);
}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
diff --git a/sdk/typescript/src/publication-store.ts b/sdk/typescript/src/publication-store.ts
index f4966ee4d..5b626251f 100644
--- a/sdk/typescript/src/publication-store.ts
+++ b/sdk/typescript/src/publication-store.ts
@@ -1,6 +1,7 @@
import { mkdtemp, realpath, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { isRecord } from "./record.js";
import { CodexSecurityError } from "./errors.js";
import type { PreparedScanPublication } from "./publication.js";
import type { PublishedScanIssue } from "./publish.js";
@@ -235,7 +236,3 @@ function invalidPublicationRecords(): CodexSecurityError {
"The workbench returned invalid persisted Linear publication records.",
);
}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
diff --git a/sdk/typescript/src/publish.ts b/sdk/typescript/src/publish.ts
index 4323f38cb..4eed00ba9 100644
--- a/sdk/typescript/src/publish.ts
+++ b/sdk/typescript/src/publish.ts
@@ -14,6 +14,7 @@ import {
writeFile,
} from "node:fs/promises";
import { join, win32 } from "node:path";
+import { isRecord } from "./record.js";
import {
InternalLinearError,
NetworkLinearError,
@@ -1556,10 +1557,8 @@ async function runPublicationCodex(
const cleanup = (): void => {
signal?.removeEventListener("abort", onAbort);
activePublicationProcesses.delete(child);
- if (forcedTermination !== undefined) {
- clearTimeout(forcedTermination);
- forcedTermination = undefined;
- }
+ clearTimeout(forcedTermination);
+ forcedTermination = undefined;
};
signal?.addEventListener("abort", onAbort, { once: true });
if (signal?.aborted === true) onAbort();
@@ -1742,7 +1741,3 @@ async function writePublicationReceipt(
mode: 0o600,
});
}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
diff --git a/sdk/typescript/src/record.ts b/sdk/typescript/src/record.ts
new file mode 100644
index 000000000..35f1d60d9
--- /dev/null
+++ b/sdk/typescript/src/record.ts
@@ -0,0 +1,3 @@
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
diff --git a/sdk/typescript/src/runtime.ts b/sdk/typescript/src/runtime.ts
index 002fea5a9..505469bf5 100644
--- a/sdk/typescript/src/runtime.ts
+++ b/sdk/typescript/src/runtime.ts
@@ -58,8 +58,10 @@ import {
type ProtectedScanPathKind,
SandboxUnavailableError,
errorMessage,
+ abortReason,
} from "./errors.js";
import type { JsonObject } from "./config.js";
+import { isRecord } from "./record.js";
import {
resolveTrustedExecutable,
type InspectedExecutable,
@@ -394,9 +396,7 @@ function windowsCredentialAclFailure(error: unknown): string {
const detail =
typeof stderr === "string" && stderr.trim() !== ""
? stderr
- : error instanceof Error
- ? error.message
- : String(error);
+ : errorMessage(error);
const normalized = errorMessage(detail)
.replace(/\s+/gu, " ")
.trim()
@@ -3206,23 +3206,12 @@ function processErrorDetail(error: unknown): string {
return String(error) || "unknown error";
}
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-
function nodeErrorCode(error: unknown): string | undefined {
return isRecord(error) && typeof error["code"] === "string"
? error["code"]
: undefined;
}
-function abortReason(signal: AbortSignal): unknown {
- return (
- signal.reason ??
- new DOMException("The operation was aborted.", "AbortError")
- );
-}
-
function throwIfSignalAborted(signal?: AbortSignal): void {
if (signal?.aborted) throw abortReason(signal);
}
diff --git a/sdk/typescript/src/saved-scan.ts b/sdk/typescript/src/saved-scan.ts
index b73e50a44..5fa70ce9a 100644
--- a/sdk/typescript/src/saved-scan.ts
+++ b/sdk/typescript/src/saved-scan.ts
@@ -1,7 +1,8 @@
import { lstat } from "node:fs/promises";
import { resolve } from "node:path";
-import type { JsonObject, JsonValue } from "./config.js";
+import type { JsonObject } from "./config.js";
import { CodexSecurityError } from "./errors.js";
+import { isRecord as isJsonObject } from "./record.js";
import { expandHome } from "./runtime.js";
export type SavedScan = JsonObject & { scanId: string; scanDir: string };
@@ -21,7 +22,6 @@ export async function resolveWorkflowScan(
);
const workflow = context["workflow"];
if (
- workflow === undefined ||
!isJsonObject(workflow) ||
typeof workflow["scanId"] !== "string" ||
typeof workflow["scanDir"] !== "string"
@@ -48,11 +48,7 @@ export async function resolveCompletedScan(
]);
const scans = history["scans"];
const latest = Array.isArray(scans) ? scans[0] : undefined;
- if (
- latest === undefined ||
- !isJsonObject(latest) ||
- typeof latest["scanId"] !== "string"
- ) {
+ if (!isJsonObject(latest) || typeof latest["scanId"] !== "string") {
throw new CodexSecurityError(
"No completed saved scan was found for this repository.",
);
@@ -65,20 +61,12 @@ export async function resolveCompletedScan(
scanId,
]);
const scan = context["scan"];
- if (
- scan === undefined ||
- !isJsonObject(scan) ||
- typeof scan["scanId"] !== "string"
- ) {
+ if (!isJsonObject(scan) || typeof scan["scanId"] !== "string") {
throw new CodexSecurityError(`Could not read saved scan ${scanId}.`);
}
scanId = scan["scanId"];
const progress = scan["progress"];
- if (
- progress === undefined ||
- !isJsonObject(progress) ||
- progress["status"] !== "complete"
- ) {
+ if (!isJsonObject(progress) || progress["status"] !== "complete") {
throw new CodexSecurityError(`Scan ${scanId} is not complete.`);
}
const storedDirectory = scan["scanDir"];
@@ -97,7 +85,3 @@ export async function resolveCompletedScan(
}
return { ...scan, scanId, scanDir };
}
-
-function isJsonObject(value: JsonValue): value is JsonObject {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
diff --git a/sdk/typescript/src/scan-activity.ts b/sdk/typescript/src/scan-activity.ts
index 4cd377b9e..344dc8ee8 100644
--- a/sdk/typescript/src/scan-activity.ts
+++ b/sdk/typescript/src/scan-activity.ts
@@ -1,3 +1,5 @@
+import { isRecord } from "./record.js";
+
const MAX_ACTIVITY_PATHS = 8;
const MAX_PROSE_CHARACTERS = 1_000;
const SHELL_TOKEN = /"(?:\\.|[^"\\])*"|'[^']*'|[^\s|;&<>]+/gu;
@@ -424,7 +426,3 @@ function argumentRepositoryPaths(value: unknown, repository: string): string[] {
}
return [...paths];
}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return value !== null && typeof value === "object" && !Array.isArray(value);
-}
diff --git a/sdk/typescript/src/scan-dashboard.ts b/sdk/typescript/src/scan-dashboard.ts
index 85d8c2693..1b41921b9 100644
--- a/sdk/typescript/src/scan-dashboard.ts
+++ b/sdk/typescript/src/scan-dashboard.ts
@@ -1,6 +1,7 @@
import { basename, isAbsolute } from "node:path";
import { pathToFileURL } from "node:url";
import { stripVTControlCharacters } from "node:util";
+import { isRecord } from "./record.js";
import type { ScanBudget } from "./api.js";
import type { ScanModelConfiguration } from "./config.js";
import type {
@@ -1093,10 +1094,6 @@ function detailsText(value: unknown): string {
.join("\n");
}
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-
function styleInlineCode(value: string, line: DashboardActivityLine): string {
for (const text of line.bold ?? []) {
value = value.replace(text, `\u001B[1m${text}\u001B[22m`);
diff --git a/sdk/typescript/src/scan-logs.ts b/sdk/typescript/src/scan-logs.ts
index a2c3cb4f6..81a42daa3 100644
--- a/sdk/typescript/src/scan-logs.ts
+++ b/sdk/typescript/src/scan-logs.ts
@@ -2,6 +2,7 @@ import { createReadStream } from "node:fs";
import { basename, dirname, join, relative } from "node:path";
import { createInterface } from "node:readline";
import { isDeepStrictEqual } from "node:util";
+import { isRecord } from "./record.js";
import { sessionFiles } from "./cost.js";
import { CodexSecurityError } from "./errors.js";
import type { JsonObject } from "./config.js";
@@ -286,7 +287,3 @@ async function* sessionEvents(
stream.destroy();
}
}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
diff --git a/sdk/typescript/src/scan-sessions.ts b/sdk/typescript/src/scan-sessions.ts
index 676f7a10b..f34d53270 100644
--- a/sdk/typescript/src/scan-sessions.ts
+++ b/sdk/typescript/src/scan-sessions.ts
@@ -1,4 +1,5 @@
import { isAbsolute, join, relative, sep } from "node:path";
+import { isRecord } from "./record.js";
export function sessionStartedAt(timestamp: unknown): number | null {
const startedAt =
@@ -39,7 +40,3 @@ export function isScanArtifactDirectory(
relative(join(workers, components[0]!, "output"), workingDirectory) === ""
);
}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
diff --git a/sdk/typescript/src/security-policy.ts b/sdk/typescript/src/security-policy.ts
index 3aaff171e..3724b6a34 100644
--- a/sdk/typescript/src/security-policy.ts
+++ b/sdk/typescript/src/security-policy.ts
@@ -1,5 +1,5 @@
import { execFile } from "node:child_process";
-import { createHash } from "node:crypto";
+import { hash } from "node:crypto";
import { constants } from "node:fs";
import {
lstat,
@@ -332,7 +332,10 @@ export async function readSecurityPolicySnapshot(
`SECURITY.md ${JSON.stringify(policyPath)} points to the selected policy and would change guidance outside the selected component. Fix the link before drafting a policy.`,
);
const links = { links: alias.links, destination: alias.destination };
- inherited.push([policyPath, `link:${digest(JSON.stringify(links))}`]);
+ inherited.push([
+ policyPath,
+ `link:${hash("sha256", JSON.stringify(links))}`,
+ ]);
metadata = await stat(path).catch((error: NodeJS.ErrnoException) => {
if (error.code === "ENOENT" || error.code === "ENOTDIR") return null;
throw error;
@@ -352,14 +355,14 @@ export async function readSecurityPolicySnapshot(
gitMetadataPaths,
);
const content = await readPolicyFile(canonical);
- inherited.push([policyPath, digest(content)]);
+ inherited.push([policyPath, hash("sha256", content)]);
}
directory = join(directory, part);
}
signal?.throwIfAborted();
return {
previousContent,
- inheritedPolicySha256: digest(JSON.stringify(inherited)),
+ inheritedPolicySha256: hash("sha256", JSON.stringify(inherited)),
};
}
@@ -920,7 +923,7 @@ export async function runSecurityPolicyStages(options: {
createdAt: new Date().toISOString(),
revision: options.revision,
previousPolicySha256:
- previousContent === null ? null : digest(previousContent),
+ previousContent === null ? null : hash("sha256", previousContent),
inheritedPolicySha256,
model: options.model,
reasoningEffort: options.reasoningEffort,
@@ -1088,7 +1091,3 @@ function diffLabel(path: string): string {
return path;
return formatSecurityPolicyText(JSON.stringify(path));
}
-
-function digest(value: string): string {
- return createHash("sha256").update(value).digest("hex");
-}
diff --git a/sdk/typescript/src/targets.ts b/sdk/typescript/src/targets.ts
index bace30339..563f0f36b 100644
--- a/sdk/typescript/src/targets.ts
+++ b/sdk/typescript/src/targets.ts
@@ -12,7 +12,7 @@ import {
sep,
} from "node:path";
import { promisify } from "node:util";
-import { InvalidTargetError } from "./errors.js";
+import { InvalidTargetError, abortReason } from "./errors.js";
import { resolveTrustedExecutable } from "./trusted-executable.js";
import { windowsUnsafePathComponent } from "./windows-path.js";
@@ -824,13 +824,6 @@ function throwIfAborted(signal?: AbortSignal): void {
if (signal?.aborted === true) throw abortReason(signal);
}
-function abortReason(signal: AbortSignal): unknown {
- return (
- signal.reason ??
- new DOMException("The operation was aborted.", "AbortError")
- );
-}
-
function expandHome(value: string): string {
if (value === "~") {
return homedir();
diff --git a/sdk/typescript/src/worker-progress.ts b/sdk/typescript/src/worker-progress.ts
index 9be80e904..82012f469 100644
--- a/sdk/typescript/src/worker-progress.ts
+++ b/sdk/typescript/src/worker-progress.ts
@@ -1,3 +1,5 @@
+import { isRecord } from "./record.js";
+
const WORKER_STATUS_PREFIX = "CODEX_SECURITY_WORKER_STATUS ";
const SCAN_PROGRESS_PREFIX = "CODEX_SECURITY_SCAN_PROGRESS ";
const PREFLIGHT_COMMAND = /(?:^|[\\/])config_preflight\.py(?=$|["'\s])/u;
@@ -218,7 +220,3 @@ function isScanPhase(value: unknown): value is ScanPhase {
value === "reporting"
);
}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return value !== null && typeof value === "object" && !Array.isArray(value);
-}
diff --git a/sdk/typescript/tests-ts/api-attribution-concurrency.test.ts b/sdk/typescript/tests-ts/api-attribution-concurrency.test.ts
index 8bcbeb9d6..77b8f50bb 100644
--- a/sdk/typescript/tests-ts/api-attribution-concurrency.test.ts
+++ b/sdk/typescript/tests-ts/api-attribution-concurrency.test.ts
@@ -31,10 +31,8 @@ describe("delegated scan attribution", () => {
await mkdir(ambientHome);
let active = 0;
let maximumActive = 0;
- let releaseConcurrentScans!: () => void;
- const concurrentScans = new Promise<void>((resolve) => {
- releaseConcurrentScans = resolve;
- });
+ const { promise: concurrentScans, resolve: releaseConcurrentScans } =
+ Promise.withResolvers<void>();
const clients = await Promise.all(
(["cli", "sdk"] as const).map(async (surface) => {
diff --git a/sdk/typescript/tests-ts/api-credentials.test.ts b/sdk/typescript/tests-ts/api-credentials.test.ts
index ed69de78c..74f86767c 100644
--- a/sdk/typescript/tests-ts/api-credentials.test.ts
+++ b/sdk/typescript/tests-ts/api-credentials.test.ts
@@ -395,10 +395,8 @@ describe("CodexSecurity orchestration", () => {
await writeFile(join(ambientHome, "auth.json"), "{}\n");
let scansStarted = 0;
const deepScanConfigPaths = new Set<string>();
- let releaseScans!: () => void;
- const concurrentScans = new Promise<void>((resolve) => {
- releaseScans = resolve;
- });
+ const { promise: concurrentScans, resolve: releaseScans } =
+ Promise.withResolvers<void>();
const clients = await Promise.all(
[0, 1].map(async (index) => {
diff --git a/sdk/typescript/tests-ts/api-events.test.ts b/sdk/typescript/tests-ts/api-events.test.ts
index e94379b71..8e7f26713 100644
--- a/sdk/typescript/tests-ts/api-events.test.ts
+++ b/sdk/typescript/tests-ts/api-events.test.ts
@@ -642,10 +642,8 @@ describe("one-shot scan events", () => {
await mkdir(scanDir, { mode: 0o700 });
const abortController = new AbortController();
const reconnects: Array<[number, number]> = [];
- let notifyReconnect!: () => void;
- const reconnectSeen = new Promise<void>((resolve) => {
- notifyReconnect = resolve;
- });
+ const { promise: reconnectSeen, resolve: notifyReconnect } =
+ Promise.withResolvers<void>();
async function* interruptedEvents(): AsyncGenerator<ThreadEvent> {
yield { type: "thread.started", thread_id: "thread-2" };
yield { type: "error", message: "Reconnecting... 2/5" };
@@ -713,14 +711,9 @@ describe("one-shot scan events", () => {
test("keeps the Codex stream alive through reconnect notifications", async () => {
const scanDir = await copyCompletedScan(await temporaryDirectory());
const reconnects: Array<[number, number]> = [];
- let release!: () => void;
- const paused = new Promise<void>((resolve) => {
- release = resolve;
- });
- let notifyReconnect!: () => void;
- const reconnectSeen = new Promise<void>((resolve) => {
- notifyReconnect = resolve;
- });
+ const { promise: paused, resolve: release } = Promise.withResolvers<void>();
+ const { promise: reconnectSeen, resolve: notifyReconnect } =
+ Promise.withResolvers<void>();
let closed = false;
async function* reconnectingEvents(): AsyncGenerator<ThreadEvent> {
try {
diff --git a/sdk/typescript/tests-ts/api-policy.test.ts b/sdk/typescript/tests-ts/api-policy.test.ts
index f69bc8fdf..391c05657 100644
--- a/sdk/typescript/tests-ts/api-policy.test.ts
+++ b/sdk/typescript/tests-ts/api-policy.test.ts
@@ -1729,10 +1729,8 @@ describe("CodexSecurity policy API", () => {
test("close cancels an owner-question callback even if it never settles", async () => {
const f = await setup();
- let entered!: () => void;
- const waiting = new Promise<void>((resolve) => {
- entered = resolve;
- });
+ const { promise: waiting, resolve: entered } =
+ Promise.withResolvers<void>();
let promptSignal: AbortSignal | undefined;
const generation = f.security.generatePolicy(f.repository, {
outputDir: f.outputDir,
diff --git a/sdk/typescript/tests-ts/api-post-scan.test.ts b/sdk/typescript/tests-ts/api-post-scan.test.ts
index 6282fe358..3cc1b7df1 100644
--- a/sdk/typescript/tests-ts/api-post-scan.test.ts
+++ b/sdk/typescript/tests-ts/api-post-scan.test.ts
@@ -12,7 +12,6 @@ import {
writeFile,
} from "node:fs/promises";
import { dirname, join } from "node:path";
-import type { ThreadEvent } from "@openai/codex-sdk";
import { afterEach, describe, expect, test } from "bun:test";
import {
prepareScanArtifactRestorer,
@@ -23,6 +22,7 @@ import { TestClient } from "./support/api-client.js";
import {
completedEvents,
createApiTestFixtures,
+ failedPostScanEvents,
preparedRuntime,
} from "./support/api-events.js";
@@ -48,13 +48,6 @@ interface FailedPostScanScenario {
): ScanArtifactRestorer;
}
-async function* failedEvents(): AsyncGenerator<ThreadEvent> {
- yield {
- type: "turn.failed",
- error: { message: "Could not draft fixes." },
- };
-}
-
async function startFailedPostScan(scenario: FailedPostScanScenario) {
const root = await temporaryDirectory();
const repository = join(root, "repository");
@@ -125,7 +118,7 @@ async function startFailedPostScan(scenario: FailedPostScanScenario) {
return { events: completedEvents() };
}
await scenario.mutate(context);
- return { events: failedEvents() };
+ return { events: failedPostScanEvents() };
},
}),
}),
diff --git a/sdk/typescript/tests-ts/api-preflight-config.test.ts b/sdk/typescript/tests-ts/api-preflight-config.test.ts
index d679103e5..06533bbab 100644
--- a/sdk/typescript/tests-ts/api-preflight-config.test.ts
+++ b/sdk/typescript/tests-ts/api-preflight-config.test.ts
@@ -1,3 +1,4 @@
+import { pythonExecutable } from "./support/python.js";
import { execFileSync, spawnSync } from "node:child_process";
import {
mkdir,
@@ -150,11 +151,7 @@ describe("CodexSecurity preflight configuration", () => {
},
});
- const interpreter =
- process.env["PYTHON"] ??
- Bun.which("python3") ??
- Bun.which("python") ??
- Bun.which("py");
+ const interpreter = pythonExecutable();
expect(interpreter).not.toBeNull();
const result = spawnSync(
interpreter!,
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index 3ff35ba7e..777ba9114 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -71,6 +71,7 @@ import {
import {
completedEvents,
createApiTestFixtures,
+ failedPostScanEvents,
preparedRuntime,
} from "./support/api-events.js";
import { runTestInSubprocess } from "./support/test-subprocess.js";
@@ -1843,10 +1844,8 @@ describe("CodexSecurity orchestration", () => {
],
];
let started = 0;
- let release!: () => void;
- const allStarted = new Promise<void>((resolve) => {
- release = resolve;
- });
+ const { promise: allStarted, resolve: release } =
+ Promise.withResolvers<void>();
const configPaths = new Set<string>();
const deepConfigPaths = new Set<string>();
const manifest = JSON.parse(
@@ -4479,13 +4478,7 @@ describe("CodexSecurity orchestration", () => {
if (setupFails) {
throw new Error("post-scan turn started after setup failed");
}
- async function* failedEvents(): AsyncGenerator<ThreadEvent> {
- yield {
- type: "turn.failed",
- error: { message: "Could not draft fixes." },
- };
- }
- return { events: failedEvents() };
+ return { events: failedPostScanEvents() };
},
}),
}),
@@ -4727,18 +4720,12 @@ describe("CodexSecurity orchestration", () => {
const codexHome = join(root, "codex-home");
const scanDir = join(root, "scan");
await Promise.all([mkdir(repository), mkdir(codexHome), mkdir(scanDir)]);
- let requested!: () => void;
- const requestStarted = new Promise<void>((resolve) => {
- requested = resolve;
- });
- let observed!: () => void;
- const nextCost = new Promise<void>((resolve) => {
- observed = resolve;
- });
- let answer!: (limit: number) => void;
- const lateAnswer = new Promise<number>((resolve) => {
- answer = resolve;
- });
+ const { promise: requestStarted, resolve: requested } =
+ Promise.withResolvers<void>();
+ const { promise: nextCost, resolve: observed } =
+ Promise.withResolvers<void>();
+ const { promise: lateAnswer, resolve: answer } =
+ Promise.withResolvers<number>();
const controller = new AbortController();
const commands: Array<readonly string[]> = [];
const warnings: string[] = [];
@@ -5765,10 +5752,8 @@ describe("CodexSecurity orchestration", () => {
const codexHome = join(stateDirectory, "codex-home");
await mkdir(repository);
let scansStarted = 0;
- let releaseScans!: () => void;
- const concurrentScans = new Promise<void>((resolve) => {
- releaseScans = resolve;
- });
+ const { promise: concurrentScans, resolve: releaseScans } =
+ Promise.withResolvers<void>();
const clients = await Promise.all(
(
@@ -7229,16 +7214,10 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
const codexHome = join(root, "codex-home");
await mkdir(repository);
await mkdir(codexHome);
- let releaseRuntime!: (runtime: ReturnType<typeof preparedRuntime>) => void;
- let preparationStarted!: () => void;
- const started = new Promise<void>((resolve) => {
- preparationStarted = resolve;
- });
- const prepared = new Promise<ReturnType<typeof preparedRuntime>>(
- (resolve) => {
- releaseRuntime = resolve;
- },
- );
+ const { promise: started, resolve: preparationStarted } =
+ Promise.withResolvers<void>();
+ const { promise: prepared, resolve: releaseRuntime } =
+ Promise.withResolvers<ReturnType<typeof preparedRuntime>>();
let createCodexCalled = false;
const client = new TestClient(
{},
@@ -7283,16 +7262,10 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
await mkdir(repository);
await mkdir(codexHome);
await mkdir(scanDir, { mode: 0o700 });
- let releaseRuntime!: (runtime: ReturnType<typeof preparedRuntime>) => void;
- let preparationStarted!: () => void;
- const started = new Promise<void>((resolve) => {
- preparationStarted = resolve;
- });
- const prepared = new Promise<ReturnType<typeof preparedRuntime>>(
- (resolve) => {
- releaseRuntime = resolve;
- },
- );
+ const { promise: started, resolve: preparationStarted } =
+ Promise.withResolvers<void>();
+ const { promise: prepared, resolve: releaseRuntime } =
+ Promise.withResolvers<ReturnType<typeof preparedRuntime>>();
const client = new TestClient(
{},
{
@@ -7346,14 +7319,10 @@ if ([basename(process.argv[1]), ...process.argv.slice(2)].join(" ") !== "login s
const scanDir = await copyCompletedScan(root);
await mkdir(repository);
await mkdir(codexHome);
- let revisionStarted!: () => void;
- let releaseRevision!: () => void;
- const started = new Promise<void>((resolve) => {
- revisionStarted = resolve;
- });
- const blocked = new Promise<void>((resolve) => {
- releaseRevision = resolve;
- });
+ const { promise: started, resolve: revisionStarted } =
+ Promise.withResolvers<void>();
+ const { promise: blocked, resolve: releaseRevision } =
+ Promise.withResolvers<void>();
let createCodexCalled = false;
const client = new TestClient(
{},
diff --git a/sdk/typescript/tests-ts/build-plugin.test.ts b/sdk/typescript/tests-ts/build-plugin.test.ts
index ecd012ee1..3850aa43d 100644
--- a/sdk/typescript/tests-ts/build-plugin.test.ts
+++ b/sdk/typescript/tests-ts/build-plugin.test.ts
@@ -137,22 +137,20 @@ describe("bundled plugin build", () => {
"package.json",
await readFile(new URL("../package.json", import.meta.url), "utf8"),
);
- await writeFixture(
- packageRoot,
- "scripts/build-plugin.mjs",
- await readFile(
- new URL("../scripts/build-plugin.mjs", import.meta.url),
- "utf8",
- ),
- );
- await writeFixture(
- packageRoot,
- "scripts/check-plugin-source.mjs",
- await readFile(
- new URL("../scripts/check-plugin-source.mjs", import.meta.url),
- "utf8",
- ),
- );
+ for (const script of [
+ "build-plugin",
+ "check-plugin-source",
+ "plugin-contract",
+ ]) {
+ await writeFixture(
+ packageRoot,
+ `scripts/${script}.mjs`,
+ await readFile(
+ new URL(`../scripts/${script}.mjs`, import.meta.url),
+ "utf8",
+ ),
+ );
+ }
await writeFixture(
source,
"plugin-files.json",
diff --git a/sdk/typescript/tests-ts/cli-patch.test.ts b/sdk/typescript/tests-ts/cli-patch.test.ts
index a29bdde1d..0beda9ef3 100644
--- a/sdk/typescript/tests-ts/cli-patch.test.ts
+++ b/sdk/typescript/tests-ts/cli-patch.test.ts
@@ -807,12 +807,7 @@ describe("scan and patch workflow", () => {
);
const repository = join(directory, "repository");
await mkdir(repository, { recursive: true });
- const git = (...args: string[]) =>
- execFileSync("git", args, {
- cwd: repository,
- encoding: "utf8",
- stdio: ["ignore", "pipe", "pipe"],
- }).trim();
+ const git = repositoryGit(repository);
try {
git("init", "--initial-branch=main");
@@ -917,12 +912,7 @@ describe("scan and patch workflow", () => {
patchRiskSummary(),
].join("\n");
let pullRequestArguments: readonly string[] = [];
- const git = (...args: string[]) =>
- execFileSync("git", args, {
- cwd: repository,
- encoding: "utf8",
- stdio: ["ignore", "pipe", "pipe"],
- }).trim();
+ const git = repositoryGit(repository);
try {
await mkdir(join(repository, "src"), { recursive: true });
@@ -1052,12 +1042,7 @@ describe("scan and patch workflow", () => {
);
const repository = join(directory, "repository");
await mkdir(repository, { recursive: true });
- const git = (...args: string[]) =>
- execFileSync("git", args, {
- cwd: repository,
- encoding: "utf8",
- stdio: ["ignore", "pipe", "pipe"],
- }).trim();
+ const git = repositoryGit(repository);
try {
git("init", "--initial-branch=main");
@@ -1387,12 +1372,7 @@ describe("scan and patch workflow", () => {
let pullRequestArguments: readonly string[] = [];
const githubCommands: string[][] = [];
await mkdir(join(repository, "src"), { recursive: true });
- const git = (...args: string[]) =>
- execFileSync("git", args, {
- cwd: repository,
- encoding: "utf8",
- stdio: ["ignore", "pipe", "pipe"],
- }).trim();
+ const git = repositoryGit(repository);
try {
git("init", "--initial-branch=main");
@@ -1567,12 +1547,7 @@ describe("scan and patch workflow", () => {
let failOnce = true;
let publishedUrl = "";
await mkdir(join(repository, "src"), { recursive: true });
- const git = (...args: string[]) =>
- execFileSync("git", args, {
- cwd: repository,
- encoding: "utf8",
- stdio: ["ignore", "pipe", "pipe"],
- }).trim();
+ const git = repositoryGit(repository);
try {
git("init", "--initial-branch=main");
@@ -2412,12 +2387,7 @@ describe("scan and patch workflow", () => {
expect(scan.stderr).toContain("--create-pr requires --patch");
const directory = await mkdtemp(join(tmpdir(), "codex-security-dirty-pr-"));
- const git = (...args: string[]) =>
- execFileSync("git", args, {
- cwd: directory,
- encoding: "utf8",
- stdio: ["ignore", "pipe", "pipe"],
- }).trim();
+ const git = repositoryGit(directory);
try {
git("init", "--initial-branch=main");
git("config", "user.name", "Synthetic User");
@@ -2457,3 +2427,12 @@ describe("scan and patch workflow", () => {
}
});
});
+
+function repositoryGit(repository: string) {
+ return (...args: string[]) =>
+ execFileSync("git", args, {
+ cwd: repository,
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "pipe"],
+ }).trim();
+}
diff --git a/sdk/typescript/tests-ts/cli-publish.test.ts b/sdk/typescript/tests-ts/cli-publish.test.ts
index ba7c5a4b7..87d310f58 100644
--- a/sdk/typescript/tests-ts/cli-publish.test.ts
+++ b/sdk/typescript/tests-ts/cli-publish.test.ts
@@ -376,14 +376,10 @@ describe("publish check", () => {
deps.forceExit = () => {
forced = true;
};
- let started!: () => void;
- const operationStarted = new Promise<void>((resolve) => {
- started = resolve;
- });
- let finishCleanup!: () => void;
- const cleanup = new Promise<void>((resolve) => {
- finishCleanup = resolve;
- });
+ const { promise: operationStarted, resolve: started } =
+ Promise.withResolvers<void>();
+ const { promise: cleanup, resolve: finishCleanup } =
+ Promise.withResolvers<void>();
const operation = async (
_directory: string,
options: { signal?: AbortSignal },
@@ -787,14 +783,10 @@ describe("publish scan", () => {
const signals = new FakeSignals();
const events: string[] = [];
let now = 0;
- let enteredPublication!: () => void;
- const publicationStarted = new Promise<void>((resolve) => {
- enteredPublication = resolve;
- });
- let finishRecovery!: () => void;
- const recoveryFinished = new Promise<void>((resolve) => {
- finishRecovery = resolve;
- });
+ const { promise: publicationStarted, resolve: enteredPublication } =
+ Promise.withResolvers<void>();
+ const { promise: recoveryFinished, resolve: finishRecovery } =
+ Promise.withResolvers<void>();
const deps = dependencies({ signals });
deps.environment["CODEX_SECURITY_LINEAR_API_KEY"] = "synthetic-key";
deps.now = () => now;
@@ -1952,14 +1944,10 @@ describe("publish scan", () => {
};
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 { promise: publicationStarted, resolve: enteredPublication } =
+ Promise.withResolvers<void>();
+ const { promise: recoveryFinished, resolve: finishRecovery } =
+ Promise.withResolvers<void>();
const deps = dependencies();
deps.addSignalListener = (name, listener) => {
listeners.set(name, listener);
diff --git a/sdk/typescript/tests-ts/cli-workbench.test.ts b/sdk/typescript/tests-ts/cli-workbench.test.ts
index 1a1b26e4d..9c12e14a5 100644
--- a/sdk/typescript/tests-ts/cli-workbench.test.ts
+++ b/sdk/typescript/tests-ts/cli-workbench.test.ts
@@ -763,14 +763,10 @@ describe("CLI workbench", () => {
"debounces matching %s and allows a later %s to terminate a blocked workbench",
async (first, second, delay, expectedExit) => {
const signals = new FakeSignals();
- let began!: () => void;
- const started = new Promise<void>((resolve) => {
- began = resolve;
- });
- let finish!: (value: JsonObject) => void;
- const pending = new Promise<JsonObject>((resolve) => {
- finish = resolve;
- });
+ const { promise: started, resolve: began } =
+ Promise.withResolvers<void>();
+ const { promise: pending, resolve: finish } =
+ Promise.withResolvers<JsonObject>();
let observedSignal: AbortSignal | undefined;
const forced: string[] = [];
let now = 0;
diff --git a/sdk/typescript/tests-ts/compact-diff-scan.test.ts b/sdk/typescript/tests-ts/compact-diff-scan.test.ts
index 087eeda64..af4bfd2e5 100644
--- a/sdk/typescript/tests-ts/compact-diff-scan.test.ts
+++ b/sdk/typescript/tests-ts/compact-diff-scan.test.ts
@@ -1,4 +1,5 @@
-import { execFileSync, spawn, spawnSync } from "node:child_process";
+import { git } from "./git-fixture.js";
+import { spawn, spawnSync } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import {
mkdirSync,
@@ -36,20 +37,6 @@ function createRepository(): { root: string; repository: string } {
return { root, repository };
}
-function git(repository: string, ...args: string[]): string {
- return execFileSync(
- "git",
- [
- "-c",
- "user.name=Fixture",
- "-c",
- ...args,
- ],
- { cwd: repository, encoding: "utf8" },
- ).trim();
-}
-
function writeSource(
repository: string,
path: string,
diff --git a/sdk/typescript/tests-ts/component-scan.test.ts b/sdk/typescript/tests-ts/component-scan.test.ts
index 9a3b3eb8b..16ca3a2c1 100644
--- a/sdk/typescript/tests-ts/component-scan.test.ts
+++ b/sdk/typescript/tests-ts/component-scan.test.ts
@@ -45,6 +45,7 @@ import {
FakeSignals,
} from "./cli-fixtures.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
+import { readJson as readJsonFile } from "./support/json.js";
const temporary: string[] = [];
const components: ComponentPlan["components"] = [
@@ -104,9 +105,7 @@ async function largePlanningFixture() {
return { ...paths, files: files.sort() };
}
-async function json(path: string) {
- return JSON.parse(await readFile(path, "utf8"));
-}
+const json = readJsonFile<any>;
function finding(
id: string,
@@ -303,10 +302,8 @@ test("bounds standard scans, continues after failure, and preserves partial resu
let active = 0,
peak = 0,
closed = 0;
- let unblock!: () => void;
- const bothStarted = new Promise<void>((resolve) => {
- unblock = resolve;
- });
+ const { promise: bothStarted, resolve: unblock } =
+ Promise.withResolvers<void>();
const seen: ScanOptions[] = [];
const summary = await scan(paths, {
workers: 2,
diff --git a/sdk/typescript/tests-ts/contract.test.ts b/sdk/typescript/tests-ts/contract.test.ts
index e7e95fb23..333a85229 100644
--- a/sdk/typescript/tests-ts/contract.test.ts
+++ b/sdk/typescript/tests-ts/contract.test.ts
@@ -21,6 +21,7 @@ import { ContractValidationError, loadContract } from "../src/index.js";
import { sameCheckedFileDevice } from "../src/contract.js";
import type { NormalizedTarget, ScanExpectation } from "../src/index.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
+import { readJson as readJsonFile, writeJson } from "./support/json.js";
import { propertyOptions } from "./support/property.js";
const EXAMPLE = join(PLUGIN_ROOT, "examples", "completed-scan");
@@ -43,13 +44,7 @@ async function copyExample(): Promise<string> {
return scanDir;
}
-async function readJson(path: string): Promise<Record<string, any>> {
- return JSON.parse(await readFile(path, "utf8"));
-}
-
-async function writeJson(path: string, payload: unknown): Promise<void> {
- await writeFile(path, `${JSON.stringify(payload, null, 2)}\n`);
-}
+const readJson = readJsonFile<Record<string, any>>;
async function reseal(scanDir: string): Promise<void> {
const manifestPath = join(scanDir, "scan-manifest.json");
diff --git a/sdk/typescript/tests-ts/cost.test.ts b/sdk/typescript/tests-ts/cost.test.ts
index aaa2f09e2..19c2e907a 100644
--- a/sdk/typescript/tests-ts/cost.test.ts
+++ b/sdk/typescript/tests-ts/cost.test.ts
@@ -549,10 +549,8 @@ describe("live scan cost tracking", () => {
});
const errors: string[] = [];
let traversals = 0;
- let release: (() => void) | undefined;
- const blocked = new Promise<void>((resolve) => {
- release = resolve;
- });
+ const { promise: blocked, resolve: release } =
+ Promise.withResolvers<void>();
const tracker = new ScanCostTracker({
codexHome: home,
model: "gpt-5.6-sol",
@@ -589,10 +587,8 @@ describe("live scan cost tracking", () => {
cached_input_tokens: 200,
output_tokens: 30,
});
- let reportCost!: (cost: unknown) => void;
- const reportedCost = new Promise<unknown>((resolve) => {
- reportCost = resolve;
- });
+ const { promise: reportedCost, resolve: reportCost } =
+ Promise.withResolvers<unknown>();
const tracker = new ScanCostTracker({
codexHome: home,
model: "gpt-5.6-sol",
@@ -2004,10 +2000,8 @@ describe("live scan cost tracking", () => {
);
await appendSessionItem(worker, progressMessage(3));
- let reportProgress!: (progress: ScanProgress) => void;
- const reportedProgress = new Promise<ScanProgress>((resolve) => {
- reportProgress = resolve;
- });
+ const { promise: reportedProgress, resolve: reportProgress } =
+ Promise.withResolvers<ScanProgress>();
const tracker = new ScanCostTracker({
codexHome: home,
model: "gpt-5.6-sol",
diff --git a/sdk/typescript/tests-ts/custom-validation.test.ts b/sdk/typescript/tests-ts/custom-validation.test.ts
index 95f4dad83..50115378d 100644
--- a/sdk/typescript/tests-ts/custom-validation.test.ts
+++ b/sdk/typescript/tests-ts/custom-validation.test.ts
@@ -26,6 +26,7 @@ import {
runWorkbench,
} from "../src/runtime.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
+import { readJson as json } from "./support/json.js";
import { TestClient } from "./support/api-client.js";
import {
completedEvents,
@@ -37,10 +38,6 @@ const { cleanup, temporaryDirectory } = createApiTestFixtures();
const resultName = "artifacts/custom-validation/results.json";
afterEach(cleanup);
-async function json<T>(path: string): Promise<T> {
- return JSON.parse(await readFile(path, "utf8")) as T;
-}
-
async function save(path: string, value: unknown) {
await writeFile(path, JSON.stringify(value));
}
diff --git a/sdk/typescript/tests-ts/dedupe-records.test.ts b/sdk/typescript/tests-ts/dedupe-records.test.ts
index edfa1031a..87b966e3c 100644
--- a/sdk/typescript/tests-ts/dedupe-records.test.ts
+++ b/sdk/typescript/tests-ts/dedupe-records.test.ts
@@ -702,10 +702,8 @@ test.each(["result", "error"] as const)(
const inputStream = new PassThrough();
const messages: Message[] = [];
let release!: () => void;
- let started!: () => void;
- const writing = new Promise<void>((resolve) => {
- started = resolve;
- });
+ const { promise: writing, resolve: started } =
+ Promise.withResolvers<void>();
const output = new Writable({
write(chunk, _encoding, callback) {
messages.push(JSON.parse(chunk.toString()));
diff --git a/sdk/typescript/tests-ts/deep-scan-workbench.test.ts b/sdk/typescript/tests-ts/deep-scan-workbench.test.ts
index 1df7f704a..927458362 100644
--- a/sdk/typescript/tests-ts/deep-scan-workbench.test.ts
+++ b/sdk/typescript/tests-ts/deep-scan-workbench.test.ts
@@ -1285,31 +1285,7 @@ describe("deep scan workbench ownership", () => {
const python = Bun.which("python3") ?? Bun.which("python");
expect(python).not.toBeNull();
- const command = (args: string[]): Record<string, unknown> => {
- const result = Bun.spawnSync(
- [
- python!,
- "-I",
- "-B",
- join(PLUGIN_ROOT, "scripts", "workbench_db.py"),
- ...args,
- ],
- {
- env: {
- ...process.env,
- CODEX_SECURITY_STATE_DIR: stateDir,
- CODEX_HOME: codexHome,
- },
- stdout: "pipe",
- stderr: "pipe",
- },
- );
- expect(result.exitCode, new TextDecoder().decode(result.stderr)).toBe(0);
- return JSON.parse(new TextDecoder().decode(result.stdout)) as Record<
- string,
- unknown
- >;
- };
+ const command = workbenchCommand(python, stateDir, codexHome);
const registration = command([
"register-cli-scan",
"--repository",
@@ -1471,31 +1447,7 @@ describe("deep scan workbench ownership", () => {
const python = Bun.which("python3") ?? Bun.which("python");
expect(python).not.toBeNull();
- const command = (args: string[]): Record<string, unknown> => {
- const result = Bun.spawnSync(
- [
- python!,
- "-I",
- "-B",
- join(PLUGIN_ROOT, "scripts", "workbench_db.py"),
- ...args,
- ],
- {
- env: {
- ...process.env,
- CODEX_SECURITY_STATE_DIR: stateDir,
- CODEX_HOME: codexHome,
- },
- stdout: "pipe",
- stderr: "pipe",
- },
- );
- expect(result.exitCode, new TextDecoder().decode(result.stderr)).toBe(0);
- return JSON.parse(new TextDecoder().decode(result.stdout)) as Record<
- string,
- unknown
- >;
- };
+ const command = workbenchCommand(python, stateDir, codexHome);
const state = (result: Record<string, unknown>) =>
result["deepScan"] as Record<string, unknown>;
const initial = state(
@@ -1775,3 +1727,35 @@ describe("deep scan workbench ownership", () => {
expect(await readFile(ledgerPath, "utf8")).toBe(existingFinding);
});
});
+
+function workbenchCommand(
+ python: string | null,
+ stateDir: string,
+ codexHome: string,
+) {
+ return (args: string[]): Record<string, unknown> => {
+ const result = Bun.spawnSync(
+ [
+ python!,
+ "-I",
+ "-B",
+ join(PLUGIN_ROOT, "scripts", "workbench_db.py"),
+ ...args,
+ ],
+ {
+ env: {
+ ...process.env,
+ CODEX_SECURITY_STATE_DIR: stateDir,
+ CODEX_HOME: codexHome,
+ },
+ stdout: "pipe",
+ stderr: "pipe",
+ },
+ );
+ expect(result.exitCode, new TextDecoder().decode(result.stderr)).toBe(0);
+ return JSON.parse(new TextDecoder().decode(result.stdout)) as Record<
+ string,
+ unknown
+ >;
+ };
+}
diff --git a/sdk/typescript/tests-ts/diff-rank-input.test.ts b/sdk/typescript/tests-ts/diff-rank-input.test.ts
index 6c65cd5d2..3baed9245 100644
--- a/sdk/typescript/tests-ts/diff-rank-input.test.ts
+++ b/sdk/typescript/tests-ts/diff-rank-input.test.ts
@@ -1,4 +1,6 @@
-import { execFileSync, spawnSync } from "node:child_process";
+import { pythonExecutable } from "./support/python.js";
+import { git } from "./git-fixture.js";
+import { spawnSync } from "node:child_process";
import {
chmodSync,
existsSync,
@@ -18,35 +20,12 @@ import { PLUGIN_ROOT } from "./plugin-root.js";
const temporaryRoots: string[] = [];
const testPosix = process.platform === "win32" ? test.skip : test;
-function pythonExecutable(): string | null {
- return (
- process.env["PYTHON"] ??
- Bun.which("python3") ??
- Bun.which("python") ??
- Bun.which("py")
- );
-}
-
afterEach(() => {
for (const root of temporaryRoots.splice(0)) {
rmSync(root, { recursive: true, force: true });
}
});
-function git(repository: string, ...args: string[]): string {
- return execFileSync(
- "git",
- [
- "-c",
- "user.name=Fixture",
- "-c",
- ...args,
- ],
- { cwd: repository, encoding: "utf8" },
- ).trim();
-}
-
test("diff previews stay inside the selected repository", () => {
const root = realpathSync(
mkdtempSync(join(tmpdir(), "codex-security-diff-rank-")),
diff --git a/sdk/typescript/tests-ts/finding-catalogue.test.ts b/sdk/typescript/tests-ts/finding-catalogue.test.ts
index 67643c6e1..d40f2a2c7 100644
--- a/sdk/typescript/tests-ts/finding-catalogue.test.ts
+++ b/sdk/typescript/tests-ts/finding-catalogue.test.ts
@@ -746,22 +746,14 @@ describe("finding catalogue", () => {
});
const pieces: string[] = [];
let expectedOffset = 0;
- const request = (offset: number) => ({
- ...empty,
- request: {
- kind: "evidence",
- beforeOccurrenceIds: ["large"],
- afterOccurrenceIds: [],
- offset,
- },
- });
+
const observed = conversation((prompt, index) => {
expect(characters(prompt)).toBeLessThanOrEqual(1 << 20);
if (index === 0) {
expect(data<CatalogueData>(prompt).findings.before).toEqual([
{ occurrenceId: "large", detailsOmitted: true },
]);
- return request(0);
+ return largeEvidenceRequest(0);
}
const payload = data<EvidenceData>(prompt);
expect(payload.offset).toBe(expectedOffset);
@@ -770,7 +762,9 @@ describe("finding catalogue", () => {
if (payload.nextOffset !== null)
expect(payload.nextOffset).toBe(expectedOffset);
pieces.push(payload.content);
- return payload.nextOffset === null ? empty : request(payload.nextOffset);
+ return payload.nextOffset === null
+ ? empty
+ : largeEvidenceRequest(payload.nextOffset);
});
await matchScanFindings(
{ before: [original], after: [finding("new")] },
@@ -846,20 +840,13 @@ describe("finding catalogue", () => {
test.each(["overlap", "skip"] as const)(
"rejects an evidence cursor that would %s the previous page",
async (scenario) => {
- const request = (offset: number) => ({
- ...empty,
- request: {
- kind: "evidence",
- beforeOccurrenceIds: ["large"],
- afterOccurrenceIds: [],
- offset,
- },
- });
const observed = conversation((prompt, index) => {
- if (index === 0) return request(0);
+ if (index === 0) return largeEvidenceRequest(0);
const nextOffset = data<EvidenceData>(prompt).nextOffset;
expect(nextOffset).not.toBeNull();
- return request(nextOffset! + (scenario === "overlap" ? -1 : 1));
+ return largeEvidenceRequest(
+ nextOffset! + (scenario === "overlap" ? -1 : 1),
+ );
});
await expect(
matchScanFindings(
@@ -1169,3 +1156,13 @@ describe("finding catalogue", () => {
}
});
});
+
+const largeEvidenceRequest = (offset: number) => ({
+ ...empty,
+ request: {
+ kind: "evidence",
+ beforeOccurrenceIds: ["large"],
+ afterOccurrenceIds: [],
+ offset,
+ },
+});
diff --git a/sdk/typescript/tests-ts/finding-deduplication.test.ts b/sdk/typescript/tests-ts/finding-deduplication.test.ts
index 9a5d958aa..4cce6f3ab 100644
--- a/sdk/typescript/tests-ts/finding-deduplication.test.ts
+++ b/sdk/typescript/tests-ts/finding-deduplication.test.ts
@@ -101,16 +101,6 @@ function screening(
};
}
-function deferred<T>() {
- let resolve!: (value: T) => void;
- let reject!: (error: unknown) => void;
- const promise = new Promise<T>((yes, no) => {
- resolve = yes;
- reject = no;
- });
- return { promise, resolve, reject };
-}
-
test.each(["screening", "pair-review"])(
"%s fills each free slot immediately and preserves serial grouping",
async (stage) => {
@@ -128,8 +118,8 @@ test.each(["screening", "pair-review"])(
};
},
};
- const gates = entries.map(() => deferred<void>());
- const started = entries.map(() => deferred<void>());
+ const gates = entries.map(() => Promise.withResolvers<void>());
+ const started = entries.map(() => Promise.withResolvers<void>());
const starts: number[] = [];
const phases: string[] = [];
let active = 0;
@@ -188,10 +178,10 @@ test("ready pairs take free slots before pending screenings and share the concur
const nominations = new Set(
ids.map((id) => pairKey([id, neighbor.findingId])),
);
- const screeningGates = entries.map(() => deferred<void>());
- const screeningStarts = entries.map(() => deferred<void>());
- const pairGates = entries.map(() => deferred<void>());
- const pairStarts = entries.map(() => deferred<void>());
+ const screeningGates = entries.map(() => Promise.withResolvers<void>());
+ const screeningStarts = entries.map(() => Promise.withResolvers<void>());
+ const pairGates = entries.map(() => Promise.withResolvers<void>());
+ const pairStarts = entries.map(() => Promise.withResolvers<void>());
const events: string[] = [];
let active = 0;
let peak = 0;
@@ -262,9 +252,9 @@ test("ready pairs take free slots before pending screenings and share the concur
test("a pair waits for its delayed reciprocal screening and honors a DISTINCT veto", async () => {
const entries = [entry(1), entry(2)];
const ids = entries.map((finding) => finding.findingId);
- const gates = entries.map(() => deferred<void>());
- const started = entries.map(() => deferred<void>());
- const finished = deferred<void>();
+ const gates = entries.map(() => Promise.withResolvers<void>());
+ const started = entries.map(() => Promise.withResolvers<void>());
+ const finished = Promise.withResolvers<void>();
const reviewed: string[] = [];
const result = new FindingDeduplicator(
candidates(entries),
@@ -325,11 +315,11 @@ test("reverse completion preserves pair orientation and the final input-order fi
},
{ finding: entries[2]!, potentialDuplicates: [finalA] },
];
- const lookupStarts = entries.map(() => deferred<void>());
- const lookupGates = entries.map(() => deferred<void>());
- const screenStarts = entries.map(() => deferred<void>());
- const screenGates = entries.map(() => deferred<void>());
- const pairStarted = deferred<void>();
+ const lookupStarts = entries.map(() => Promise.withResolvers<void>());
+ const lookupGates = entries.map(() => Promise.withResolvers<void>());
+ const screenStarts = entries.map(() => Promise.withResolvers<void>());
+ const screenGates = entries.map(() => Promise.withResolvers<void>());
+ const pairStarted = Promise.withResolvers<void>();
const reviewed: Finding[][] = [];
const result = new FindingDeduplicator(
{
@@ -389,9 +379,9 @@ test.each(["screen", "pair", "cancel"])(
const ids = entries.map((finding) => finding.findingId);
const starts: string[] = [];
const completed: string[] = [];
- const screenGate = deferred<void>();
- const pairGate = deferred<void>();
- const pairStarted = deferred<void>();
+ const screenGate = Promise.withResolvers<void>();
+ const pairGate = Promise.withResolvers<void>();
+ const pairStarted = Promise.withResolvers<void>();
const controller = new AbortController();
const failure = new Error("Synthetic mixed-stage failure");
const result = new FindingDeduplicator(
@@ -459,8 +449,8 @@ test.each(["screen", "pair", "cancel"])(
test("terminal failure drains started reviews without starting queued jobs", async () => {
const entries = [entry(1), entry(2), entry(3)];
- const gates = entries.map(() => deferred<void>());
- const started = entries.map(() => deferred<void>());
+ const gates = entries.map(() => Promise.withResolvers<void>());
+ const started = entries.map(() => Promise.withResolvers<void>());
const calls: string[] = [];
const failure = new Error("Synthetic review failure");
const result = new FindingDeduplicator(
diff --git a/sdk/typescript/tests-ts/git-fixture.ts b/sdk/typescript/tests-ts/git-fixture.ts
new file mode 100644
index 000000000..a0afedb0f
--- /dev/null
+++ b/sdk/typescript/tests-ts/git-fixture.ts
@@ -0,0 +1,15 @@
+import { execFileSync } from "node:child_process";
+
+export function git(repository: string, ...args: string[]): string {
+ return execFileSync(
+ "git",
+ [
+ "-c",
+ "user.name=Fixture",
+ "-c",
+ ...args,
+ ],
+ { cwd: repository, encoding: "utf8" },
+ ).trim();
+}
diff --git a/sdk/typescript/tests-ts/multiscan.test.ts b/sdk/typescript/tests-ts/multiscan.test.ts
index 9bcadcaa9..83dfa9f3f 100644
--- a/sdk/typescript/tests-ts/multiscan.test.ts
+++ b/sdk/typescript/tests-ts/multiscan.test.ts
@@ -1438,10 +1438,8 @@ describe("multiscan", () => {
let maximum = 0;
let created = 0;
let closed = 0;
- let release!: () => void;
- const simultaneous = new Promise<void>((resolve) => {
- release = resolve;
- });
+ const { promise: simultaneous, resolve: release } =
+ Promise.withResolvers<void>();
const security = client(async (_repository, scanOptions = {}) => {
expect(scanOptions.knowledgeBasePaths).toEqual(knowledgeBasePaths);
active += 1;
@@ -1492,14 +1490,9 @@ describe("multiscan", () => {
paths.input,
`id,repository,revision\nexclusive,${source.path},${source.revision}\n`,
);
- let started!: () => void;
- let release!: () => void;
- const running = new Promise<void>((resolve) => {
- started = resolve;
- });
- const finish = new Promise<void>((resolve) => {
- release = resolve;
- });
+ const { promise: running, resolve: started } =
+ Promise.withResolvers<void>();
+ const { promise: finish, resolve: release } = Promise.withResolvers<void>();
const security = client(async (_repository, scanOptions = {}) => {
started();
await finish;
@@ -1780,14 +1773,9 @@ describe("multiscan", () => {
mode: 0o600,
},
);
- let started!: () => void;
- let release!: () => void;
- const running = new Promise<void>((resolve) => {
- started = resolve;
- });
- const finish = new Promise<void>((resolve) => {
- release = resolve;
- });
+ const { promise: running, resolve: started } =
+ Promise.withResolvers<void>();
+ const { promise: finish, resolve: release } = Promise.withResolvers<void>();
let active = 0;
let maximum = 0;
const security = client(async (_repository, scanOptions = {}) => {
@@ -1823,14 +1811,9 @@ describe("multiscan", () => {
paths.input,
`id,repository,revision\nreplacement,${source.path},${source.revision}\n`,
);
- let started!: () => void;
- let release!: () => void;
- const running = new Promise<void>((resolve) => {
- started = resolve;
- });
- const finish = new Promise<void>((resolve) => {
- release = resolve;
- });
+ const { promise: running, resolve: started } =
+ Promise.withResolvers<void>();
+ const { promise: finish, resolve: release } = Promise.withResolvers<void>();
const first = runMultiscan(
options(
paths,
diff --git a/sdk/typescript/tests-ts/patch-risk-contract.test.ts b/sdk/typescript/tests-ts/patch-risk-contract.test.ts
index 6f786a909..02c0102c7 100644
--- a/sdk/typescript/tests-ts/patch-risk-contract.test.ts
+++ b/sdk/typescript/tests-ts/patch-risk-contract.test.ts
@@ -1,3 +1,4 @@
+import { pythonExecutable } from "./support/python.js";
import { spawnSync } from "node:child_process";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
@@ -68,11 +69,7 @@ const validatorPath = join(
"scripts",
"validate_patch_risk_assessment.py",
);
-const python =
- process.env["PYTHON"] ??
- Bun.which("python3") ??
- Bun.which("python") ??
- Bun.which("py");
+const python = pythonExecutable();
function assessment(): Assessment {
return {
diff --git a/sdk/typescript/tests-ts/plugin-finding-detail-contract.test.ts b/sdk/typescript/tests-ts/plugin-finding-detail-contract.test.ts
index 07e23f24b..befeb9656 100644
--- a/sdk/typescript/tests-ts/plugin-finding-detail-contract.test.ts
+++ b/sdk/typescript/tests-ts/plugin-finding-detail-contract.test.ts
@@ -1,11 +1,11 @@
import { spawn } from "node:child_process";
-import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { createInterface } from "node:readline";
import { describe, expect, test } from "bun:test";
import Ajv from "ajv";
import Ajv2020 from "ajv/dist/2020.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
+import { readJson as readJsonFile } from "./support/json.js";
type JsonObject = Record<string, unknown>;
@@ -113,9 +113,7 @@ function projectFindingDetails(details: JsonObject): string {
return new TextDecoder().decode(result.stdout);
}
-async function readJson(path: string): Promise<JsonObject> {
- return JSON.parse(await readFile(path, "utf8")) as JsonObject;
-}
+const readJson = readJsonFile<JsonObject>;
async function startMcp() {
const child = spawn(
diff --git a/sdk/typescript/tests-ts/publication-store.test.ts b/sdk/typescript/tests-ts/publication-store.test.ts
index c2adeea00..33b77528b 100644
--- a/sdk/typescript/tests-ts/publication-store.test.ts
+++ b/sdk/typescript/tests-ts/publication-store.test.ts
@@ -330,10 +330,8 @@ describe("read-only publication history", () => {
const controller = new AbortController();
const reason = new Error("Synthetic inspection cancellation.");
let inputFile = "";
- let started!: () => void;
- const inspecting = new Promise<void>((resolve) => {
- started = resolve;
- });
+ const { promise: inspecting, resolve: started } =
+ Promise.withResolvers<void>();
const python = spyOn(runtime, "resolvePluginPython").mockImplementation(
async (options) => {
expect(options?.signal).toBe(controller.signal);
diff --git a/sdk/typescript/tests-ts/publication.test.ts b/sdk/typescript/tests-ts/publication.test.ts
index 104c8f0bb..41b83f175 100644
--- a/sdk/typescript/tests-ts/publication.test.ts
+++ b/sdk/typescript/tests-ts/publication.test.ts
@@ -8,7 +8,6 @@ import {
realpath,
rm,
symlink,
- writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
@@ -21,6 +20,7 @@ import type {
SeverityLevel,
} from "../src/models.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
+import { readJson, writeJson } from "./support/json.js";
const EXAMPLE = join(PLUGIN_ROOT, "examples", "completed-scan");
const temporaryDirectories: string[] = [];
@@ -53,14 +53,6 @@ async function copyExample(): Promise<string> {
return scanDirectory;
}
-async function readJson<T>(path: string): Promise<T> {
- return JSON.parse(await readFile(path, "utf8")) as T;
-}
-
-async function writeJson(path: string, value: unknown): Promise<void> {
- await writeFile(path, `${JSON.stringify(value, null, 2)}\n`);
-}
-
async function reseal(scanDirectory: string): Promise<void> {
const manifestPath = join(scanDirectory, "scan-manifest.json");
const manifest = await readJson<ScanManifest>(manifestPath);
diff --git a/sdk/typescript/tests-ts/publish.test.ts b/sdk/typescript/tests-ts/publish.test.ts
index a5a703f21..4369a33e4 100644
--- a/sdk/typescript/tests-ts/publish.test.ts
+++ b/sdk/typescript/tests-ts/publish.test.ts
@@ -805,10 +805,8 @@ describe("direct Linear API publication", () => {
let started = 0;
let completed = 0;
let completedAtFirstIssueProgress: number | undefined;
- let releaseFirstBatch: (() => void) | undefined;
- const firstBatchStarted = new Promise<void>((resolve) => {
- releaseFirstBatch = resolve;
- });
+ const { promise: firstBatchStarted, resolve: releaseFirstBatch } =
+ Promise.withResolvers<void>();
const result = await publishScanInternal(
publication.scanDirectory,
{
diff --git a/sdk/typescript/tests-ts/runtime.test.ts b/sdk/typescript/tests-ts/runtime.test.ts
index 4e1b55fc1..e1f310dd9 100644
--- a/sdk/typescript/tests-ts/runtime.test.ts
+++ b/sdk/typescript/tests-ts/runtime.test.ts
@@ -2718,14 +2718,10 @@ describe("runtime directories and plugin Python boundary", () => {
let separateDatabaseCreates = 0;
let observedMode: number | undefined;
let paused = false;
- let reportPaused!: () => void;
- let resumeCreator!: () => void;
- const creatorPaused = new Promise<void>((resolve) => {
- reportPaused = resolve;
- });
- const creatorResumed = new Promise<void>((resolve) => {
- resumeCreator = resolve;
- });
+ const { promise: creatorPaused, resolve: reportPaused } =
+ Promise.withResolvers<void>();
+ const { promise: creatorResumed, resolve: resumeCreator } =
+ Promise.withResolvers<void>();
mock.module("node:fs/promises", () => ({
...fsPromises,
lstat: async (...args: Parameters<typeof originalLstat>) => {
@@ -3339,14 +3335,10 @@ describe("runtime directories and plugin Python boundary", () => {
kill: () => true,
});
const first = makeChild();
- let enterCallback!: () => void;
- const callbackEntered = new Promise<void>((resolve) => {
- enterCallback = resolve;
- });
- let releaseCallback!: () => void;
- const callbackReleased = new Promise<void>((resolve) => {
- releaseCallback = resolve;
- });
+ const { promise: callbackEntered, resolve: enterCallback } =
+ Promise.withResolvers<void>();
+ const { promise: callbackReleased, resolve: releaseCallback } =
+ Promise.withResolvers<void>();
let paused = false;
let callbackFinished = false;
let attempts = 0;
diff --git a/sdk/typescript/tests-ts/scan-comparison.test.ts b/sdk/typescript/tests-ts/scan-comparison.test.ts
index 8362b39e9..3fbc8cb5d 100644
--- a/sdk/typescript/tests-ts/scan-comparison.test.ts
+++ b/sdk/typescript/tests-ts/scan-comparison.test.ts
@@ -618,10 +618,8 @@ describe("semantic scan comparison", () => {
});
const controller = new AbortController();
let observedSignal: AbortSignal | undefined;
- let statusStarted!: () => void;
- const started = new Promise<void>((resolve) => {
- statusStarted = resolve;
- });
+ const { promise: started, resolve: statusStarted } =
+ Promise.withResolvers<void>();
const waiting = comparisonEnvironment(
{ CODEX_SECURITY_STATE_DIR: stateDirectory },
diff --git a/sdk/typescript/tests-ts/scan-matching-e2e.test.ts b/sdk/typescript/tests-ts/scan-matching-e2e.test.ts
index 5a04c2d19..803bf9b91 100644
--- a/sdk/typescript/tests-ts/scan-matching-e2e.test.ts
+++ b/sdk/typescript/tests-ts/scan-matching-e2e.test.ts
@@ -27,6 +27,7 @@ import {
} from "../src/scan-comparison.js";
import { capture, dependencies } from "./cli-fixtures.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
+import { readJson } from "./support/json.js";
const empty = { matches: [], uncertain: [] } satisfies ScanComparisonResult;
@@ -74,8 +75,6 @@ test("matches sealed scan history end to end without merging related findings",
args,
input,
);
- const readJson = async <T>(path: string): Promise<T> =>
- JSON.parse(await readFile(path, "utf8")) as T;
const writeJson = async (path: string, value: unknown) =>
writeFile(path, JSON.stringify(value));
const artifacts: string[] = [];
diff --git a/sdk/typescript/tests-ts/scan-recovery.test.ts b/sdk/typescript/tests-ts/scan-recovery.test.ts
index c731e9f94..5b5d7efd6 100644
--- a/sdk/typescript/tests-ts/scan-recovery.test.ts
+++ b/sdk/typescript/tests-ts/scan-recovery.test.ts
@@ -13,6 +13,7 @@ import { join } from "node:path";
import { afterEach, describe, expect, test } from "bun:test";
import { runWorkbench } from "../src/runtime.js";
import { PLUGIN_ROOT } from "./plugin-root.js";
+import { readJson } from "./support/json.js";
type Finding = Record<string, unknown> & {
ruleId: string;
@@ -94,10 +95,6 @@ afterEach(async () => {
);
});
-async function readJson<T>(path: string): Promise<T> {
- return JSON.parse(await readFile(path, "utf8")) as T;
-}
-
async function writeJson(path: string, value: unknown): Promise<void> {
await writeFile(path, `${JSON.stringify(value)}\n`);
}
diff --git a/sdk/typescript/tests-ts/support/api-events.ts b/sdk/typescript/tests-ts/support/api-events.ts
index 1b8ab48b2..ff633bd8e 100644
--- a/sdk/typescript/tests-ts/support/api-events.ts
+++ b/sdk/typescript/tests-ts/support/api-events.ts
@@ -81,6 +81,13 @@ export function createApiTestFixtures() {
};
}
+export async function* failedPostScanEvents(): AsyncGenerator<ThreadEvent> {
+ yield {
+ type: "turn.failed",
+ error: { message: "Could not draft fixes." },
+ };
+}
+
export async function* completedEvents(
threadId = "thread-1",
): AsyncGenerator<ThreadEvent> {
diff --git a/sdk/typescript/tests-ts/support/json.ts b/sdk/typescript/tests-ts/support/json.ts
new file mode 100644
index 000000000..6f2b1d7c4
--- /dev/null
+++ b/sdk/typescript/tests-ts/support/json.ts
@@ -0,0 +1,9 @@
+import { readFile, writeFile } from "node:fs/promises";
+
+export async function readJson<T>(path: string): Promise<T> {
+ return JSON.parse(await readFile(path, "utf8")) as T;
+}
+
+export async function writeJson(path: string, value: unknown): Promise<void> {
+ await writeFile(path, `${JSON.stringify(value, null, 2)}\n`);
+}
diff --git a/sdk/typescript/tests-ts/support/python.ts b/sdk/typescript/tests-ts/support/python.ts
new file mode 100644
index 000000000..a6be76ba5
--- /dev/null
+++ b/sdk/typescript/tests-ts/support/python.ts
@@ -0,0 +1,8 @@
+export function pythonExecutable(): string | null {
+ return (
+ process.env["PYTHON"] ??
+ Bun.which("python3") ??
+ Bun.which("python") ??
+ Bun.which("py")
+ );
+}
diff --git a/sdk/typescript/tests-ts/workbench-nested-git-utf8.test.ts b/sdk/typescript/tests-ts/workbench-nested-git-utf8.test.ts
index 8cab07e2a..f9c044527 100644
--- a/sdk/typescript/tests-ts/workbench-nested-git-utf8.test.ts
+++ b/sdk/typescript/tests-ts/workbench-nested-git-utf8.test.ts
@@ -1,3 +1,4 @@
+import { pythonExecutable } from "./support/python.js";
import { spawnSync } from "node:child_process";
import {
mkdirSync,
@@ -27,15 +28,6 @@ function git(directory: string, ...args: string[]): void {
expect(result.status, result.stderr).toBe(0);
}
-function pythonExecutable(): string | null {
- return (
- process.env["PYTHON"] ??
- Bun.which("python3") ??
- Bun.which("python") ??
- Bun.which("py")
- );
-}
-
test("writes nested Git pointers as UTF-8 independently of the locale", () => {
const root = realpathSync(
mkdtempSync(join(tmpdir(), "codex-security-nested-git-utf8-")),