OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
refactor: render MCP threat models in TypeScript (#1839)
Michael D'Angeloee4c6109dca7
diff --git a/plugins/codex-security/mcp-app/src/threat-model-document.ts b/plugins/codex-security/mcp-app/src/threat-model-document.tsindex 5626f1bda..4f0638bd6 100644--- a/plugins/codex-security/mcp-app/src/threat-model-document.ts+++ b/plugins/codex-security/mcp-app/src/threat-model-document.ts@@ -1,12 +1,11 @@-import { join } from "node:path";import type { ArtifactContext } from "./artifact-context.js";import {artifactDestination,readArtifactJsonObject,replaceArtifactText,} from "./artifact-io.js";-import { resolvePythonCommand, runPythonWithInput } from "./python_command.js";import { asRecord } from "./record.js";+import { renderThreatModel } from "./threat-model-render.js";const pendingDocuments = new Map<string, Promise<void>>();@@ -48,9 +47,11 @@ async function writeCurrentThreatModelDocument(["threatmodel.md"],"threat model document",);- const python = context.pythonCommand ?? (await resolvePythonCommand());const target = asRecord(document?.target);- const markdown = await renderThreatModel(python, context.pluginRoot!, {+ const snapshotDigest =+ target?.snapshotDigest ??+ asRecord(context.targetContract?.target)?.requiredSnapshotDigest;+ const markdown = renderThreatModel({threatModel,provenance: {source: context.layout,@@ -58,8 +59,7 @@ async function writeCurrentThreatModelDocument(target: context.repoRoot,revision: context.targetRevision,snapshotDigest:- target?.snapshotDigest ??- asRecord(context.targetContract?.target)?.requiredSnapshotDigest,+ typeof snapshotDigest === "string" ? snapshotDigest : undefined,status: context.status ?? "running",provisional: context.status !== "complete",...(context.scope === undefined@@ -73,22 +73,3 @@ async function writeCurrentThreatModelDocument(return `The threat model was saved, but threatmodel.md could not be written: ${reason}`;}}--function renderThreatModel(- python: string,- pluginRoot: string,- input: Record<string, unknown>,-): Promise<string> {- return runPythonWithInput(- python,- [- "-I",- "-X",- "utf8",- join(pluginRoot, "scripts", "threat_model_projection.py"),- "--input-json-stdin",- ],- JSON.stringify(input),- "Threat-model renderer",- );-}diff --git a/plugins/codex-security/mcp-app/src/threat-model-format.ts b/plugins/codex-security/mcp-app/src/threat-model-format.tsnew file mode 100644index 000000000..c57a77196--- /dev/null+++ b/plugins/codex-security/mcp-app/src/threat-model-format.ts@@ -0,0 +1,29 @@+const whitespace = /[\p{White_Space}\u001c-\u001f]+/gu;++/** Match the retained artifact projection's Python whitespace semantics. */+export function nonblank(value: string): boolean {+ return value.replace(whitespace, "").length > 0;+}++function collapse(value: string): string {+ return value.replace(whitespace, " ").replace(/^ | $/gu, "");+}++/** Plain metadata remains text; authored single-backtick spans remain intact. */+export function text(value: unknown, fallback = ""): string {+ const candidate =+ typeof value === "string" && nonblank(value) ? value : fallback;+ const normalized = collapse(candidate);+ const protectedText =+ /^(?:#{1,6} |[-*+] |> |```|~~~|\p{Decimal_Number}+[.)] |\|)/u.test(+ normalized,+ )+ ? `Text: ${normalized}`+ : normalized;+ return protectedText+ .split(/((?<!`)`[^`\n]+`(?!`))/u)+ .map((part, index) =>+ index % 2 ? part : part.replace(/([\\`*_\[\]<>])/gu, "\\$1"),+ )+ .join("");+}diff --git a/plugins/codex-security/mcp-app/src/threat-model-render.ts b/plugins/codex-security/mcp-app/src/threat-model-render.tsnew file mode 100644index 000000000..237d755d0--- /dev/null+++ b/plugins/codex-security/mcp-app/src/threat-model-render.ts@@ -0,0 +1,166 @@+import { isRecord } from "./record.js";+import { nonblank, text } from "./threat-model-format.js";+import { threatModelSchemas } from "./threat-model-schema.js";+import * as z from "zod/v4";++const sections = [+ ["Assets", "assets"],+ ["Trust Boundaries", "trustBoundaries"],+ ["Attacker Capabilities", "attackerCapabilities"],+ ["Security Objectives", "securityObjectives"],+ ["Assumptions", "assumptions"],+] as const;+const shapes = threatModelSchemas(+ z.array(z.string().min(1)),+ z.string().refine(nonblank),+);++const fields = [+ ["source", "Source"],+ ["scanId", "Scan"],+ ["target", "Target"],+ ["revision", "Revision"],+ ["snapshotDigest", "Snapshot"],+ ["status", "Result status"],+] as const;+export interface ThreatModelRenderInput {+ threatModel: unknown;+ provenance?: {+ source?: string;+ scanId?: string;+ target?: string;+ revision?: string;+ snapshotDigest?: string;+ status?: string;+ provisional?: boolean;+ scanScope?: {+ includePaths: string[];+ excludePaths?: string[];+ summary?: string;+ };+ };+}++function markdownContent(model: Record<string, unknown>): string | undefined {+ return model.format === "markdown" &&+ typeof model.content === "string" &&+ nonblank(model.content)+ ? model.content+ : undefined;+}++function body(model: Record<string, unknown>): string {+ const markdown = markdownContent(model);+ const structured = shapes.schema.options[0].safeParse(model);+ if (markdown !== undefined) {+ // Structured models permit legacy metadata as extension fields.+ if (!structured.success) validateMarkdownMetadata(model);+ return markdown;+ }+ if (!structured.success) {+ const [key, index] = structured.error.issues[0]!.path;+ if (key === "summary")+ throw new Error(+ model.format === "markdown"+ ? "threatModel.content: expected non-empty Markdown"+ : "threatModel.summary: expected a non-empty string",+ );+ throw new Error(+ index === undefined+ ? `threatModel.${String(key)}: expected an array`+ : `threatModel.${String(key)}[${String(index)}]: expected a non-empty string`,+ );+ }+ const { summary } = structured.data;+ const result = [+ nonblank(summary)+ ? summary+ : "No explicit canonical threat-model summary was recorded.",+ ];+ for (const [heading, key] of sections) {+ const values = structured.data[key];+ if (values?.length)+ result.push(+ `## ${heading}`,+ values.map((value) => "- " + value.replaceAll("\n", "\n ")).join("\n"),+ );+ }+ return "# Threat Model\n\n" + result.join("\n\n");+}++function validateMarkdownMetadata(model: Record<string, unknown>): void {+ // Keep the retained renderer's field order and diagnostics while sharing the+ // authored-tool schema.+ if (!shapes.markdown.shape.origin.safeParse(model.origin).success)+ throw new Error("threatModel.origin: unsupported value");+ if (!("scope" in model)) return;+ const scope = model.scope;+ if (!isRecord(scope) || !("includePaths" in scope))+ throw new Error("threatModel.scope: expected an object with includePaths");+ const parsed = shapes.scope.safeParse(scope);+ if (!parsed.success) {+ const key = parsed.error.issues[0]!.path[0];+ throw new Error(+ key === "summary"+ ? "threatModel.scope.summary: expected a non-empty string"+ : `threatModel.scope.${String(key)}: expected an array of non-empty strings`,+ );+ }+}++function scopeLines(scope: unknown, label: string): string[] {+ if (+ !isRecord(scope) ||+ !Array.isArray(scope.includePaths) ||+ !scope.includePaths.every((path) => typeof path === "string")+ ) {+ return [`- ${label}: not recorded`];+ }+ const lines = [`- ${label}: ${text(scope.includePaths.join(", "), "none")}`];+ if (+ Array.isArray(scope.excludePaths) &&+ scope.excludePaths.length &&+ scope.excludePaths.every((path) => typeof path === "string")+ ) {+ lines.push(+ `- ${label} exclusions: ${text(scope.excludePaths.join(", "), "none")}`,+ );+ }+ if (typeof scope.summary === "string" && scope.summary)+ lines.push(+ `- ${label} description: ${text(scope.summary, "not recorded")}`,+ );+ return lines;+}++export function renderThreatModel(input: ThreatModelRenderInput): string {+ const model = input.threatModel;+ if (!isRecord(model)) throw new Error("threatModel: expected an object");+ const provenance = input.provenance ?? {};+ const rendered = body(model);+ const footer = ["---", "", "## Saved Model Context", ""];+ for (const [key, label] of fields) {+ const value = provenance[key];+ if (value) footer.push(`- ${label}: ${text(value, "not recorded")}`);+ }+ footer.push(`- Model origin: ${text(model.origin, "not recorded")}`);+ footer.push(...scopeLines(model.scope, "Model scope"));+ if (isRecord(provenance.scanScope))+ footer.push(...scopeLines(provenance.scanScope, "Scan scope"));+ if (provenance.provisional)+ footer.push(+ "",+ "This is a provisional model saved before successful completion.",+ );+ const result =+ rendered ++ (rendered.endsWith("\n") ? "\n" : "\n\n") ++ footer.join("\n") ++ "\n";+ if (!result.isWellFormed()) {+ throw new Error(+ "Threat-model Markdown contains an unpaired Unicode surrogate",+ );+ }+ return result;+}diff --git a/plugins/codex-security/mcp-app/tests/test_threat_model_document.ts b/plugins/codex-security/mcp-app/tests/test_threat_model_document.tsindex 282ba2da0..9a31af7b1 100644--- a/plugins/codex-security/mcp-app/tests/test_threat_model_document.ts+++ b/plugins/codex-security/mcp-app/tests/test_threat_model_document.ts@@ -9,10 +9,8 @@ import {watch,writeFile,} from "node:fs/promises";-import { EventEmitter } from "node:events";-import { createRequire, syncBuiltinESMExports } from "node:module";+import { promises as fs } from "node:fs";import { join } from "node:path";-import { PassThrough, Writable } from "node:stream";import { test } from "node:test";import { importModule } from "./import-module.ts";import {@@ -261,7 +259,42 @@ test("a convenience-document failure preserves the worker result and reports a w}});-test("the configured worker interpreter is honored without losing the canonical model on failure", async () => {+test("a renderer failure preserves saved canonical bytes and reports a warning", async () => {+ const root = await temporaryDirectory("threatmodel-render-failure-");+ try {+ const resultPath = join(root, "result.json");+ const canonical = Buffer.from(+ JSON.stringify(+ {+ scanId,+ complete: false,+ threatModel: { summary: "" },+ findings: [],+ coverage,+ },+ null,+ 2,+ ) + "\n",+ );+ await writeFile(resultPath, canonical);+ const warning = await saveThreatModelDocument(+ { root, repoRoot: root, layout: "worker", scanId, pluginRoot },+ threatModel,+ );+ assert.equal(+ warning,+ "The threat model was saved, but threatmodel.md could not be written: threatModel.summary: expected a non-empty string",+ );+ assert.deepEqual(await readFile(resultPath), canonical);+ await assert.rejects(readFile(join(root, "threatmodel.md")), {+ code: "ENOENT",+ });+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("saved-model rendering does not require the worker's Python interpreter", async () => {const root = await temporaryDirectory("threatmodel-python-");try {const result = await recordCodexSecurityWorkerScanDraft(@@ -275,7 +308,12 @@ test("the configured worker interpreter is honored without losing the canonical},{ scanId, complete: false, threatModel, findings: [], coverage },);- assert.match(result.warnings[0], /missing-interpreter/);+ assert.equal(result.warnings, undefined);+ assert.ok(+ (await readFile(join(root, "threatmodel.md"), "utf8")).startsWith(+ markdown,+ ),+ );assert.deepEqual((await readJson(root, "result.json")).threatModel,threatModel,@@ -286,58 +324,33 @@ test("the configured worker interpreter is honored without losing the canonical});test("overlapping draft projections retain the latest committed model", async (t) => {- const root = await temporaryDirectory("threatmodel-concurrent-");- const childProcess = createRequire(import.meta.url)("node:child_process");- const firstStarted = Promise.withResolvers<{- provenance: { revision: string; snapshotDigest: string };- }>();- let releaseFirst: (() => void) | undefined;+ const root = await temporaryDirectory("threatmodel-concurrent-", true);+ const firstStarted = Promise.withResolvers<string>();+ const releaseFirst = Promise.withResolvers<void>();+ const originalRename = fs.rename;+ let firstProjection = true;let activeRenderers = 0;let maximumRenderers = 0;- t.mock.method(childProcess, "spawn", (command: string, args: string[]) => {- assert.equal(command, "fixture-python");- assert.deepEqual(args, [- "-B",- "-I",- "-X",- "utf8",- join(pluginRoot, "scripts", "threat_model_projection.py"),- "--input-json-stdin",- ]);- const child = new EventEmitter() as EventEmitter & {- stdout: PassThrough;- stderr: PassThrough;- stdin: Writable;- };- child.stdout = new PassThrough();- child.stderr = new PassThrough();- let contents = "";- child.stdin = new Writable({- write(chunk, _encoding, callback) {- contents += chunk.toString("utf8");- callback();- },- final(callback) {- const input = JSON.parse(contents);- activeRenderers += 1;- maximumRenderers = Math.max(maximumRenderers, activeRenderers);- const finish = () => {- child.stdout.end(input.threatModel.content);- activeRenderers -= 1;- child.emit("close", 0, null);- };- if (!releaseFirst) {- releaseFirst = finish;- firstStarted.resolve(input);- } else {- finish();+ t.mock.method(+ fs,+ "rename",+ async (...[source, destination]: Parameters<typeof fs.rename>) => {+ if (destination !== join(root, "threatmodel.md"))+ return originalRename(source, destination);+ activeRenderers += 1;+ maximumRenderers = Math.max(maximumRenderers, activeRenderers);+ try {+ if (firstProjection) {+ firstProjection = false;+ firstStarted.resolve(await readFile(source, "utf8"));+ await releaseFirst.promise;}- callback();- },- });- return child;- });- syncBuiltinESMExports();+ return await originalRename(source, destination);+ } finally {+ activeRenderers -= 1;+ }+ },+ );const context = {root,repoRoot: root,@@ -366,11 +379,12 @@ test("overlapping draft projections retain the latest committed model", async (tfindings: [],coverage,});- const input = await firstStarted.promise;- assert.equal(input.provenance.revision, context.targetRevision);- assert.equal(- input.provenance.snapshotDigest,- context.targetContract.target.requiredSnapshotDigest,+ const firstDocument = await firstStarted.promise;+ assert.ok(firstDocument.includes(`Revision: ${context.targetRevision}`));+ assert.ok(+ firstDocument.includes(+ `Snapshot: ${context.targetContract.target.requiredSnapshotDigest}`,+ ),);const latest = recordCodexSecurityWorkerScanDraft(context, {scanId,@@ -380,31 +394,29 @@ test("overlapping draft projections retain the latest committed model", async (tcoverage,});await latestCommitted;- releaseFirst!();+ releaseFirst.resolve();const results = await Promise.all([first, latest]);assert.deepEqual(results.map((result) => result.warnings),[undefined, undefined],);assert.equal(maximumRenderers, 1);- assert.equal(- await readFile(join(root, "threatmodel.md"), "utf8"),- latestModel.content,- );+ const latestDocument = await readFile(join(root, "threatmodel.md"), "utf8");+ assert.ok(latestDocument.startsWith(latestModel.content));// A caller queued with older input must reread the saved canonical result.await saveThreatModelDocument(context, firstModel);assert.equal(await readFile(join(root, "threatmodel.md"), "utf8"),- latestModel.content,+ latestDocument,);assert.deepEqual((await readJson(root, "result.json")).threatModel,latestModel,);} finally {+ releaseFirst.resolve();await events.return!();t.mock.restoreAll();- syncBuiltinESMExports();await rm(root, { recursive: true, force: true });}});diff --git a/plugins/codex-security/mcp-app/tests/test_threat_model_installed.ts b/plugins/codex-security/mcp-app/tests/test_threat_model_installed.tsnew file mode 100644index 000000000..0b2a817c5--- /dev/null+++ b/plugins/codex-security/mcp-app/tests/test_threat_model_installed.ts@@ -0,0 +1,87 @@+import assert from "node:assert/strict";+import { cp, mkdir, readFile, rm } from "node:fs/promises";+import { join, resolve } from "node:path";+import { test } from "node:test";+import { assertNoError } from "./assertions.ts";+import { startRpcServer } from "./support/rpc-server.ts";+import { temporaryDirectory } from "./support/temporary-directories.ts";++const source =+ process.env.CODEX_SECURITY_TEST_PLUGIN_ROOT ??+ resolve(import.meta.dirname, "../../../../sdk/typescript/_bundled_plugin");++test("installed worker MCP saves threat models without Python", async (t) => {+ const root = await temporaryDirectory("threatmodel-installed-", true);+ t.after(() => rm(root, { recursive: true, force: true }));+ const pluginRoot = join(root, "installed plugin");+ await cp(source, pluginRoot, { recursive: true });+ const artifactRoot = join(root, "artifacts");+ const repoRoot = join(root, "repository");+ const emptyPath = join(root, "empty-path");+ await Promise.all(+ [artifactRoot, repoRoot, emptyPath].map((path) =>+ mkdir(path, { recursive: true }),+ ),+ );+ const scanId = "7b95abf2-dc04-47a9-9950-53b5c2057f49";+ const server = startRpcServer({+ command: process.execPath,+ args: [join(pluginRoot, "mcp", "server.mjs"), "--artifact-writer"],+ cwd: root,+ env: {+ ...process.env,+ PATH: emptyPath,+ PYTHON: join(emptyPath, "python"),+ CODEX_SECURITY_PYTHON_COMMAND: join(emptyPath, "python"),+ XDG_CACHE_HOME: join(root, "cache"),+ CODEX_SECURITY_PLUGIN_ROOT: pluginRoot,+ CODEX_SECURITY_ARTIFACT_ROOT: artifactRoot,+ CODEX_SECURITY_REPO_ROOT: repoRoot,+ CODEX_SECURITY_ARTIFACT_LAYOUT: "worker",+ CODEX_SECURITY_SCAN_ID: scanId,+ },+ });+ try {+ assertNoError(await server.initialize("threatmodel-installed"));+ const content = "# Saved model\r\n\r\n Preserve spacing.\r\n";+ const threatModel = {+ summary: "Legacy structured model.",+ format: "markdown",+ content,+ origin: false,+ scope: { includePaths: ["src/[api]"] },+ };+ const draft = {+ scanId,+ complete: false,+ findings: [],+ coverage: { surfaces: [], explicitExclusions: [], deferred: [] },+ };+ const result = await server.callTool(2, {+ name: "record_codex_security_scan_draft",+ arguments: { ...draft, threatModel },+ });+ assertNoError(result);+ assert.equal(result.result.structuredContent.warnings, undefined);+ const documentPath = join(artifactRoot, "threatmodel.md");+ const document = await readFile(documentPath, "utf8");+ assert.ok(document.startsWith(content));+ assert.match(document, /Model origin: not recorded\n/);+ assert.match(document, /Model scope: src\/\\\[api\\\]\n/);+ assert.match(document, /provisional/);+ assertNoError(+ await server.callTool(3, {+ name: "record_codex_security_scan_draft",+ arguments: draft,+ }),+ );+ assert.equal(await readFile(documentPath, "utf8"), document);+ assert.deepEqual(+ JSON.parse(await readFile(join(artifactRoot, "result.json"), "utf8"))+ .threatModel,+ threatModel,+ );+ } finally {+ await server.stop();+ }+});diff --git a/plugins/codex-security/mcp-app/tests/test_threat_model_render.ts b/plugins/codex-security/mcp-app/tests/test_threat_model_render.tsnew file mode 100644index 000000000..7c189f4e5--- /dev/null+++ b/plugins/codex-security/mcp-app/tests/test_threat_model_render.ts@@ -0,0 +1,228 @@+import assert from "node:assert/strict";+import { execFileSync } from "node:child_process";+import { join } from "node:path";+import { test } from "node:test";+import { importSource } from "./import-module.ts";+import type { ThreatModelRenderInput as Input } from "../src/threat-model-render.js";++const pluginRoot = join(import.meta.dirname, "../..");+const { renderThreatModel } = await importSource(+ join(pluginRoot, "mcp-app/src/threat-model-render.ts"),+);+const python = process.env.PYTHON?.trim() || "python3";+function pythonRender(input: Input): string {+ return execFileSync(+ python,+ [+ "-B",+ "-I",+ "-X",+ "utf8",+ join(pluginRoot, "scripts/threat_model_projection.py"),+ "--input-json-stdin",+ ],+ { input: JSON.stringify(input), encoding: "utf8", stdio: "pipe" },+ );+}++function equivalent(+ name: string,+ threatModel: unknown,+ provenance?: Input["provenance"],+) {+ test(`threat model rendering matches Python: ${name}`, () => {+ const input = { threatModel, provenance };+ assert.equal(renderThreatModel(input), pythonRender(input));+ });+}+const markdownModel = { format: "markdown", content: "# Full model\n" };+equivalent("all structured sections and multiline bodies", {+ summary: "A **model**.\n\n```text\nA -> B\n```",+ assets: ["Queue\n ownership", "Stored records"],+ trustBoundaries: ["API -> queue"],+ attackerCapabilities: ["Send requests"],+ securityObjectives: ["Keep [records] private"],+ assumptions: ["Authenticated callers"],+});+equivalent("whitespace-only structured strings", {+ summary: " \n\t",+ assets: [" \n\t"],+});+equivalent("blank Markdown falls back to the summary", {+ ...markdownModel,+ summary: "Saved summary",+ content: " \n",+});+equivalent("structured metadata bypasses Markdown validation", {+ ...markdownModel,+ summary: " ",+ assets: [" "],+ origin: false,+ scope: { includePaths: ["", "src"], excludePaths: 42, summary: [] },+});+equivalent("Markdown accepts non-structured extensions", {+ ...markdownModel,+ summary: 42,+ assets: false,+});+equivalent(+ "scope formatting and footer truthiness",+ {+ summary: "Model",+ origin: false,+ scope: { includePaths: [], excludePaths: [""], summary: " " },+ },+ {+ source: "",+ scanId: "example-scan",+ target: "",+ revision: "",+ snapshotDigest: "",+ status: " ",+ provisional: false,+ },+);+equivalent(+ "footer escaping preserves inline code",+ {+ ...markdownModel,+ content: "# Authored [model]\n\nKeep **this**.",+ origin: "provided",+ scope: {+ includePaths: ["src/[queue]", "a\\b"],+ excludePaths: ["tmp/*"],+ summary: "## Scope\n`[literal]` <tag>",+ },+ },+ {+ source: "- source",+ scanId: "1. scan",+ target: "> workspace",+ revision: "``revision``",+ snapshotDigest: "| digest",+ status: "```status",+ provisional: true,+ scanScope: {+ includePaths: ["."],+ excludePaths: ["vendor"],+ summary: "Source\tboundary",+ },+ },+);+for (const ending of ["", "\n", "\n\n", "\r\n"]) {+ equivalent(`authored Markdown ending ${JSON.stringify(ending)}`, {+ ...markdownModel,+ content: "# Model\n\n```text\nexact spacing\n```" + ending,+ });+}+for (const value of ["\ufeff", "\u0085", "\u001c", "\u00a0"]) {+ equivalent(+ `Python whitespace ${JSON.stringify(value)}`,+ { summary: value, assets: [value] },+ { target: `a${value}b` },+ );+}+equivalent("a BOM is authored Markdown", {+ ...markdownModel,+ content: "\ufeff",+});++const invalidCases: [unknown, string][] = [+ [{}, "summary"],+ [{ summary: "" }, "summary"],+ [{ summary: "Model", assets: false }, "assets"],+ [{ summary: "Model", assets: [""] }, "assets"],+ [{ ...markdownModel, content: "\u0085" }, "content"],+ [{ ...markdownModel, origin: false }, "origin"],+ [{ ...markdownModel, scope: [] }, "scope"],+ [{ ...markdownModel, scope: {} }, "scope"],+ [{ ...markdownModel, scope: { includePaths: [""] } }, "scope.includePaths"],+ [+ {+ ...markdownModel,+ scope: { includePaths: [], excludePaths: false },+ },+ "scope.excludePaths",+ ],+ [+ {+ ...markdownModel,+ scope: { includePaths: [], summary: "" },+ },+ "scope.summary",+ ],+];+for (const [threatModel, field] of invalidCases) {+ test(`invalid model identifies ${field}: ${JSON.stringify(threatModel)}`, () => {+ const diagnostic = `threatModel.${field}`;+ assert.throws(+ () => pythonRender({ threatModel }),+ (error: unknown) =>+ String((error as { stderr: unknown }).stderr).includes(diagnostic),+ );+ assert.throws(+ () => renderThreatModel({ threatModel }),+ (error: unknown) =>+ error instanceof Error && error.message.includes(diagnostic),+ );+ });+}+test("non-object models report a threatModel diagnostic", () => {+ for (const threatModel of [null, [], false, "model"]) {+ assert.throws(() => renderThreatModel({ threatModel }), /threatModel/);+ }+});++test("Python finalizer recognizes native renderer bytes as the current projection", () => {+ const threatModel = { summary: "Saved model", assets: ["Queue"] };+ const scan = {+ id: "example-scan",+ status: "running",+ threatModel,+ target: {+ displayName: "Example [workspace]",+ revision: "example-revision",+ },+ scope: { includePaths: ["src"], excludePaths: [] },+ };+ const markdown = renderThreatModel({+ threatModel,+ provenance: {+ source: "scan",+ scanId: scan.id,+ target: scan.target.displayName,+ revision: scan.target.revision,+ status: scan.status,+ provisional: true,+ scanScope: scan.scope,+ },+ });+ const result = execFileSync(+ python,+ [+ "-B",+ "-I",+ "-X",+ "utf8",+ "-c",+ `+import json, pathlib, sys, tempfile+sys.path.insert(0, sys.argv[1])+import finalize_scan_contract as finalizer+payload = json.load(sys.stdin)+with tempfile.TemporaryDirectory() as directory:+ root = pathlib.Path(directory).resolve()+ (root / "scan-manifest.json").write_text(json.dumps({"scan": payload["scan"]}))+ (root / "threatmodel.md").write_bytes(payload["markdown"].encode("utf-8"))+ print(finalizer.describe_threat_model(root)["path"] == str(root / "threatmodel.md"))+`,+ join(pluginRoot, "scripts"),+ ],+ {+ input: JSON.stringify({ scan, markdown }),+ encoding: "utf8",+ stdio: "pipe",+ },+ );+ assert.equal(result.trim(), "True");+});