OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
feat: expose durable scan lifecycle telemetry (#2274)
Michael D'Angelocfb78b9cd9d8
diff --git a/plugins/codex-security/mcp-app/server.ts b/plugins/codex-security/mcp-app/server.tsindex ddc39ba53..6b36af822 100644--- a/plugins/codex-security/mcp-app/server.ts+++ b/plugins/codex-security/mcp-app/server.ts@@ -10,6 +10,7 @@ import { randomUUID } from "node:crypto";import { realpath, stat } from "node:fs/promises";import { isAbsolute, resolve } from "node:path";import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";import * as z from "zod/v4";import { resolvePythonCommand } from "./src/python_command.js";import { version as MCP_APP_VERSION } from "./package.json";@@ -665,6 +666,7 @@ export function createCodexSecurityServer(): McpServer {handoffClaimToken,},`${started.startDisposition === "created" ? "Started" : "Rejoined"} Standard scan ${scanId}. When the scan is in preflight, follow references/scan-runtime.md, then advance to threat_model before reviewing the target. Use available workers or parent fallback. Preserve the returned handoffClaimToken for scan progress, the semantic draft, and completion.`,+ scanId,);},);@@ -933,7 +935,7 @@ export function createCodexSecurityServer(): McpServer {"--scan-root",await scanRoot(),])) as WorkspaceState;- return workspaceResult(workspace);+ return workspaceResult(workspace, workspace.results?.scanId);},);@@ -1036,143 +1038,154 @@ export function createCodexSecurityServer(): McpServer {};}};- const preparation = await deepScanStartLock- .run(async () => {- const begun = await deepScanStore.begin({- scanId,- targetPath,- scope: hasTarget ? (scope ?? ".") : undefined,- userContext: normalizedUserContext,- handoffClaimToken,+ let registeredScanId: string | undefined;+ const preparing = deepScanStartLock.run(async () => {+ const begun = await deepScanStore.begin({+ scanId,+ targetPath,+ scope: hasTarget ? (scope ?? ".") : undefined,+ userContext: normalizedUserContext,+ handoffClaimToken,+ threadId,+ projectConfigPath,+ ...modelSettings,+ serviceTier:+ typeof serviceTier === "string" ? serviceTier : undefined,+ scanRoot: await scanRoot(),+ });+ registeredScanId = begun.scanId;+ if (handoffClaimToken) {+ authenticatedArtifactClaims.set(begun.scanId, {+ claimToken: handoffClaimToken,threadId,- projectConfigPath,- ...modelSettings,- serviceTier:- typeof serviceTier === "string" ? serviceTier : undefined,- scanRoot: await scanRoot(),});- if (handoffClaimToken) {- authenticatedArtifactClaims.set(begun.scanId, {- claimToken: handoffClaimToken,- threadId,- });- }- const immediate = deepScanTerminalResult(begun);- if (immediate) {- const coordinator = deepScanCoordinators.get(begun.scanId);- return {- begun,- immediate,- completion: {- result:- (coordinator && deepScanCompletions.get(coordinator)) ??- completeDeepScan(begun),- },- };- }- const completion: {- result?: Promise<ReturnType<typeof deepScanTerminalResult>>;- } = {};- const onStart = (coordinator: DeepScanCoordinator) => {- completion.result = deepScanCompletions.get(coordinator);- if (!completion.result) {- // The same hook runs when a remote observer adopts an expired lease.- // Completion belongs to the coordinator, not an abortable RPC waiter.- completion.result = coordinator- .settled()- .then(completeDeepScan, (error) =>- toolErrorResult(deepScanInvocationFailureMessage(error)),- );- deepScanCompletions.set(coordinator, completion.result);- }+ }+ const immediate = deepScanTerminalResult(begun);+ if (immediate) {+ const coordinator = deepScanCoordinators.get(begun.scanId);+ return {+ begun,+ immediate,+ completion: {+ result:+ (coordinator && deepScanCompletions.get(coordinator)) ??+ completeDeepScan(begun),+ },};- const started = await startDeepScanEngine({- run: begun,- registry: deepScanCoordinators,- store: deepScanStore,- runWorkbench,- ...modelSettings,- parentSandbox,- parentTurn: codexParentTurnFromExtra(extra),- pythonCommand: await resolvePythonCommand(),- pluginRoot: PLUGIN_ROOT,- log: logDeepScanEvent,- handoffClaimToken,- threadId,- onStart,- });- if (- !completion.result &&- started.coordinator instanceof DeepScanCoordinator- ) {- onStart(started.coordinator);+ }+ const completion: {+ result?: Promise<ReturnType<typeof deepScanTerminalResult>>;+ } = {};+ const onStart = (coordinator: DeepScanCoordinator) => {+ completion.result = deepScanCompletions.get(coordinator);+ if (!completion.result) {+ // The same hook runs when a remote observer adopts an expired lease.+ // Completion belongs to the coordinator, not an abortable RPC waiter.+ completion.result = coordinator+ .settled()+ .then(completeDeepScan, (error) =>+ toolErrorResult(deepScanInvocationFailureMessage(error)),+ );+ deepScanCompletions.set(coordinator, completion.result);}- return { begun, ...started, completion };- })- .catch((error: unknown) => ({- invocationFailure: toolErrorResult(- deepScanInvocationFailureMessage(error),- ),- }));- if ("invocationFailure" in preparation)- return preparation.invocationFailure;- const { begun } = preparation;+ };+ const started = await startDeepScanEngine({+ run: begun,+ registry: deepScanCoordinators,+ store: deepScanStore,+ runWorkbench,+ ...modelSettings,+ parentSandbox,+ parentTurn: codexParentTurnFromExtra(extra),+ pythonCommand: await resolvePythonCommand(),+ pluginRoot: PLUGIN_ROOT,+ log: logDeepScanEvent,+ handoffClaimToken,+ threadId,+ onStart,+ });+ if (+ !completion.result &&+ started.coordinator instanceof DeepScanCoordinator+ ) {+ onStart(started.coordinator);+ }+ return { begun, ...started, completion };+ });+ let preparation: Awaited<typeof preparing> | undefined;let result;- if (preparation.immediate) {- result = (await preparation.completion.result) ?? preparation.immediate;- } else {- const { coordinator, joined } = preparation;- if (joined) {- logDeepScanEvent({- event: "coordinator_joined",- scanId: begun.scanId,- });+ try {+ preparation = await preparing;+ const { begun } = preparation;+ if (preparation.immediate) {+ result =+ (await preparation.completion.result) ?? preparation.immediate;+ } else {+ const { coordinator, joined } = preparation;+ if (joined) {+ logDeepScanEvent({+ event: "coordinator_joined",+ scanId: begun.scanId,+ });+ }+ const terminal = await coordinator.wait(abortSignalFromExtra(extra));+ result = preparation.completion.result+ ? await preparation.completion.result+ : await completeDeepScan(terminal);}- const terminal = await coordinator.wait(abortSignalFromExtra(extra));- result = preparation.completion.result- ? await preparation.completion.result- : await completeDeepScan(terminal);- }- if (!result) {- return toolErrorResult(- deepScanInvocationFailureMessage(- new Error(- `Deep Scan ${begun.scanId} ended without a terminal result.`,+ if (!result) {+ result = toolErrorResult(+ deepScanInvocationFailureMessage(+ new Error(+ `Deep Scan ${begun.scanId} ended without a terminal result.`,+ ),),- ),- );- }- // A canceled waiter or a transport size error never delivers the scan ID.- const transport = server.server.transport;- if (- !handoffClaimToken &&- "structuredContent" in result &&- "completion" in result.structuredContent &&- transport instanceof CodexSecurityStdioTransport- ) {- transport.afterResultSent(extra.requestId, extra.signal, () =>- deepScanStartLock.run(async () => {- try {- await runWorkbench(- workbenchArgs("acknowledge-deep-scan-result", {+ );+ }+ // A canceled waiter or a transport size error never delivers the scan ID.+ const transport = server.server.transport;+ if (+ !handoffClaimToken &&+ "structuredContent" in result &&+ "completion" in result.structuredContent &&+ transport instanceof CodexSecurityStdioTransport+ ) {+ transport.afterResultSent(extra.requestId, extra.signal, () =>+ deepScanStartLock.run(async () => {+ try {+ await runWorkbench(+ workbenchArgs("acknowledge-deep-scan-result", {+ scanId: begun.scanId,+ }),+ );+ } catch (error) {+ logDeepScanEvent({+ event: "target_result_acknowledgment_failed",scanId: begun.scanId,- }),- );- } catch (error) {- logDeepScanEvent({- event: "target_result_acknowledgment_failed",- scanId: begun.scanId,- reason: failureDiagnostic(error),- });- }- }),- );+ reason: failureDiagnostic(error),+ });+ }+ }),+ );+ }+ } catch (error) {+ // Preparation has a recovery message; waiter failures retain their MCP error text.+ const message = !preparation+ ? deepScanInvocationFailureMessage(error)+ : error instanceof Error+ ? error.message+ : String(error);+ result = toolErrorResult(message);}- return result;+ return withScanTarget(result, registeredScanId);},);- const cancelSecurityScan = async (scanId: string, threadId?: string) => {+ const cancelSecurityScan = async (+ requestedScanId: string,+ threadId?: string,+ ) => {+ const scanId = requestedScanId.toLowerCase();const args = ["cancel-scan","--scan-id",@@ -1208,19 +1221,27 @@ export function createCodexSecurityServer(): McpServer {},);if (workspace === undefined && canceledLocally) {- workspace = (await runWorkbench(workbenchArgs("get-scan", { scanId })))[- "workspace"- ] as JsonObject;- }- const scan = workspace?.["results"];- const progress = isJsonObject(scan) ? scan["progress"] : undefined;- if (- workspace === undefined ||- (isJsonObject(progress) && progress["status"] === "running")- ) {- workspace = await runWorkbench(args);+ // A joined caller did not perform the write. Read the requested parent.+ const saved = (await runWorkbench(workbenchArgs("get-scan", { scanId })))+ .workspace as WorkspaceState;+ const scan = saved.results;+ const progress = isJsonObject(scan?.progress) ? scan.progress : undefined;+ if (progress?.status !== "running") {+ return workspaceResult(+ saved,+ progress?.status === "canceled" && scan?.scanId === scanId+ ? scanId+ : undefined,+ );+ }}- return workspaceResult(workspace as unknown as WorkspaceState);+ // The displayed workspace may already have a replacement scan.+ const { canceledScanId, ...displayedWorkspace } =+ workspace ?? (await runWorkbench(args));+ return workspaceResult(+ displayedWorkspace as unknown as WorkspaceState,+ canceledScanId === scanId ? canceledScanId : undefined,+ );};server.registerTool(@@ -1286,16 +1307,22 @@ export function createCodexSecurityServer(): McpServer {annotations: writingAnnotations,_meta: appMeta,},- async ({ scanId, occurrenceId }) =>- scanActionResult(- await runWorkbench([- "get-scan",- "--scan-id",- scanId,- ...optionalArg("--occurrence-id", occurrenceId),- ]),+ async ({ scanId, occurrenceId }) => {+ const context = await runWorkbench([+ "get-scan",+ "--scan-id",+ scanId,+ ...optionalArg("--occurrence-id", occurrenceId),+ ]);+ const loadedId = isJsonObject(context.scan)+ ? context.scan.scanId+ : undefined;+ return scanActionResult(+ context,"Loaded Codex Security scan state.",- ),+ loadedId === scanId.toLowerCase() ? loadedId : undefined,+ );+ },);server.registerTool(@@ -1626,19 +1653,21 @@ export function createCodexSecurityServer(): McpServer {? turnMetadata.turn_id: undefined;try {+ const completed = await runWorkbench([+ "complete-scan",+ "--scan-id",+ scanId,+ ...optionalArg("--claim-token", handoffClaimToken),+ ...optionalArg("--thread-id", threadIdFromExtra(extra)),+ ...optionalArg(+ "--turn-id",+ typeof turnId === "string" ? turnId : undefined,+ ),+ ]);return scanActionResult(- await runWorkbench([- "complete-scan",- "--scan-id",- scanId,- ...optionalArg("--claim-token", handoffClaimToken),- ...optionalArg("--thread-id", threadIdFromExtra(extra)),- ...optionalArg(- "--turn-id",- typeof turnId === "string" ? turnId : undefined,- ),- ]),+ completed,"Validated and indexed the completed Codex Security scan.",+ isJsonObject(completed.scan) ? completed.scan.scanId : undefined,);} catch (error) {throw new Error(completionFailureMessage(error));@@ -1700,6 +1729,7 @@ export function createCodexSecurityServer(): McpServer {return scanActionResult(failed,"Recorded the Codex Security scan failure.",+ isJsonObject(scan) ? scan.scanId : undefined,);},);@@ -2117,7 +2147,7 @@ function redactHandoffClaimToken(result: JsonObject) {return result;}-function workspaceResult(workspace: WorkspaceState) {+function workspaceResult(workspace: WorkspaceState, scanId?: unknown) {const results = workspace.results;const setupSummary = workspace.setup.submitted? "Codex Security setup is saved."@@ -2126,7 +2156,11 @@ function workspaceResult(workspace: WorkspaceState) {results && typeof results.scanDir === "string"? ` Scan state is attached at ${results.scanDir}.`: "";- return scanActionResult({ workspace }, `${setupSummary}${resultsSummary}`);+ return scanActionResult(+ { workspace },+ `${setupSummary}${resultsSummary}`,+ scanId,+ );}function promptOnlyScanResult(promptOnly: JsonObject) {@@ -2155,16 +2189,37 @@ function promptOnlyScanResult(promptOnly: JsonObject) {return scanActionResult(promptOnly,`${startDisposition === "joined" ? "Rejoined" : "Started"} prompt-driven scan ${scanId}. Use the returned scanId and scanDir for every phase. Save progress and the final semantic draft with record_codex_security_scan_draft; the workbench writes the unsealed canonical files. Then call complete_codex_security_scan once to seal and index the completed findings.`,+ scanId,);}-function scanActionResult<T extends JsonObject>(result: T, summary: string) {+function withScanTarget<T extends CallToolResult>(result: T, scanId: unknown) {+ if (scanId === undefined) return result;+ const id = scanSchema.scanId.safeParse(scanId);+ if (!id.success) return result;return {- content: [{ type: "text" as const, text: summary }],- structuredContent: result,+ ...result,+ _meta: {+ ...result._meta,+ "codex/telemetry": { span: { target_id: id.data } },+ },};}+function scanActionResult<T extends JsonObject>(+ result: T,+ summary: string,+ scanId?: unknown,+) {+ return withScanTarget(+ {+ content: [{ type: "text" as const, text: summary }],+ structuredContent: result,+ },+ scanId,+ );+}+function toolErrorResult(message: string) {return {content: [{ type: "text" as const, text: message }],diff --git a/plugins/codex-security/mcp-app/src/workbench/migrations.ts b/plugins/codex-security/mcp-app/src/workbench/migrations.tsindex d462c80b3..30f122dc6 100644--- a/plugins/codex-security/mcp-app/src/workbench/migrations.ts+++ b/plugins/codex-security/mcp-app/src/workbench/migrations.ts@@ -230,9 +230,9 @@ export function applyMigrations(} else if (item.version === 16) backfill = repairStableTargets(database);else if (applied.has(item.version)) {if (- [2, 12, 13, 26, 28, 31, 32, 42, 47, 50, 54, 55, 58, 59, 60].includes(- item.version,- )+ [+ 2, 12, 13, 26, 28, 31, 32, 42, 47, 50, 54, 55, 58, 59, 60, 61,+ ].includes(item.version))repairAdditive(database, item.version);else if (item.version === 11) repairDeepScan(database);diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_cancel_response.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_cancel_response.tsindex bd3402b8a..53b37175e 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_cancel_response.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_cancel_response.ts@@ -1,4 +1,5 @@import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";import { mkdir, readFile, rm, writeFile } from "node:fs/promises";import { execFileSync } from "node:child_process";import { join } from "node:path";@@ -7,6 +8,7 @@ import { fileURLToPath } from "node:url";import { importModule } from "./import-module.ts";interface FixtureScanResults {+ scanId?: string;progress: { status: string };}@@ -41,6 +43,7 @@ interface CancelResponseModule {_registeredTools: {cancel_codex_security_scan_from_app: {handler(args: { scanId: string }): Promise<{+ _meta?: Record<string, unknown>;structuredContent: { workspace: FixtureWorkspace };}>;};@@ -53,6 +56,11 @@ const applicationRoot = fileURLToPath(new URL("../", import.meta.url));const source = await readFile(new URL("../server.ts", import.meta.url), "utf8");const calls: string[][] = [];let workspace: FixtureWorkspace;+const scanId = randomUUID();+const replacement = {+ setup: { submitted: true },+ results: { scanId: randomUUID(), progress: { status: "running" } },+};let fixtureRoot: string | undefined;let joining = false;let persisted: PromiseWithResolvers<void>;@@ -72,8 +80,10 @@ const fixture: CancelResponseFixture = {},async workbench(args) {calls.push(args);- if (args[0] === "cancel-scan")+ if (args[0] === "cancel-scan") {workspace.results.progress.status = "canceled";+ return { ...replacement, canceledScanId: scanId };+ }return args[0] === "get-scan"? { workspace, scan: workspace.results }: workspace;@@ -108,16 +118,21 @@ try {server._registeredTools.cancel_codex_security_scan_from_app.handler;workspace = {setup: { submitted: true },- results: { progress: { status: "canceled" } },+ results: { scanId, progress: { status: "canceled" } },};persisted = Promise.withResolvers<void>();release = Promise.withResolvers<void>();- const first = cancel({ scanId: "fixture-scan" });+ const first = cancel({ scanId });await persisted.promise;- const second = cancel({ scanId: "fixture-scan" });+ const second = cancel({ scanId });release.resolve();- for (const result of await Promise.all([first, second])) {- assert.deepEqual(result.structuredContent.workspace, workspace);+ const [firstResult, joinedResult] = await Promise.all([first, second]);+ assert.deepEqual(firstResult.structuredContent.workspace, replacement);+ assert.deepEqual(joinedResult.structuredContent.workspace, workspace);+ for (const result of [firstResult, joinedResult]) {+ assert.deepEqual(result._meta, {+ "codex/telemetry": { span: { target_id: scanId } },+ });}assert.deepEqual(calls.map(([command]) => command),@@ -128,7 +143,7 @@ try {results: { progress: { status: "failed" } },};assert.deepEqual(- (await cancel({ scanId: "fixture-scan" })).structuredContent.workspace,+ (await cancel({ scanId })).structuredContent.workspace,workspace,);assert.equal(diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_host_shutdown.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_host_shutdown.tsindex 25ea53ebd..b5611a4ca 100644--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_host_shutdown.ts+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_host_shutdown.ts@@ -3,6 +3,7 @@ import { readFile } from "node:fs/promises";import { mock, test } from "node:test";import { fileURLToPath } from "node:url";import { Client } from "@modelcontextprotocol/sdk/client/index.js";+import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";import { importModule } from "./import-module.ts";import {@@ -189,10 +190,19 @@ try {assert.equal((await resumed.settled()).status, "succeeded");}for (const outcome of outcomes) {+ const result = outcome as CallToolResult;+ assert.equal(result.isError, true);+ assert.deepEqual(result._meta, {+ "codex/telemetry": { span: { target_id: fixture.run.scanId } },+ });+ if (stage === "takeover") {+ // The remote coordinator's wait rejects after its lease claim.+ assert.deepEqual(result.content, [+ { type: "text", text: "Deep Scan coordinator host has closed." },+ ]);+ }assert.match(- outcome instanceof Error- ? outcome.message- : JSON.stringify(outcome),+ JSON.stringify(result.content),/coordinator host has closed/,);}diff --git a/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts b/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.tsindex 631301220..84d404781 100644--- a/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts+++ b/plugins/codex-security/mcp-app/tests/test_mcp_app_smoke.ts@@ -20,6 +20,12 @@ import {import { tmpdir } from "node:os";import path from "node:path";+function assertScanTarget(meta: unknown, scanId: string) {+ assert.deepEqual(meta, {+ "codex/telemetry": { span: { target_id: scanId } },+ });+}+const continuationOptions = [{label: "Continue",@@ -432,6 +438,10 @@ async function assertWorkspaceWorksWithoutUiCapability(scope: string) {_meta: { "openai/threadId": `fixture-path-launch-${index}` },});assertNoError(launched);+ assertScanTarget(+ launched.result._meta,+ launched.result.structuredContent.scan.scanId,+ );assert.equal(launched.result.structuredContent.scan.targetPath,canonicalTarget,@@ -500,6 +510,7 @@ async function assertHeadlessStandardScanWorksWithoutUiCapability() {arguments: { targetPath: target },});assert.equal(withoutOwner.result.isError, true);+ assert.equal(withoutOwner.result._meta, undefined);assert.match(withoutOwner.result.content[0].text,/owning Codex thread context/,@@ -520,7 +531,6 @@ async function assertHeadlessStandardScanWorksWithoutUiCapability() {},});assertNoError(started);- assert.equal(started.result._meta, undefined);const result = started.result.structuredContent;assert.equal(result.startDisposition, "created");assert.match(result.scanId, /^[0-9a-f-]{36}$/);@@ -549,6 +559,12 @@ async function assertHeadlessStandardScanWorksWithoutUiCapability() {assert.equal(joined.result.structuredContent.startDisposition, "joined");assert.equal(joined.result.structuredContent.scanId, result.scanId);for (const response of [started, joined]) {+ assertScanTarget(response.result._meta, result.scanId);+ assert.deepEqual(+ response.result.structuredContent.scan.lifecycle,+ result.scan.lifecycle,+ );+ assert.equal(result.scan.lifecycle.status, "running");assert.match(response.result.content[0].text,/references\/scan-runtime\.md/,@@ -652,6 +668,11 @@ async function assertHeadlessStandardScanWorksWithoutUiCapability() {},});assertNoError(completed);+ assertScanTarget(completed.result._meta, scan.scanId);+ assert.equal(+ completed.result.structuredContent.scan.lifecycle.status,+ "completed",+ );assert.equal(completed.result.structuredContent.scan.progress.status,"complete",@@ -827,6 +848,7 @@ with sqlite3.connect(sys.argv[1]) as connection:.map((item: { text: string }) => item.text).join(" ");assert.equal(canceledWithPublicationFailure.result.isError, true);+ assertScanTarget(canceledWithPublicationFailure.result._meta, scan.scanId);assert.equal(canceledWithPublicationFailure.result.structuredContent,undefined,@@ -1906,6 +1928,7 @@ try {.map((item: { text: string }) => item.text).join(" ");assert.equal(missingPersistedDeepScan.result.isError, true);+ assert.equal(missingPersistedDeepScan.result._meta, undefined);assert.equal(missingPersistedDeepScan.result.structuredContent, undefined);assert.match(missingPersistedDeepScanText, /Codex Security scan not found/);assert.match(@@ -2289,6 +2312,7 @@ try {false,);const scanId = startedWorkspace.results.scanId;+ assertScanTarget(started.result._meta, scanId);assert.equal(startedWorkspace.results.progress.phase, "preflight");assert.equal(startedWorkspace.results.progress.status, "running");assert.equal(startedWorkspace.results.handoffStatus, "pending");@@ -2572,9 +2596,10 @@ try {);const refreshed = await testServer.callTool(10, {name: "get_codex_security_scan",- arguments: { scanId },+ arguments: { scanId: scanId.toUpperCase() },});assertNoError(refreshed);+ assertScanTarget(refreshed.result._meta, scanId);const results = refreshed.result.structuredContent.scan;assert.equal(results.findings.length, 2);assert.equal(results.findingCount, 2);@@ -3063,13 +3088,15 @@ try {arguments: { scanId: canceledScanId },});assertNoError(canceledFromNativeRoute);+ assertScanTarget(canceledFromNativeRoute.result._meta, canceledScanId);const canceled = await testServer.callTool(172, {name: "cancel_codex_security_scan",- arguments: { scanId: canceledScanId },+ arguments: { scanId: canceledScanId.toUpperCase() },_meta: { "openai/threadId": "fixture-thread" },});assertNoError(canceled);+ assertScanTarget(canceled.result._meta, canceledScanId);assert.equal(canceled.result.structuredContent.workspace.results.progress.status,"canceled",@@ -3096,6 +3123,16 @@ try {assertNoError(fallbackStarted);const fallbackScanId =fallbackStarted.result.structuredContent.workspace.results.scanId;+ const oldCancellation = await testServer.callTool(2211, {+ name: "cancel_codex_security_scan_from_app",+ arguments: { scanId: canceledScanId },+ });+ assertNoError(oldCancellation);+ assert.equal(+ oldCancellation.result.structuredContent.workspace.results.scanId,+ fallbackScanId,+ );+ assertScanTarget(oldCancellation.result._meta, canceledScanId);const fallbackClaimToken = `recovery_${randomUUID()}`;const fallbackClaimed = await testServer.callTool(2012, {name: "claim_codex_security_scan_handoff_delivery",@@ -3423,6 +3460,7 @@ with sqlite3.connect(sys.argv[1]) as connection:},});assertNoError(rotatedFailure);+ assertScanTarget(rotatedFailure.result._meta, fallbackScanId);assert.equal(rotatedFailure.result.structuredContent.scan.failureMessage,failureMessage,diff --git a/plugins/codex-security/mcp-app/tests/test_workbench_database.ts b/plugins/codex-security/mcp-app/tests/test_workbench_database.tsindex bec376917..05e6ffde3 100644--- a/plugins/codex-security/mcp-app/tests/test_workbench_database.ts+++ b/plugins/codex-security/mcp-app/tests/test_workbench_database.ts@@ -840,7 +840,10 @@ test("repairs pre-release numbering and shadowed migrations without repeating dadatabase.exec("INSERT INTO schema_migrations VALUES (5, 'scan target snapshot digests', 'original')",);- applyMigrations(database);+ applyMigrations(+ database,+ migrations.filter((item) => item.version <= 22),+ );insertScan(database);database.exec(`UPDATE scans SET handoff_status = 'delivered', handoff_claimed_at = 'old', handoff_claim_token = 'old';UPDATE schema_migrations SET name = 'scan target summaries' WHERE version = 18;@@ -942,11 +945,25 @@ test("recorded additive migrations restore missing columns and configured errordatabase.exec(`INSERT INTO deep_scan_runs (scan_id, schema_version, workflow_version, status, phase,workers, subagents, stop_after_no_new, max_discovery_runs, created_at, updated_at)VALUES ('scan', 1, 'v1', 'running', 'discovery', 1, 0, 7, 10, 'created', 'updated')`);- for (const version of [27, 28, 31, 32, 47, 54, 55, 58, 59, 60])+ for (const version of [27, 28, 31, 32, 47, 54, 55, 58, 59, 60, 61])database.prepare("INSERT INTO schema_migrations VALUES (?, ?, 'original')").run(version, migrations[version - 1].name);applyMigrations(database);+ const launch = database+ .prepare(+ "SELECT launch_surface, launch_package_version, launch_plugin_version, launch_kind FROM scans",+ )+ .get();+ assert.deepEqual(+ { ...launch },+ {+ launch_surface: null,+ launch_package_version: null,+ launch_plugin_version: null,+ launch_kind: null,+ },+ );assert.ok(database.prepare("PRAGMA table_info(scan_severity_classifications)")diff --git a/plugins/codex-security/scripts/workbench_db.py b/plugins/codex-security/scripts/workbench_db.pyindex 575899a18..b547ed9f7 100644--- a/plugins/codex-security/scripts/workbench_db.py+++ b/plugins/codex-security/scripts/workbench_db.py@@ -80,6 +80,7 @@ from workbench_finding_workflows import finding_workflow, register_workflow_scanfrom workbench_scan_start import (archive_scan,insert_running_scan,+ loaded_plugin_version,safe_segment,scan_diff_identity,scan_target_identity,@@ -139,6 +140,7 @@ from workbench_validation import (optional_text,parse_scan_cost,path_within_scope,+ read_json_object,reject_non_finite_json,require_close_note,require_occurrence,@@ -342,12 +344,7 @@ def workbench_completion_binding() -> dict[str, Any]:contract = scan_contract(scan)target_contract = contract["target"]- plugin_manifest = read_json_object(- Path(__file__).resolve().parent.parent / ".codex-plugin" / "plugin.json"- )- plugin_version = plugin_manifest.get("version")- if not isinstance(plugin_version, str) or not plugin_version:- raise SystemExit("plugin.json: expected a nonempty Codex Security plugin version.")+ plugin_version = loaded_plugin_version()target: dict[str, Any] = {"targetId": target_contract["targetId"],"displayName": target_contract["displayName"],@@ -659,7 +656,7 @@ def start_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict(workspace["id"],),).fetchone()if active is not None:- return workspace_state(connection, workspace["id"])+ return workspace_state(connection, workspace["id"], result_scan_id=active["id"])workspace_version = workspace["updated_at"]scan_id = str(uuid.uuid4())timestamp = now()@@ -710,7 +707,7 @@ def start_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dictif active is not None:if manages_transaction:connection.commit()- return workspace_state(connection, workspace["id"])+ return workspace_state(connection, workspace["id"], result_scan_id=active["id"])if workspace["updated_at"] != workspace_version:raise SystemExit("Codex Security setup changed while the scan was starting. Try again.")current_target = require_remediation_target(str(target))@@ -756,7 +753,7 @@ def start_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dictif manages_transaction:connection.rollback()raise- return workspace_state(connection, workspace["id"])+ return workspace_state(connection, workspace["id"], result_scan_id=scan_id)def _start_prompt_driven_scan(@@ -1449,14 +1446,25 @@ def register_cli_scan(scan_dir = require_cli_scan_directory(repository, args)user_context = Noneworkflow_id = None+ surface = None+ package_version = Noneif args.registration_json_stdin:registration = json.load(sys.stdin)recipe_json = json.dumps(registration["recipe"], ensure_ascii=False, separators=(",", ":"))user_context = registration.get("userContext")workflow_id = registration.get("workflowId")+ if registration.get("surface") in ("cli", "sdk"):+ surface = registration["surface"]+ if isinstance(registration.get("packageVersion"), str):+ package_version = registration["packageVersion"] or Noneelse:recipe_json = sys.stdin.read() if args.recipe_json_stdin else args.recipe_jsonrecipe = parse_scan_recipe(recipe_json, repository)+ launch_kind = "scan"+ if isinstance(recipe.get("import"), dict):+ launch_kind = "import"+ elif recipe.get("mock") is True:+ launch_kind = "mock"requested_target = recipe["target"]paths = requested_target["paths"]recipe.pop("_codexSecurityFileScopes", None)@@ -1581,6 +1589,9 @@ def register_cli_scan(timestamp=timestamp,handoff_status="delivered",scan_dir=scan_dir,+ surface=surface,+ package_version=package_version,+ launch_kind=launch_kind,)connection.execute("UPDATE scans SET recipe_json = ?, parent_scan_id = ?, user_context = ? WHERE id = ?",@@ -1593,14 +1604,19 @@ def register_cli_scan()if workflow_id is not None:register_workflow_scan(connection, workflow_id, scan_id, str(scan_dir), timestamp)+ scan = connection.execute(+ "SELECT scans.*, snapshot AS lifecycle_json FROM scans "+ "JOIN scan_lifecycles ON scan_id = scans.id WHERE scans.id = ?",+ (scan_id,),+ ).fetchone()connection.commit()except BaseException:connection.rollback()raise- scan = require_scan(connection, scan_id)return {**({"archivedScanDir": str(archived_scan_dir)} if archived_scan_dir is not None else {}),"contract": scan_contract(scan),+ "lifecycle": json.loads(scan["lifecycle_json"]),"scanDir": str(scan_dir),"scanId": scan_id,"scopeFileCount": scope_file_count,@@ -2515,9 +2531,7 @@ def scan_result(occurrence_id: str | None = None,) -> dict[str, Any]:backfill_legacy_finding_details(connection, scan)- progress = connection.execute(- "SELECT * FROM scan_progress WHERE scan_id = ?", (scan["id"],)- ).fetchone()+ scan = scan_history.scan_with_progress(connection, scan["id"])artifact_rows = connection.execute("SELECT kind, path FROM scan_artifacts WHERE scan_id = ?", (scan["id"],))@@ -2567,26 +2581,26 @@ def scan_result(else None)progress_result = {- "candidates": {"reportable": progress["reportable_findings_count"]},+ "candidates": {"reportable": scan["reportable_findings_count"]},"coverage": {- "closedRows": progress["review_items_completed"],- "filesTotal": progress["scope_file_count"],- "worklistRows": progress["review_items_total"],+ "closedRows": scan["review_items_completed"],+ "filesTotal": scan["scope_file_count"],+ "worklistRows": scan["review_items_total"],},"phase": scan["phase"],"phaseProgress": {- "completed": progress["phase_items_completed"],- "total": progress["phase_items_total"],- "unit": progress["phase_progress_unit"],+ "completed": scan["phase_items_completed"],+ "total": scan["phase_items_total"],+ "unit": scan["phase_progress_unit"],},"preflightProgress": {- "completed": progress["preflight_checks_completed"],- "total": progress["preflight_checks_total"],+ "completed": scan["preflight_checks_completed"],+ "total": scan["preflight_checks_total"],},- "preflightIssues": json.loads(progress["preflight_issues_json"]),- "reviewPass": progress["deep_review_pass"],+ "preflightIssues": json.loads(scan["preflight_issues_json"]),+ "reviewPass": scan["deep_review_pass"],"status": "canceled" if scan["canceled_at"] else scan["status"],- "updatedAt": progress["updated_at"],+ "updatedAt": scan["progress_updated_at"],}review_updated_at = ""if independent_reviews is not None:@@ -2605,6 +2619,7 @@ def scan_result("threadIds": scan_usage._scan_root_thread_ids(connection, scan, None),"executionThreadIds": scan_usage._scan_execution_thread_ids(connection, scan),"failureMessage": scan["failure_message"],+ "lifecycle": json.loads(scan["lifecycle_json"]),"findings": [finding_result(connection, scan, row, related=relations.get(row["id"], []))for row in occurrence_rows@@ -2635,7 +2650,7 @@ def scan_result("targetSummary": scan["target_summary"],"updatedAt": max(scan["updated_at"],- progress["updated_at"],+ scan["progress_updated_at"],review_updated_at,finding_management_updated_at(connection, scan["id"]) or "",),@@ -3108,19 +3123,6 @@ def require_canonical_scan_directory(scan_dir: Path) -> Path:return scan_dir-def read_json_object(path: Path) -> dict[str, Any]:- try:- payload = json.loads(- path.read_text(encoding="utf-8"),- parse_constant=reject_non_finite_json,- )- except (OSError, ValueError) as exc:- raise SystemExit(f"{path.name}: invalid JSON: {exc}") from exc- if not isinstance(payload, dict):- raise SystemExit(f"{path.name}: expected a JSON object.")- return payload--_WORKBENCH_PUBLICATION_CONTEXT = _WORKBENCH_DB_CONTEXT = SimpleNamespace(**globals())diff --git a/plugins/codex-security/scripts/workbench_native_indexes.py b/plugins/codex-security/scripts/workbench_native_indexes.pyindex 623cef23e..1f64c5030 100644--- a/plugins/codex-security/scripts/workbench_native_indexes.py+++ b/plugins/codex-security/scripts/workbench_native_indexes.py@@ -212,6 +212,7 @@ def list_repositories(LEFT JOIN scans ON scans.target_id = targets.idAND scans.id IN (SELECT scan_id FROM scan_progress)LEFT JOIN scan_progress AS progress ON progress.scan_id = scans.id+ LEFT JOIN scan_lifecycles AS lifecycle ON lifecycle.scan_id = scans.idORDER BY julianday(upper(scans.started_at)) DESC, scans.id DESC, targets.id""").fetchall():diff --git a/plugins/codex-security/scripts/workbench_saved_results.py b/plugins/codex-security/scripts/workbench_saved_results.pyindex 12125ca48..f61f3c3a0 100644--- a/plugins/codex-security/scripts/workbench_saved_results.py+++ b/plugins/codex-security/scripts/workbench_saved_results.py@@ -1303,7 +1303,10 @@ def cancel_scan_locked(db: Any, connection: Any, args: Any) -> dict[str, Any]:raise SystemExit("A scan can only be canceled from its owning Codex thread.")if scan["canceled_at"] is not None:connection.commit()- return db.workspace_state(connection, scan["workspace_id"])+ return {+ **db.workspace_state(connection, scan["workspace_id"]),+ "canceledScanId": scan["id"],+ }if scan["status"] != "running":raise SystemExit("Only a running scan can be canceled.")updated = connection.execute(@@ -1324,7 +1327,7 @@ def cancel_scan_locked(db: Any, connection: Any, args: Any) -> dict[str, Any]:if progress_updated.rowcount != 1:raise SystemExit("Codex Security scan progress not found.")preserve_stopped_results_after_transition(db, connection, scan["id"])- return db.workspace_state(connection, scan["workspace_id"])+ return {**db.workspace_state(connection, scan["workspace_id"]), "canceledScanId": scan["id"]}def preserve_stopped_results_after_transition(db: Any, connection: Any, scan_id: str) -> None:diff --git a/plugins/codex-security/scripts/workbench_scan_history.py b/plugins/codex-security/scripts/workbench_scan_history.pyindex b0f017e1a..2c1de0a5e 100644--- a/plugins/codex-security/scripts/workbench_scan_history.py+++ b/plugins/codex-security/scripts/workbench_scan_history.py@@ -72,6 +72,7 @@ def cli_scan_resume(scan: sqlite3.Row,workspace: sqlite3.Row,) -> dict[str, Any]:+ scan = scan_with_progress(connection, scan["id"])if scan["mode"] != "deep" or scan["recipe_json"] is None:raise SystemExit("Resume requires a Deep Scan with a saved CLI launch recipe.")if scan["status"] != "running" or scan["canceled_at"] is not None:@@ -109,15 +110,13 @@ def cli_scan_resume(raise SystemExit("Cannot resume: the original checkout revision or contents changed.")recipe = wb.parse_scan_recipe(scan["recipe_json"], repository)scan_dir = wb.require_canonical_scan_directory(Path(scan["scan_dir"]))- progress = connection.execute(- "SELECT scope_file_count FROM scan_progress WHERE scan_id = ?", (scan["id"],)- ).fetchone()result = {"contract": wb.scan_contract(scan),+ "lifecycle": json.loads(scan["lifecycle_json"]),"recipe": recipe,"scanDir": str(scan_dir),"scanId": scan["id"],- "scopeFileCount": progress["scope_file_count"],+ "scopeFileCount": scan["scope_file_count"],"startedAt": scan["started_at"],"targetId": scan["target_id"],"targetRevision": scan["target_revision"],@@ -268,6 +267,7 @@ def _repository_origin(remote: str | None) -> tuple[str, str] | None:SCAN_SUMMARY_COLUMNS = """scans.*,+ lifecycle.snapshot AS lifecycle_json,progress.reportable_findings_count,progress.scope_file_count,progress.review_items_completed,@@ -283,15 +283,35 @@ SCAN_SUMMARY_QUERY = f"""SELECT {SCAN_SUMMARY_COLUMNS}FROM scansJOIN scan_progress AS progress ON progress.scan_id = scans.id+JOIN scan_lifecycles AS lifecycle ON lifecycle.scan_id = scans.id"""+def scan_with_progress(connection: sqlite3.Connection, scan_id: str) -> sqlite3.Row:+ return connection.execute(+ """+ SELECT scans.*, lifecycle.snapshot AS lifecycle_json, progress.updated_at AS progress_updated_at,+ progress.scope_file_count, progress.reportable_findings_count,+ progress.review_items_total, progress.review_items_completed, progress.deep_review_pass,+ progress.phase_items_total, progress.phase_items_completed, progress.phase_progress_unit,+ progress.preflight_checks_total, progress.preflight_checks_completed,+ progress.preflight_issues_json+ FROM scans+ JOIN scan_progress AS progress ON progress.scan_id = scans.id+ JOIN scan_lifecycles AS lifecycle ON lifecycle.scan_id = scans.id+ WHERE scans.id = ?+ """,+ (scan_id,),+ ).fetchone()++def scan_summary(row: sqlite3.Row) -> dict[str, Any]:return {"completedAt": row["completed_at"],"continuationThreadId": row["continuation_thread_id"],**stored_scan_cost_fields(row["cost_json"]),"findingCount": row["finding_count"],+ "lifecycle": json.loads(row["lifecycle_json"]),"handoffStatus": row["handoff_status"],"mode": row["mode"],"model": row["model"],diff --git a/plugins/codex-security/scripts/workbench_scan_start.py b/plugins/codex-security/scripts/workbench_scan_start.pyindex 6b5a4df88..96460f18f 100644--- a/plugins/codex-security/scripts/workbench_scan_start.py+++ b/plugins/codex-security/scripts/workbench_scan_start.py@@ -26,7 +26,7 @@ from workbench_target import (git_revision,worktree_content_digest,)-from workbench_validation import optional_text+from workbench_validation import optional_text, read_json_objectdef safe_segment(value: str) -> str:@@ -40,6 +40,16 @@ def compact_timestamp() -> str:return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")+def loaded_plugin_version() -> str:+ manifest = read_json_object(+ Path(__file__).resolve().parents[1] / ".codex-plugin" / "plugin.json"+ )+ version = manifest.get("version")+ if not isinstance(version, str) or not version:+ raise SystemExit("plugin.json: expected a nonempty Codex Security plugin version.")+ return version++def scan_target_identity(target: Path,diff_target: dict[str, str] | None,@@ -239,10 +249,18 @@ def insert_running_scan(model: str | None = None,reasoning_effort: str | None = None,scan_dir: Path | None = None,+ surface: str | None = "plugin",+ package_version: str | None = None,+ launch_kind: str = "scan",) -> str:revision = target_identity[0]native_scan = scan_dir is Noneuser_context = optional_text(workspace["user_context"])+ try:+ plugin_version = loaded_plugin_version()+ except SystemExit:+ # Missing version attribution must not prevent scan registration.+ plugin_version = Noneif scan_dir is None:scan_dir = Path(tempfile.mkdtemp(@@ -257,9 +275,10 @@ def insert_running_scan(target_device, target_inode, source_scopes_json, scope, mode, user_context,deep_scan_owner_thread_id, diff_target_kind, diff_base_revision,diff_head_revision, diff_content_digest, target_summary, scan_dir, model,- reasoning_effort, status, phase, handoff_status, started_at, created_at, updated_at+ reasoning_effort, status, phase, handoff_status, started_at, created_at, updated_at,+ launch_surface, launch_package_version, launch_plugin_version, launch_kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,- 'running', 'preflight', ?, ?, ?, ?)+ 'running', 'preflight', ?, ?, ?, ?, ?, ?, ?, ?)""",(scan_id,@@ -281,6 +300,10 @@ def insert_running_scan(timestamp,timestamp,timestamp,+ surface,+ package_version,+ plugin_version,+ launch_kind,),)connection.execute(diff --git a/plugins/codex-security/scripts/workbench_schema.py b/plugins/codex-security/scripts/workbench_schema.pyindex f9c23f350..526fb38f5 100644--- a/plugins/codex-security/scripts/workbench_schema.py+++ b/plugins/codex-security/scripts/workbench_schema.py@@ -75,7 +75,7 @@ def apply_migrations(elif version == 16:should_backfill_targets = repair_stable_targets_migration(connection)elif version in applied:- if version in (2, 12, 13, 26, 28, 31, 32, 42, 47, 50, 54, 55, 58, 59, 60):+ if version in (2, 12, 13, 26, 28, 31, 32, 42, 47, 50, 54, 55, 58, 59, 60, 61):repair_additive_migration(connection, version)elif version == 11:repair_deep_scan_migration(connection)diff --git a/plugins/codex-security/scripts/workbench_validation.py b/plugins/codex-security/scripts/workbench_validation.pyindex 124269d34..cc9f51cf5 100644--- a/plugins/codex-security/scripts/workbench_validation.py+++ b/plugins/codex-security/scripts/workbench_validation.py@@ -26,6 +26,19 @@ from workbench_scan_usage import _timestamp as usage_timestampreject_non_finite_json = finalizer._reject_non_finite_json+def read_json_object(path: Path) -> dict[str, Any]:+ try:+ payload = json.loads(+ path.read_text(encoding="utf-8"),+ parse_constant=reject_non_finite_json,+ )+ except (OSError, ValueError) as exc:+ raise SystemExit(f"{path.name}: invalid JSON: {exc}") from exc+ if not isinstance(payload, dict):+ raise SystemExit(f"{path.name}: expected a JSON object.")+ return payload++def javascript_utf8(value: str) -> bytes:"""Match Node's UTF-8 encoding of UTF-16 strings without changing stored text."""return (diff --git a/plugins/codex-security/shared/workbench-migrations.json b/plugins/codex-security/shared/workbench-migrations.jsonindex db4ca7672..3ad24c4fb 100644--- a/plugins/codex-security/shared/workbench-migrations.json+++ b/plugins/codex-security/shared/workbench-migrations.json@@ -488,5 +488,25 @@"statements": ["ALTER TABLE scan_severity_classifications ADD COLUMN rubric_binding_json TEXT;"]+ },+ {+ "version": 61,+ "name": "record scan launch attribution",+ "statements": [+ "ALTER TABLE scans ADD COLUMN launch_surface TEXT;",+ "ALTER TABLE scans ADD COLUMN launch_package_version TEXT;",+ "ALTER TABLE scans ADD COLUMN launch_plugin_version TEXT;",+ "ALTER TABLE scans ADD COLUMN launch_kind TEXT CHECK (launch_kind IN ('scan', 'mock', 'import'));"+ ]+ },+ {+ "version": 62,+ "name": "project scan lifecycle snapshots",+ "statements": [+ "CREATE TRIGGER classify_legacy_scan_recipe\nAFTER UPDATE OF recipe_json ON scans\nWHEN OLD.recipe_json IS NULL AND (NEW.launch_kind IS NULL OR NEW.launch_plugin_version IS NULL)\n AND json_valid(NEW.recipe_json)\nBEGIN\n UPDATE scans SET\n launch_kind = COALESCE(launch_kind, CASE\n WHEN json_type(recipe_json, '$.import') = 'object' THEN 'import'\n WHEN json_type(recipe_json, '$.mock') = 'true' THEN 'mock' END),\n launch_plugin_version = COALESCE(launch_plugin_version, CASE\n WHEN json_type(recipe_json, '$.pluginVersion') = 'text'\n AND trim(json_extract(recipe_json, '$.pluginVersion'), char(9, 10, 11, 12, 13, 32)) <> ''\n THEN json_extract(recipe_json, '$.pluginVersion') END)\n WHERE id = NEW.id;\nEND;",+ "UPDATE scans\nSET launch_kind = CASE WHEN json_type(recipe_json, '$.import') = 'object' THEN 'import' ELSE 'mock' END\nWHERE launch_kind IS NULL AND CASE WHEN json_valid(recipe_json) THEN\n json_type(recipe_json, '$.import') = 'object' OR json_type(recipe_json, '$.mock') = 'true'\nEND;",+ "UPDATE scans SET launch_plugin_version = json_extract(recipe_json, '$.pluginVersion')\nWHERE launch_plugin_version IS NULL AND CASE WHEN json_valid(recipe_json) THEN\n json_type(recipe_json, '$.pluginVersion') = 'text'\n AND trim(json_extract(recipe_json, '$.pluginVersion'), char(9, 10, 11, 12, 13, 32)) <> ''\nEND;",+ "CREATE VIEW scan_lifecycles AS\nSELECT scans.id AS scan_id, json_object(\n 'scanId', scans.id,\n 'mode', CASE WHEN launch_kind = 'import' THEN 'import' ELSE scans.mode END,\n 'startedAt', scans.started_at,\n 'status', CASE WHEN canceled_at IS NOT NULL THEN 'canceled'\n WHEN scans.status = 'complete' THEN 'completed' ELSE scans.status END,\n 'finishedAt', COALESCE(canceled_at, completed_at),\n 'hasReportableFindings', json(CASE\n WHEN scans.status = 'complete' AND canceled_at IS NULL\n THEN (SELECT CASE WHEN reportable_findings_count > 0 THEN 'true' ELSE 'false' END\n FROM scan_progress WHERE scan_id = scans.id) END),\n 'surface', launch_surface,\n 'packageVersion', launch_package_version,\n 'pluginVersion', launch_plugin_version,\n 'mock', json(CASE WHEN launch_kind = 'mock' THEN 'true'\n WHEN launch_kind IS NOT NULL THEN 'false' END)\n) AS snapshot\nFROM scans;"+ ]}]diff --git a/plugins/codex-security/tests/test_workbench_cancellation.py b/plugins/codex-security/tests/test_workbench_cancellation.pyindex 0e3cd2090..e0d74a4e5 100644--- a/plugins/codex-security/tests/test_workbench_cancellation.py+++ b/plugins/codex-security/tests/test_workbench_cancellation.py@@ -1,14 +1,18 @@from __future__ import annotations+import argparseimport uuid+from contextlib import closingfrom pathlib import Path+import pytestfrom workbench_test_support import (cancel_scan,create_saved_workspace,empty_target_paths,fail_scan,get_scan,+ load_script,mark_handoff_delivered,scan_claim_command,scan_command,@@ -18,6 +22,97 @@ from workbench_test_support import ()+def test_get_scan_returns_consistent_progress_when_canceled_during_read(tmp_path, monkeypatch):+ workbench = load_script("workbench_db")+ state_dir, target = empty_target_paths(tmp_path)+ thread_id = "thread-cancel-owner"+ workspace = create_saved_workspace(state_dir, target, thread_id=thread_id)+ scan_id = start_scan_command(state_dir, workspace["id"])["results"]["scanId"]+ monkeypatch.setenv("CODEX_SECURITY_STATE_DIR", str(state_dir))+ backfill = workbench.backfill_legacy_finding_details++ def cancel_after_backfill(connection, scan):+ backfill(connection, scan)+ cancel_scan(state_dir, scan_id, thread_id)++ monkeypatch.setattr(workbench, "backfill_legacy_finding_details", cancel_after_backfill)+ with closing(workbench.connect(deferred=True)) as connection:+ result = workbench.get_scan(+ connection, argparse.Namespace(scan_id=scan_id, occurrence_id=None)+ )+ scan = result["scan"]+ assert scan["progress"]["status"] == scan["lifecycle"]["status"] == "canceled"+ assert scan["canceledAt"] == scan["lifecycle"]["finishedAt"]+ assert scan["canceledAt"] is not None++[email protected]("rejoin", [False, True])+def test_start_scan_returns_selected_scan_when_replaced_before_response(+ tmp_path, monkeypatch, rejoin+):+ workbench = load_script("workbench_db")+ state_dir, target = empty_target_paths(tmp_path)+ thread_id = "thread-cancel-owner"+ workspace_id = create_saved_workspace(state_dir, target, thread_id=thread_id)["id"]+ if rejoin:+ start_scan_command(state_dir, workspace_id)+ monkeypatch.setenv("CODEX_SECURITY_STATE_DIR", str(state_dir))+ workspace_state = workbench.workspace_state+ replaced_id = None++ def replace_then_read(connection, workspace_id, **selection):+ nonlocal replaced_id+ replaced_id = workbench.require_workspace(connection, workspace_id)["active_scan_id"]+ cancel_scan(state_dir, replaced_id, thread_id)+ replacement = start_scan_command(state_dir, workspace_id)+ assert replacement["results"]["scanId"] != replaced_id+ return workspace_state(connection, workspace_id, **selection)++ monkeypatch.setattr(workbench, "workspace_state", replace_then_read)+ args = argparse.Namespace(+ workspace_id=workspace_id, scan_root=None, model=None, reasoning_effort=None+ )+ with closing(workbench.connect()) as connection:+ result = workbench.start_scan(connection, args)+ assert result["results"]["scanId"] == replaced_id+ assert result["results"]["progress"]["status"] == "canceled"+++def test_cancellation_identifies_committed_scan_when_workspace_has_replacement(+ tmp_path, monkeypatch+):+ workbench = load_script("workbench_db")+ state_dir, target = empty_target_paths(tmp_path)+ thread_id = "thread-cancel-owner"+ workspace_id = create_saved_workspace(state_dir, target, thread_id=thread_id)["id"]+ scan_id = start_scan_command(state_dir, workspace_id)["results"]["scanId"]+ monkeypatch.setenv("CODEX_SECURITY_STATE_DIR", str(state_dir))+ preserve = workbench.saved_results.preserve_stopped_results_after_transition+ replacement_id = None++ def start_replacement(db, connection, canceled_id):+ nonlocal replacement_id+ assert canceled_id == scan_id+ replacement_id = start_scan_command(state_dir, workspace_id)["results"]["scanId"]+ preserve(db, connection, canceled_id)++ monkeypatch.setattr(+ workbench.saved_results, "preserve_stopped_results_after_transition", start_replacement+ )+ with closing(workbench.connect()) as connection:+ canceled = workbench.saved_results.cancel_scan(+ workbench._WORKBENCH_DB_CONTEXT,+ connection,+ argparse.Namespace(scan_id=scan_id, thread_id=thread_id),+ )+ replay = cancel_scan(state_dir, scan_id, thread_id)+ assert replacement_id and replacement_id != scan_id+ for response in (canceled, replay):+ assert response["canceledScanId"] == scan_id+ assert response["results"]["scanId"] == replacement_id+ assert response["results"]["progress"]["status"] == "running"++def test_workbench_records_scan_failure(tmp_path: Path) -> None:state_dir, target = empty_target_paths(tmp_path)saved = create_saved_workspace(state_dir, target)@@ -77,6 +172,10 @@ def test_workbench_cancels_running_scan_and_rejects_late_updates(tmp_path: Path)assert restarted_scan_id != scan_idassert restarted["progress"]["status"] == "running"previous_scan = get_scan(state_dir, scan_id)+ lifecycle = previous_scan["scan"]["lifecycle"]+ assert lifecycle["status"] == "canceled"+ assert lifecycle["finishedAt"] == canceled["results"]["canceledAt"]+ assert lifecycle["hasReportableFindings"] is Noneassert previous_scan["scan"]["scanId"] == scan_idassert previous_scan["workspace"]["results"]["scanId"] == scan_idassert previous_scan["workspace"]["results"]["progress"]["status"] == "canceled"diff --git a/plugins/codex-security/tests/test_workbench_deep_scan.py b/plugins/codex-security/tests/test_workbench_deep_scan.pyindex 90924ddd5..bfd7642e1 100644--- a/plugins/codex-security/tests/test_workbench_deep_scan.py+++ b/plugins/codex-security/tests/test_workbench_deep_scan.py@@ -97,6 +97,12 @@ def start_empty_target_scan(tmp_path: Path, *, config: str | None = None) -> Deedef restore_v53_schema(state_dir: Path) -> None:with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:+ connection.execute("DROP TRIGGER classify_legacy_scan_recipe")+ connection.execute("DROP VIEW scan_lifecycles")+ connection.execute("ALTER TABLE scans DROP COLUMN launch_kind")+ connection.execute("ALTER TABLE scans DROP COLUMN launch_plugin_version")+ connection.execute("ALTER TABLE scans DROP COLUMN launch_package_version")+ connection.execute("ALTER TABLE scans DROP COLUMN launch_surface")connection.execute("ALTER TABLE scan_severity_classifications DROP COLUMN rubric_binding_json")@@ -588,6 +594,8 @@ def test_paused_discovery_resumes_after_restart_with_original_handoff_claim(handoff_claim_token,environment=deep_environment(codex_home),)["scan"]+ assert parent["lifecycle"] == paused["lifecycle"]+ assert parent["lifecycle"]["scanId"] == scan_idassert (parent["progress"]["status"],parent["progress"]["phase"],diff --git a/plugins/codex-security/tests/test_workbench_prompt_only_scan.py b/plugins/codex-security/tests/test_workbench_prompt_only_scan.pyindex dabe327e3..2f2eca21a 100644--- a/plugins/codex-security/tests/test_workbench_prompt_only_scan.py+++ b/plugins/codex-security/tests/test_workbench_prompt_only_scan.py@@ -144,6 +144,10 @@ def test_headless_standard_scan_joins_only_the_owning_thread(tmp_path: Path) ->assert first["startDisposition"] == "created"assert Path(first["scan"]["scanDir"]).parent == scan_root / target.nameassert joined["startDisposition"] == "joined"+ assert first["scan"]["lifecycle"]["surface"] == "plugin"+ assert first["scan"]["lifecycle"]["packageVersion"] is None+ assert first["scan"]["lifecycle"]["mock"] is False+ assert joined["scan"]["lifecycle"] == first["scan"]["lifecycle"]assert joined["scan"]["scanId"] == first["scan"]["scanId"]assert joined["scan"]["handoffClaimToken"] == first["scan"]["handoffClaimToken"]assert other["startDisposition"] == "created"diff --git a/plugins/codex-security/tests/test_workbench_scan_history.py b/plugins/codex-security/tests/test_workbench_scan_history.pyindex 524d00eaa..9966e6ddf 100644--- a/plugins/codex-security/tests/test_workbench_scan_history.py+++ b/plugins/codex-security/tests/test_workbench_scan_history.py@@ -27,6 +27,7 @@ from workbench_test_support import (run_workbench,scan_command,set_triage,+ source_plugin_version,stable_target_id,write_completed_contract,)@@ -189,6 +190,7 @@ def create_cli_scan(cost: dict[str, Any] | None = None,target: dict[str, Any] | None = None,target_revision: str | None = None,+ surface: str = "cli",) -> dict[str, Any]:scan_dir = root / str(uuid.uuid4())scan_dir.mkdir(mode=0o700, parents=True)@@ -204,12 +206,15 @@ def create_cli_scan(str(scan_dir),"--repository",str(repository),- "--recipe-json",- json.dumps(recipe),+ "--registration-json-stdin",]if parent_scan_id is not None:arguments.extend(("--parent-scan-id", parent_scan_id))- launched = run_workbench(state_dir, *arguments)+ launched = run_workbench(+ state_dir,+ *arguments,+ input_text=json.dumps({"recipe": recipe, "surface": surface, "packageVersion": "1.2.3"}),+ )if not complete:return launchedif mode == "deep":@@ -379,13 +384,14 @@ def test_cli_scan_lifecycle_persists_recipes_lineage_and_filtered_history(tmp_pa(repository / "src").mkdir(parents=True)(repository / "tests").mkdir()root = tmp_path / "results"- first = create_cli_scan(state_dir, root, repository)+ first = create_cli_scan(state_dir, root, repository, surface="sdk")rerun = create_cli_scan(state_dir,root,repository,parent_scan_id=first["scanId"],paths=["src", "tests"],+ finding=False,)failed = create_cli_scan(state_dir, root, repository, complete=False)fail_scan(state_dir, failed["scanId"], "interrupted")@@ -400,6 +406,12 @@ def test_cli_scan_lifecycle_persists_recipes_lineage_and_filtered_history(tmp_paassert connection.execute("SELECT parent_scan_id FROM scans WHERE id = ?", (rerun["scanId"],)).fetchone() == (first["scanId"],)+ snapshots = {+ scan_id: json.loads(snapshot)+ for scan_id, snapshot in connection.execute(+ "SELECT scan_id, snapshot FROM scan_lifecycles"+ )+ }assert scan_command(state_dir, "get-scan-recipe", first["scanId"])["recipe"]["config"] == {"model": "gpt-5.6-sol","model_reasoning_effort": "high",@@ -416,6 +428,37 @@ def test_cli_scan_lifecycle_persists_recipes_lineage_and_filtered_history(tmp_parerun["scanId"],failed["scanId"],}+ by_id = {row["scanId"]: row for row in history["scans"]}+ for launch, surface, status, has_findings in (+ (first, "sdk", "completed", True),+ (rerun, "cli", "completed", False),+ (failed, "cli", "failed", None),+ ):+ row = by_id[launch["scanId"]]+ assert launch["lifecycle"] == {+ "scanId": launch["scanId"],+ "startedAt": row["startedAt"],+ "mode": "standard",+ "status": "running",+ "finishedAt": None,+ "hasReportableFindings": None,+ "surface": surface,+ "packageVersion": "1.2.3",+ "pluginVersion": source_plugin_version(),+ "mock": False,+ }+ assert row["completedAt"]+ assert row["lifecycle"] == {+ **launch["lifecycle"],+ "status": status,+ "finishedAt": row["completedAt"],+ "hasReportableFindings": has_findings,+ }+ snapshot = snapshots[launch["scanId"]]+ assert snapshot == row["lifecycle"]+ assert snapshot["hasReportableFindings"] is has_findings+ assert snapshot["mock"] is False+ assert detail["scan"]["lifecycle"] == by_id[rerun["scanId"]]["lifecycle"]assert any(scan["progress"]["status"] == "failed" for scan in history["scans"])assert all(scan["recipeAvailable"] for scan in history["scans"])assert len(run_workbench(state_dir, "list-scans", "--repository", str(other))["scans"]) == 1diff --git a/plugins/codex-security/tests/test_workbench_setup_and_migrations.py b/plugins/codex-security/tests/test_workbench_setup_and_migrations.pyindex 55f44834f..162258b23 100644--- a/plugins/codex-security/tests/test_workbench_setup_and_migrations.py+++ b/plugins/codex-security/tests/test_workbench_setup_and_migrations.py@@ -103,6 +103,8 @@ EXPECTED_MIGRATIONS = [(58, "record the final Deep Scan reviewed surface count"),(59, "retain the launching Deep Scan service tier"),(60, "record classification rubric provenance"),+ (61, "record scan launch attribution"),+ (62, "project scan lifecycle snapshots"),]@@ -1103,23 +1105,93 @@ def test_workbench_backfills_repository_targets_only_during_migration() -> None:backfill.assert_called_once_with(connection)-def test_scan_model_migration_preserves_existing_scans() -> None:[email protected]("complete", [False, True])+def test_scan_model_migration_preserves_existing_scans(complete: bool) -> None:connection, apply_migrations = create_historical_database(25)timestamp = "2026-07-01T00:00:00Z"insert_historical_row(connection, "workspaces", timestamp, id="legacy-workspace")- insert_legacy_scan(connection, timestamp)+ status = "complete" if complete else "running"+ finished_at = "2026-07-01T01:00:00Z" if complete else None+ insert_legacy_scan(connection, timestamp, status=status, completed_at=finished_at)connection.commit()apply_migrations(connection)- scan = connection.execute(- "SELECT status, model, reasoning_effort, completion_warnings_json FROM scans WHERE id = ?",- ("legacy-scan",),- ).fetchone()- assert scan["status"] == "running"+ scan = connection.execute("SELECT * FROM scans WHERE id = ?", ("legacy-scan",)).fetchone()+ assert scan["status"] == statusassert scan["model"] is Noneassert scan["reasoning_effort"] is Noneassert scan["completion_warnings_json"] == "[]"+ assert scan["launch_surface"] is None+ assert scan["launch_package_version"] is None+ assert scan["launch_plugin_version"] is None+ assert scan["launch_kind"] is None+ (snapshot,) = connection.execute(+ "SELECT snapshot FROM scan_lifecycles WHERE scan_id = ?", ("legacy-scan",)+ ).fetchone()+ assert json.loads(snapshot) == {+ "scanId": "legacy-scan",+ "mode": "standard",+ "startedAt": timestamp,+ "status": "completed" if complete else "running",+ "finishedAt": finished_at,+ "hasReportableFindings": None,+ "surface": None,+ "packageVersion": None,+ "pluginVersion": None,+ "mock": None,+ }+++ ("recipe", "kind", "mode", "is_mock", "plugin_version", "registered_version"),+ (+ ('{"mock":true,"pluginVersion":"0.4.0"}', "mock", "standard", True, "0.4.0", None),+ ('{"import":{},"pluginVersion":"0.5.0"}', "import", "import", False, "0.5.0", None),+ ('{"mode":"standard","pluginVersion":"0.6.0"}', None, "standard", None, "0.6.0", None),+ ('{"pluginVersion":"0.6.0"}', None, "standard", None, "0.7.0", "0.7.0"),+ ('{"pluginVersion":" "}', None, "standard", None, None, None),+ ('{"pluginVersion":42}', None, "standard", None, None, None),+ ('{"mode":"standard"}', None, "standard", None, None, None),+ ('{"pluginVersion":', None, "standard", None, None, None),+ ),+)+ "write_after_upgrade", [False, True], ids=["before-upgrade", "after-upgrade"]+)+def test_scan_lifecycle_migration_recognizes_saved_recipes(+ recipe: str,+ kind: str | None,+ mode: str,+ is_mock: bool | None,+ plugin_version: str | None,+ registered_version: str | None,+ write_after_upgrade: bool,+) -> None:+ connection, apply_migrations = create_historical_database(62 if registered_version else 61)+ if write_after_upgrade:+ apply_migrations(connection)++ timestamp = "2026-07-01T00:00:00Z"+ with connection:+ insert_historical_row(connection, "workspaces", timestamp, id="legacy-workspace")+ attribution = {"launch_plugin_version": registered_version} if registered_version else {}+ insert_legacy_scan(connection, timestamp, **attribution)+ connection.execute("UPDATE scans SET recipe_json = ? WHERE id = ?", (recipe, "legacy-scan"))++ if not write_after_upgrade:+ apply_migrations(connection)++ stored_kind, snapshot = connection.execute(+ "SELECT launch_kind, snapshot FROM scans JOIN scan_lifecycles ON scan_id = id"+ ).fetchone()+ assert stored_kind == kind+ lifecycle = json.loads(snapshot)+ assert lifecycle["mode"] == mode+ assert lifecycle["mock"] is is_mock+ assert lifecycle["surface"] is None+ assert lifecycle["packageVersion"] is None+ assert lifecycle["pluginVersion"] == plugin_version@pytest.mark.parametrize(@@ -2034,6 +2106,10 @@ def test_workbench_repairs_shadowed_scan_recipe_migration(tmp_path: Path) -> Nonstate_dir, workspace_id, scan_id, database = start_migration_scan(tmp_path)with sqlite3.connect(database) as connection:+ # Recreate the historical schema before removing its recipe column.+ connection.execute("DROP TRIGGER classify_legacy_scan_recipe")+ connection.execute("DROP VIEW scan_lifecycles")+ connection.execute("DELETE FROM schema_migrations WHERE version = 62")connection.execute("ALTER TABLE scans DROP COLUMN parent_scan_id")connection.execute("ALTER TABLE scans DROP COLUMN recipe_json")rename_migration(connection, 22, "dynamic scan execution profiles")diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 79af5fefc..c61dda1a6 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -401,6 +401,30 @@ Deep discovery retains its enforced deadline, with a default and maximum of### Progress and cost+Use `onLifecycle` to observe the saved state of a top-level scan in your own+application:++```ts+await security.run(repository, {+ onLifecycle(scan) {+ console.log(scan.scanId, scan.status, scan.hasReportableFindings);+ },+});+```++Group observations by `scanId`. A completed scan with+`hasReportableFindings: false` finished with zero reportable findings.+The field is `null` until that outcome is known. Saved scan history retains+the lifecycle snapshot after the originating process exits. The snapshot+includes the launch surface, package and plugin versions when available,+and whether the scan used a mock. Offline imports appear in history with+lifecycle mode `import`. Exclude imports and mock scans when counting executed+scans. For older records, saved recipes identify known imports, mock scans,+and the plugin version used at launch. Missing fields stay unknown.++If `run()` rejects before you receive a registration, record the error separately+from saved scan outcomes. The caller may have missed the registration receipt.+Use `onProgress` for scan progress and `onCost` for cost updates.Use `onUsageObservation` for the last reported token measurement time(`tokensUpdatedAt`) and account-wide allowance readings (`accountRateLimits`).diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.mdindex b3130b583..fe906aff5 100644--- a/sdk/typescript/docs/cli.md+++ b/sdk/typescript/docs/cli.md@@ -977,6 +977,15 @@ The setting does not control configured OpenTelemetry exporters, integrations,authentication, or CLI update checks. Validation uses isolated configuration;patching and verification preserve ambient project trust.+For scan outcomes, the workbench saves a separate, local `lifecycle` record+with the scan ID, launch surface, available release versions, mode, timestamps,+and committed status. A completed scan indicates whether it produced reportable+findings. Use `codex-security scans list --json` for the current repository.+To find an offline import, use `codex-security scans list --scan-root <DIR> --json`+with its output directory. Imported scans have lifecycle mode `import`. The SDK+exposes `onLifecycle`, and the CLI includes observations in verbose diagnostics.+Applications can choose how to collect and export these observations.+For filesystem and approval behavior, see the[local security model](../README.md#local-security-model).diff --git a/sdk/typescript/src/api.ts b/sdk/typescript/src/api.tsindex d4716eb6c..d3c503a59 100644--- a/sdk/typescript/src/api.ts+++ b/sdk/typescript/src/api.ts@@ -230,7 +230,13 @@ import {} from "./worker-progress.js";import { CODEX_SECURITY_THREAD_SOURCES } from "./thread-source.js";import { codexSecurityRequestContext } from "./request-metadata.js";-import { CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION } from "./version.js";+import {+ CODEX_EXECUTABLE_VERSION,+ CODEX_SDK_VERSION,+ VERSION,+} from "./version.js";+import { SCAN_MODES } from "./scan-modes.js";+import { readSavedScanLifecycle } from "./saved-scan-bootstrap.js";import { bundledCodexSdkEnvironment } from "./codex-sdk-environment.js";import {canonicalConfigPath,@@ -349,6 +355,21 @@ interface PreparedSession {const DEEP_SCAN_CONFIG_PATH_ENVIRONMENT ="CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH";+const scanLifecycleSchema = z.object({+ scanId: z.string(),+ mode: z.enum([...SCAN_MODES, "diff", "import"]),+ startedAt: z.string(),+ status: z.enum(["running", "completed", "failed", "canceled"]),+ finishedAt: z.string().nullable(),+ hasReportableFindings: z.boolean().nullable(),+ surface: z.enum(["plugin", "cli", "sdk"]).nullable(),+ packageVersion: z.string().nullable(),+ pluginVersion: z.string().nullable(),+ mock: z.boolean().nullable(),+});++export type ScanLifecycle = Readonly<z.infer<typeof scanLifecycleSchema>>;+export interface ScanOptions extends ScanSettings {/** Explicit policy for the initial scan and its workers. */severityRubric?: SeverityRubricSnapshot;@@ -377,6 +398,9 @@ export interface ScanOptions extends ScanSettings {) => number | undefined | Promise<number | undefined>;onOutputArchived?: (archiveDir: string) => void;onOutputDirReady?: (scanDir: string) => void;+ /** Best-effort snapshots at fresh registration and observed terminal state.+ * Resume preserves the scan ID and only reports a terminal outcome. */+ onLifecycle?: (scan: ScanLifecycle) => void;/** @internal Authoritative registration receipt for CLI scan navigation. */onScanRegistered?: (scan: {scanId: string;@@ -624,6 +648,7 @@ type ScanObserverName =| "onOutputArchived"| "onOutputDirReady"| "onScanRegistered"+ | "onLifecycle"| "onScanStarted"| "onTrustedAccessStatus"| "onReconnect"@@ -840,6 +865,7 @@ export class CodexSecurity {let completed = state.stages.scan.status === "completed";if (!completed) {const { scan, recipe } = await workflow.registeredScan(state.scanId);+ notifyScanLifecycle(options, scan, true);completed =(scan["progress"] as JsonObject | undefined)?.["status"] ==="complete";@@ -2705,6 +2731,8 @@ export class CodexSecurity {}),JSON.stringify({recipe,+ surface: this.#surface,+ packageVersion: VERSION,userContext: options.scanPrompt,workflowId: options.workflowId,}),@@ -2868,6 +2896,8 @@ export class CodexSecurity {});}activeScan = { id: scanId, options: workbenchOptions };+ if (options.resumeScanId === undefined)+ notifyScanLifecycle(options, registration);notifyObserver(options,"onScanRegistered",@@ -3401,6 +3431,7 @@ export class CodexSecurity {]);activeScan = null;const completedScan = completion["scan"];+ notifyScanLifecycle(options, completedScan);await finalizeScanUsage(scanId,workbenchOptions,@@ -3670,6 +3701,7 @@ export class CodexSecurity {terminalTurnStatus,);activeScan = null;+ notifyScanLifecycle(options, completion["scan"]);runPostScan = null;const result = await collectResult({@@ -3730,6 +3762,7 @@ export class CodexSecurity {if (isRecord(progress) && progress["status"] === "complete") {const scanId = activeScan.id;activeScan = null;+ notifyScanLifecycle(options, completedScan);if (terminalTurnStatus !== null)await finalizeScanUsage(scanId,@@ -3761,15 +3794,20 @@ export class CodexSecurity {}).catch(() => undefined);}try {- await workbench({ ...activeScan.options, signal: undefined }, [- "fail-scan",- "--scan-id",- activeScan.id,- `--message=${errorMessage(failure)}`,- ...(snapshot?.cost- ? ["--cost-json", JSON.stringify(snapshot.cost)]- : []),- ]);+ const failed = await workbench(+ { ...activeScan.options, signal: undefined },+ [+ "fail-scan",+ "--scan-id",+ activeScan.id,+ `--message=${errorMessage(failure)}`,+ ...(snapshot?.cost+ ? ["--cost-json", JSON.stringify(snapshot.cost)]+ : []),+ ],+ );+ activeScan = null;+ notifyScanLifecycle(options, failed["scan"], true);} catch {}}if (runPostScan !== null && !signal.aborted) {@@ -3815,6 +3853,7 @@ export class CodexSecurity {} catch (error) {warnCleanupFailed(options, error);}+ observeSettledScan(options, activeScan);}}@@ -4754,6 +4793,8 @@ export class CodexSecurity {}),mock: true,},+ surface: this.#surface,+ packageVersion: VERSION,userContext: options.scanPrompt,workflowId: options.workflowId,}),@@ -4770,6 +4811,7 @@ export class CodexSecurity {);}activeScan = { id: scanId, options: workbenchOptions };+ notifyScanLifecycle(options, registration);notifyObserver(options,"onScanRegistered",@@ -4810,6 +4852,7 @@ export class CodexSecurity {]);activeScan = undefined;const completedScan = completion["scan"];+ notifyScanLifecycle(options, completedScan);if (isRecord(completedScan) && Array.isArray(completedScan["warnings"])) {for (const warning of completedScan["warnings"]) {if (typeof warning === "string")@@ -4854,18 +4897,26 @@ export class CodexSecurity {return result;} catch (error) {if (activeScan !== undefined) {- await workbench({ ...activeScan.options, signal: undefined }, [- "fail-scan",- "--scan-id",- activeScan.id,- `--message=${errorMessage(error)}`,- ]).catch(() => undefined);+ try {+ const failed = await workbench(+ { ...activeScan.options, signal: undefined },+ [+ "fail-scan",+ "--scan-id",+ activeScan.id,+ `--message=${errorMessage(error)}`,+ ],+ );+ activeScan = undefined;+ notifyScanLifecycle(options, failed["scan"], true);+ } catch {}}if (this.#closed) this.#requireOpen();throwIfAborted(signal, scanDir);throw error;} finally {await cleanupSdkDirectory(workspace);+ observeSettledScan(options, activeScan);}}@@ -6060,6 +6111,35 @@ export function selectedScanEnvironment(return selected;}+function notifyScanLifecycle(+ options: ScanOptions,+ saved: unknown,+ terminalOnly = false,+): void {+ if (!options.onLifecycle || !isRecord(saved)) return;+ const snapshot = scanLifecycleSchema.safeParse(saved["lifecycle"]);+ if (snapshot.success && !(terminalOnly && snapshot.data.status === "running"))+ notifyObserver(options, "onLifecycle")(snapshot.data);+}++function observeSettledScan(+ options: ScanOptions,+ activeScan:+ { id: string; options: WorkbenchCommandOptions } | null | undefined,+): void {+ if (!activeScan || !options.onLifecycle) return;+ // An interrupted workbench command can commit before its caller receives the result.+ try {+ const lifecycle = readSavedScanLifecycle(+ activeScan.options.environment,+ activeScan.id,+ );+ notifyScanLifecycle(options, { lifecycle }, true);+ } catch {+ // Preserve the original failure when its persisted outcome cannot be read.+ }+}+function notifyObserver<Name extends ScanObserverName>(options: Pick<ScanOptions & SecurityPolicyOptions, Name | "onObserverError">,observerName: Name,diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex ff181eaf2..8b027b31d 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -10117,6 +10117,21 @@ async function executeScan(registeredScan = scan;scanDir = scan.scanDir;},+ onLifecycle: verbose+ ? (scan) =>+ diagnostic("scan.lifecycle", {+ scan_id: scan.scanId,+ mode: scan.mode,+ status: scan.status,+ started_at: scan.startedAt,+ finished_at: scan.finishedAt,+ has_reportable_findings: scan.hasReportableFindings,+ surface: scan.surface,+ package_version: scan.packageVersion,+ plugin_version: scan.pluginVersion,+ mock: scan.mock,+ })+ : undefined,onOutputDirReady: (path) => {scanDir = path;diagnostic("scan.output_ready", { scan_dir: path });@@ -10528,9 +10543,14 @@ async function executeScan(}}+ const registration = {+ registration_observed: registeredScan !== undefined,+ scan_id: registeredScan?.scanId,+ };if (requestedSignal !== null) {diagnostic("scan.interrupted", {signal: requestedSignal,+ ...registration,});if (result !== null && arguments_.validate) {const exitCode = requestedSignal === "SIGINT" ? 130 : 143;@@ -10580,6 +10600,7 @@ async function executeScan(costLimitFailure === undefined? undefined: formatScanCost(costLimitFailure.cost),+ ...registration,});errorOutput.write(`${message}\n`);if (!(failure instanceof ScanInterruptedError) && scanDir !== null) {@@ -10632,6 +10653,7 @@ async function executeScan(diagnostic("scan.failed", {classification: "unknown",message: "Scan completed without a result.",+ ...registration,});errorOutput.write("scan completed without a result\n");printFailedScanReference(registeredScan, phase, arguments_, errorOutput);diff --git a/sdk/typescript/src/hosted-scan-protocol.ts b/sdk/typescript/src/hosted-scan-protocol.tsindex 1e33361a2..0c1862a3e 100644--- a/sdk/typescript/src/hosted-scan-protocol.ts+++ b/sdk/typescript/src/hosted-scan-protocol.ts@@ -3,7 +3,7 @@ import { runHostProtocol } from "./host-protocol.js";import {type HostedScanInput,HostedScanPreparationError,- runHostedScan,+ runHostedScanInternal,} from "./hosted-scan.js";import {ScanExecutionEventSchema,@@ -27,7 +27,7 @@ export async function runHostedScanProtocol(? { reason: error.reason }: undefined,run: async (params, execute, signal, onEvent) =>- await runHostedScan(params as HostedScanInput, {+ await runHostedScanInternal("cli", params as HostedScanInput, {signal,onEvent,executor: {diff --git a/sdk/typescript/src/hosted-scan.ts b/sdk/typescript/src/hosted-scan.tsindex 46e322cc9..4580dfe55 100644--- a/sdk/typescript/src/hosted-scan.ts+++ b/sdk/typescript/src/hosted-scan.ts@@ -18,7 +18,7 @@ export type { ScanExecutor, ScanExecutionRequest } from "./scan-executor.js";import { realpath } from "node:fs/promises";import { isAbsolute, relative, resolve, sep } from "node:path";import { z } from "zod";-import { CodexSecurity } from "./api.js";+import { CodexSecurity, type CodexSecuritySurface } from "./api.js";import { severityRubricSnapshotSchema } from "./classify-severity-records.js";import { ScanInterruptedError, errorMessage } from "./errors.js";import {@@ -199,7 +199,16 @@ export interface HostedScanOptions {}/** One invocation, with only scan-domain state. The host decides retry/reconciliation. */-export async function runHostedScan(+export function runHostedScan(+ value: HostedScanInput,+ options: HostedScanOptions,+) {+ return runHostedScanInternal("sdk", value, options);+}++/** @internal */+export async function runHostedScanInternal(+ surface: CodexSecuritySurface,value: HostedScanInput,options: HostedScanOptions,) {@@ -281,7 +290,7 @@ export async function runHostedScan(throw new Error("Local inference is unavailable in hosted mode.");},},- { surface: "sdk" },+ { surface },);try {const result = await client.run(context.repository, {diff --git a/sdk/typescript/src/import-scan.ts b/sdk/typescript/src/import-scan.tsindex 581d2635f..62aa5d1ba 100644--- a/sdk/typescript/src/import-scan.ts+++ b/sdk/typescript/src/import-scan.ts@@ -43,6 +43,7 @@ import {type ProcessEnvironment,type WorkbenchCommandOptions,} from "./runtime.js";+import { VERSION } from "./version.js";export interface ImportScanOptions {sourcePath: string;@@ -238,6 +239,8 @@ export async function importScan(parentScanId: options.parentScanId,}),JSON.stringify({+ surface: "cli",+ packageVersion: VERSION,recipe: {repository,target: { kind: "repository", paths: [] },diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.tsindex 5f1ea4c34..453d62d43 100644--- a/sdk/typescript/src/index.ts+++ b/sdk/typescript/src/index.ts@@ -112,6 +112,7 @@ export type {ScanAuthMode,ScanAuthentication,ScanBudget,+ ScanLifecycle,ScanOptions,ScanPreflight,ScanReconnectDetails,diff --git a/sdk/typescript/src/saved-scan-bootstrap.ts b/sdk/typescript/src/saved-scan-bootstrap.tsindex d013cf8a8..7b1492ee6 100644--- a/sdk/typescript/src/saved-scan-bootstrap.ts+++ b/sdk/typescript/src/saved-scan-bootstrap.ts@@ -167,12 +167,9 @@ export async function savedScanWorkbench(});}-async function readTargets(- requestedId: string | { workflowId: string },+function openSavedScanDatabase(environment: ProcessEnvironment,- currentDirectory: string,- signal?: AbortSignal,-): Promise<ScanTarget[]> {+): BootstrapDatabase {const require = createRequire(import.meta.url);const bun = process.versions["bun"] !== undefined;const Database = (@@ -186,20 +183,48 @@ async function readTargets(create?: boolean;},) => BootstrapDatabase;- let database: BootstrapDatabase | undefined;+ return new Database(+ join(codexSecurityStateDirectory(environment), "workbench.sqlite3"),+ // Apple's SQLite cannot initialize absent WAL sidecars through a read-only handle.+ // Open only an existing file there; query_only still prevents SQL data/schema writes.+ bun+ ? {+ readonly: process.platform !== "darwin",+ readwrite: process.platform === "darwin",+ create: false,+ }+ : { readOnly: true },+ );+}++export function readSavedScanLifecycle(+ environment: ProcessEnvironment,+ scanId: string,+): unknown {+ const database = openSavedScanDatabase(environment);try {- database = new Database(- join(codexSecurityStateDirectory(environment), "workbench.sqlite3"),- // Apple's SQLite cannot initialize absent WAL sidecars through a read-only handle.- // Open only an existing file there; query_only still prevents SQL data/schema writes.- bun- ? {- readonly: process.platform !== "darwin",- readwrite: process.platform === "darwin",- create: false,- }- : { readOnly: true },+ database.exec("PRAGMA busy_timeout = 0");+ database.exec("PRAGMA query_only = ON");+ const [row] = readRows<{ snapshot: string }>(+ database,+ "SELECT snapshot FROM scan_lifecycles WHERE scan_id = ?",+ scanId,);+ return row && JSON.parse(row.snapshot);+ } finally {+ database.close();+ }+}++async function readTargets(+ requestedId: string | { workflowId: string },+ environment: ProcessEnvironment,+ currentDirectory: string,+ signal?: AbortSignal,+): Promise<ScanTarget[]> {+ let database: BootstrapDatabase | undefined;+ try {+ database = openSavedScanDatabase(environment);database.exec("PRAGMA busy_timeout = 5000");database.exec("PRAGMA query_only = ON");if (typeof requestedId !== "string") {diff --git a/sdk/typescript/tests-ts/api-time-budget.test.ts b/sdk/typescript/tests-ts/api-time-budget.test.tsindex 440a64ea5..1dfe3d4fe 100644--- a/sdk/typescript/tests-ts/api-time-budget.test.ts+++ b/sdk/typescript/tests-ts/api-time-budget.test.ts@@ -25,6 +25,7 @@ test("rejects an unrepresentable deadline before scan setup", async () => {throw new Error("Unexpected model preparation");});const runWorkbench = mock(async () => ({}));+ const onLifecycle = mock();const now = mock(() => Date.UTC(2026, 0, 1));await using client = TestClient.withDependencies({prepareRuntime,@@ -35,12 +36,13 @@ test("rejects an unrepresentable deadline before scan setup", async () => {await expect(client.preflight(repository, { maxTimeMinutes }),).rejects.toThrow("deadline within the supported date range");- await expect(client.run(repository, { maxTimeMinutes })).rejects.toThrow(- "deadline within the supported date range",- );+ await expect(+ client.run(repository, { maxTimeMinutes, onLifecycle }),+ ).rejects.toThrow("deadline within the supported date range");expect(prepareRuntime).not.toHaveBeenCalled();expect(createCodex).not.toHaveBeenCalled();expect(runWorkbench).not.toHaveBeenCalled();+ expect(onLifecycle).not.toHaveBeenCalled();expect(now).not.toHaveBeenCalled();});diff --git a/sdk/typescript/tests-ts/api-workflow.test.ts b/sdk/typescript/tests-ts/api-workflow.test.tsindex 8ebffedf2..438cbf02e 100644--- a/sdk/typescript/tests-ts/api-workflow.test.ts+++ b/sdk/typescript/tests-ts/api-workflow.test.ts@@ -1,7 +1,8 @@import { mkdir, readFile, rm, writeFile } from "node:fs/promises";import { dirname, join } from "node:path";import { Database } from "bun:sqlite";-import { afterEach, expect, spyOn, test } from "bun:test";+import { afterEach, expect, mock, spyOn, test } from "bun:test";+import type { ScanOptions } from "../src/index.js";import { runWorkbench } from "../src/runtime.js";import * as runtime from "../src/runtime.js";import * as ownerArtifacts from "../src/scan-owner-suggestions.js";@@ -366,9 +367,83 @@ test.each([},});try {- const result = await client.run(repository, { workflowId: workflow.id });+ const onLifecycle = mock<NonNullable<ScanOptions["onLifecycle"]>>();+ const options = { workflowId: workflow.id, onLifecycle };+ const result = await client.run(repository, options);expect(result.cost).toEqual(expected);expect(result.toJSON()["cost"]).toEqual(expected);+ if (scenario === "lost receipt") {+ expect(onLifecycle).toHaveBeenCalledWith(+ expect.objectContaining({ scanId, status: "completed" }),+ );+ await client.run(repository, options);+ }+ expect(onLifecycle).toHaveBeenCalledTimes(+ scenario === "lost receipt" ? 1 : 0,+ );+ } finally {+ await client.close();+ }+ },+);++test.each(["failed", "canceled", "running"] as const)(+ "workflow recovery observes the previous %s scan before retry",+ async (status) => {+ const root = await temporaryDirectory();+ const repository = join(root, "repository");+ const scanDir = join(root, "scan");+ await mkdir(repository);+ await mkdir(scanDir, { mode: 0o700 });+ const environment = {+ PATH: process.env["PATH"],+ SystemRoot: process.env["SystemRoot"],+ CODEX_SECURITY_STATE_DIR: join(root, "state"),+ };+ const workbench = workbenchCommand(+ await runtime.resolvePluginPython({ environment }),+ () => environment,+ );+ const registration = await workbench(+ scanRegistrationArguments(repository, scanDir),+ );+ const scanId = registration["scanId"] as string;+ const workflow = new FindingWorkflow("retry-scan", environment);+ await workflow.bind({ repositoryPath: repository, scanId, scanDir });+ await workflow.begin("scan");+ if (status === "failed")+ await workbench([+ "fail-scan",+ "--scan-id",+ scanId,+ "--message",+ "Synthetic failure",+ ]);+ if (status === "canceled")+ await workbench(["cancel-scan", "--scan-id", scanId]);+ const onLifecycle = mock<NonNullable<ScanOptions["onLifecycle"]>>();+ const client = TestClient.withDependencies({+ environment,+ runWorkbench: async (options, args, input) => {+ if (+ args[0] === "finding-workflow" &&+ JSON.parse(input!).action === "begin"+ ) {+ expect(+ onLifecycle.mock.calls.map(([snapshot]) => [+ snapshot.scanId,+ snapshot.status,+ ]),+ ).toEqual(status === "running" ? [] : [[scanId, status]]);+ throw new Error("Synthetic stop before retry");+ }+ return runWorkbench(options, args, input);+ },+ });+ try {+ await expect(+ client.run(repository, { workflowId: workflow.id, onLifecycle }),+ ).rejects.toThrow("Synthetic stop before retry");} finally {await client.close();}diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.tsindex 42a242587..b9c57e705 100644--- a/sdk/typescript/tests-ts/api.test.ts+++ b/sdk/typescript/tests-ts/api.test.ts@@ -15970,6 +15970,25 @@ if __name__ == "__main__":const { root, repository, codexHome, scanDir } = await scanDirectories();const commands: Array<readonly string[]> = [];const warnings: string[] = [];+ const onLifecycle = mock<NonNullable<ScanOptions["onLifecycle"]>>();+ const registration = {+ scanId: "scan_example_001",+ mode: "deep",+ startedAt: "2026-01-01T00:00:00Z",+ status: "running",+ finishedAt: null,+ hasReportableFindings: null,+ surface: "sdk",+ packageVersion: VERSION,+ pluginVersion: "1.0.0",+ mock: false,+ };+ const terminal = {+ ...registration,+ status: completion === "completed" ? "completed" : "failed",+ finishedAt: "2026-01-01T00:01:00Z",+ hasReportableFindings: completion === "completed" ? true : null,+ };const runStreamed = mock(async (_input: string, options: { signal: AbortSignal }) => {async function* events(): AsyncGenerator<ThreadEvent> {@@ -15995,6 +16014,14 @@ if __name__ == "__main__":input?: string,): Promise<JsonObject> => {commands.push(args);+ if (args[0] === "register-cli-scan") {+ expect(JSON.parse(input!)).toMatchObject({+ surface: "sdk",+ packageVersion: VERSION,+ });+ return { ...mockWorkbench(args, input), lifecycle: registration };+ }+ if (args[0] === "fail-scan") return { scan: { lifecycle: terminal } };if (args[0] !== "complete-budget-exhausted-scan") {return mockWorkbench(args, input);}@@ -16035,6 +16062,7 @@ if __name__ == "__main__":},}: {}),+ lifecycle: terminal,warnings: [args.find((value) => value.startsWith("--message="))!@@ -16051,6 +16079,7 @@ if __name__ == "__main__":mode: "deep",maxCostUsd: 0.004,postScanPrompt: "Do not spend another model turn.",+ onLifecycle,onWarning: (warning) => warnings.push(warning),signal: AbortSignal.timeout(5_000),});@@ -16097,6 +16126,10 @@ if __name__ == "__main__":expect(recovery?.some((value) => value.startsWith("--message="))).toBe(true,);+ expect(onLifecycle.mock.calls.map(([scan]) => scan.status)).toEqual([+ "running",+ completion === "completed" ? "completed" : "failed",+ ]);} finally {clearTimeout(keepAlive);await client.close();diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.tsindex f2454e2ba..af50ea1b0 100644--- a/sdk/typescript/tests-ts/cli.test.ts+++ b/sdk/typescript/tests-ts/cli.test.ts@@ -3758,6 +3758,18 @@ describe("CLI", () => {verified: false,});options?.onOutputDirReady?.("/tmp/scan");+ options?.onLifecycle?.({+ scanId: result.manifest.scan.id,+ mode: "standard",+ status: "running",+ startedAt: result.manifest.scan.startedAt,+ finishedAt: null,+ hasReportableFindings: null,+ surface: "cli",+ packageVersion: VERSION,+ pluginVersion: BUNDLED_PLUGIN_VERSION,+ mock: false,+ });options?.onScanStarted?.();options?.onWorkerStatus?.({kind: "dispatch",@@ -3788,6 +3800,20 @@ describe("CLI", () => {'codex-security: debug: scan.output_ready scan_dir="/tmp/scan"',);expect(stderr.text()).toContain("codex-security: debug: scan.started");+ const lifecycleLine = stderr+ .text()+ .split("\n")+ .find((line) =>+ line.startsWith("codex-security: debug: scan.lifecycle "),+ );+ expect(lifecycleLine).toContain(+ `scan_id=${JSON.stringify(result.manifest.scan.id)}`,+ );+ expect(lifecycleLine).toContain('status="running"');+ expect(lifecycleLine).toContain('surface="cli"');+ expect(lifecycleLine).toContain(+ `package_version=${JSON.stringify(VERSION)}`,+ );expect(stderr.text()).toContain('codex-security: debug: worker.phase phase="validation" planned=6 started=3',);diff --git a/sdk/typescript/tests-ts/hosted-scan.test.ts b/sdk/typescript/tests-ts/hosted-scan.test.tsindex 03307fd5b..b88ee2eba 100644--- a/sdk/typescript/tests-ts/hosted-scan.test.ts+++ b/sdk/typescript/tests-ts/hosted-scan.test.ts@@ -363,6 +363,7 @@ test.each(sealedScopes)(const executor = draftExecutor((request) => {expect(request.scope.paths).toEqual(normalized);expect(request.identity).toEqual(input.identity);+ expect(request.runtime.environment["CODEX_SECURITY_SURFACE"]).toBe("sdk");expect(request).toMatchObject({model: input.model,reasoningEffort: input.reasoningEffort,@@ -889,6 +890,9 @@ test.each([false, true])(messages.push(message);if (message.method === "execution.run") {expect(message.params.reasoningEffort).toBe(input.reasoningEffort);+ expect(+ message.params.runtime.environment.CODEX_SECURITY_SURFACE,+ ).toBe("cli");if (cancel) {expect(message.params).not.toHaveProperty("severityRubric");expect(message.params.prompt).not.toContain('"severityRubric"');@@ -1039,18 +1043,22 @@ test("standalone SDK forwards progress, isolates observer errors and defaults toconst input = await fixture();delete input.scope;const events: string[] = [];- const result = await runHostedScan(input, {- executor: draftExecutor((request, options) => {- expect(request.scope.paths).toEqual(["."]);- options.onEvent?.(progressEvent);- options.onEvent?.(activityEvent);- }),- onEvent(event) {+ const executor = draftExecutor((request, options) => {+ expect(request.scope.paths).toEqual(["."]);+ options.onEvent?.(progressEvent);+ options.onEvent?.(activityEvent);+ });+ class Options {+ get executor() {+ return executor;+ }+ onEvent(event: ScanExecutionEvent) {events.push(event.type);if (event.type === "progress")throw new Error("Optional progress failed");- },- });+ }+ }+ const result = await runHostedScan(input, new Options());expect(result.status, JSON.stringify(result)).toBe("completed");expect(result.scope.paths).toEqual(["."]);expect(events).toContain("progress");@@ -1425,7 +1433,7 @@ test.each(["cancel", "disconnect", "signal"])(const input = new PassThrough();const controller = new AbortController();const { output, writing, release } = blockedOutput();- const run = spyOn(hostedScan, "runHostedScan");+ const run = spyOn(hostedScan, "runHostedScanInternal");try {const finished = runHostedScanProtocol(input, output, controller.signal);send(input, { id: "run", method: "run", params });diff --git a/sdk/typescript/tests-ts/import-scan.test.ts b/sdk/typescript/tests-ts/import-scan.test.tsindex 47a02b969..be4a99b7d 100644--- a/sdk/typescript/tests-ts/import-scan.test.ts+++ b/sdk/typescript/tests-ts/import-scan.test.ts@@ -22,6 +22,7 @@ import { importScan, type ImportScanOptions } from "../src/import-scan.js";import type { FindingsDocument } from "../src/models.js";import { ScanResult } from "../src/result.js";import { runWorkbench } from "../src/runtime.js";+import { VERSION } from "../src/version.js";import { PLUGIN_ROOT } from "./plugin-root.js";import { runTestInSubprocess } from "./support/test-subprocess.js";import { createApiTestFixtures } from "./support/temporary-directories.js";@@ -367,6 +368,19 @@ test.each(["csv", "json"] as const)(});expect(stored!.target_path).not.toBe(process.cwd());expect(stored!.target_path).not.toBe(context.root);+ const saved = await runWorkbench(context.workbenchOptions, [+ "get-scan",+ "--scan-id",+ result.manifest.scan.id,+ ]);+ expect(saved["scan"]).toMatchObject({+ lifecycle: {+ mode: "import",+ surface: "cli",+ packageVersion: VERSION,+ status: "completed",+ },+ });const recipe = await runWorkbench(context.workbenchOptions, ["get-scan-recipe","--scan-id",diff --git a/sdk/typescript/tests-ts/mock-scan.test.ts b/sdk/typescript/tests-ts/mock-scan.test.tsindex c91dea84a..8fd03f0e1 100644--- a/sdk/typescript/tests-ts/mock-scan.test.ts+++ b/sdk/typescript/tests-ts/mock-scan.test.ts@@ -1,4 +1,5 @@import type { JsonObject, ScanOptions } from "../src/index.js";+import { BUNDLED_PLUGIN_VERSION, VERSION } from "../src/version.js";import {mkdir,mkdtemp,@@ -25,7 +26,7 @@ import { rejecting, throwing } from "./support/errors.js";const { temporaryDirectories: roots, cleanup } = createApiTestFixtures();afterEach(cleanup);-async function fixture() {+async function fixture(workbench: typeof runWorkbench = runWorkbench) {const root = await mkdtemp(join(await realpath(tmpdir()), "mock-scan-test-"));roots.track(root);const repository = join(root, "repository");@@ -46,7 +47,7 @@ async function fixture() {{ pythonPath: python! },{environment,- runWorkbench,+ runWorkbench: workbench,resolvePluginPython: async () => python!,prepareRuntime: rejecting("Mock scan initialized Codex"),matchFindings: rejecting("Mock scan called model matching"),@@ -61,6 +62,9 @@ test("mock scans seal real artifacts and index shared and unique findings withouconst registrations: Array<Parameters<NonNullable<ScanOptions["onScanRegistered"]>>[0]> = [];+ const onLifecycle = mock<NonNullable<ScanOptions["onLifecycle"]>>();+ onLifecycle.mockImplementationOnce(rejecting("observer unavailable"));+ const onObserverError = mock<NonNullable<ScanOptions["onObserverError"]>>();try {const first = await client.run(repository, {mock: true,@@ -68,6 +72,8 @@ test("mock scans seal real artifacts and index shared and unique findings withoumaxCostUsd: 0.01,failureSeverity: "informational",onAuthentication: () => callbacks.push("authentication"),+ onLifecycle,+ onObserverError,onScanRegistered: (scan) => {callbacks.push("registered");registrations.push(scan);@@ -76,6 +82,33 @@ test("mock scans seal real artifacts and index shared and unique findings withou});const second = await client.run(repository, { mock: true });expect(callbacks).toEqual(["registered", "started"]);+ const launch = {+ scanId: first.manifest.scan.id,+ mode: "standard",+ startedAt: first.manifest.scan.startedAt,+ status: "running",+ finishedAt: null,+ hasReportableFindings: null,+ surface: "sdk",+ packageVersion: VERSION,+ pluginVersion: BUNDLED_PLUGIN_VERSION,+ mock: true,+ } as const;+ expect(onLifecycle.mock.calls).toEqual([+ [launch],+ [+ {+ ...launch,+ status: "completed",+ finishedAt: first.manifest.scan.completedAt,+ hasReportableFindings: true,+ },+ ],+ ]);+ expect(onObserverError).toHaveBeenCalledWith(+ "onLifecycle",+ expect.any(Error),+ );expect(registrations).toEqual([{scanId: first.manifest.scan.id,@@ -282,10 +315,18 @@ test("mock scans bind clean Git, committed diff, and working-tree snapshots", as"export const example = 2;\n",);await git("commit", "-am", "Update synthetic fixture");+ const onLifecycle = mock<NonNullable<ScanOptions["onLifecycle"]>>();const diff = await client.run(repository, {mock: true,target: DiffTarget.refs({ base: "HEAD~1" }),+ onLifecycle,});+ expect(+ onLifecycle.mock.calls.map(([{ mode, status }]) => [mode, status]),+ ).toEqual([+ ["diff", "running"],+ ["diff", "completed"],+ ]);expect(diff.manifest.scan.target.kind).toBe("git_diff");expect(diff.manifest.scan.mode).toBe("branch_diff");await writeFile(@@ -306,11 +347,13 @@ test("mock scans bind clean Git, committed diff, and working-tree snapshots", astest("aborting mock generation leaves a terminal scan record", async () => {const { client, repository, environment, python } = await fixture();const controller = new AbortController();+ const onLifecycle = mock<NonNullable<ScanOptions["onLifecycle"]>>();try {await expect(client.run(repository, {mock: true,signal: controller.signal,+ onLifecycle,onScanStarted: () => controller.abort(),}),).rejects.toThrow(ScanInterruptedError);@@ -321,6 +364,32 @@ test("aborting mock generation leaves a terminal scan record", async () => {expect(history["scans"]).toMatchObject([{ progress: { status: "failed" } },]);+ const [saved] = history["scans"] as JsonObject[];+ expect(onLifecycle.mock.calls.map(([snapshot]) => snapshot.status)).toEqual(+ ["running", "failed"],+ );+ expect(saved?.["lifecycle"]).toEqual(onLifecycle.mock.lastCall?.[0]);+ } finally {+ await client.close();+ }+});++test("reports committed completion after the workbench response is lost", async () => {+ const { client, repository } = await fixture(async (options, args, input) => {+ if (args[0] === "get-scan")+ throw new Error("Full scan details unavailable");+ const saved = await runWorkbench(options, args, input);+ if (args[0] === "complete-scan") throw new Error("completion reply lost");+ return saved;+ });+ const onLifecycle = mock<NonNullable<ScanOptions["onLifecycle"]>>();+ try {+ await expect(+ client.run(repository, { mock: true, onLifecycle }),+ ).rejects.toThrow("completion reply lost");+ expect(onLifecycle.mock.calls.map(([snapshot]) => snapshot.status)).toEqual(+ ["running", "completed"],+ );} finally {await client.close();}diff --git a/sdk/typescript/tests-ts/scan-resume.test.ts b/sdk/typescript/tests-ts/scan-resume.test.tsindex 13f02ebe6..fbe6a2710 100644--- a/sdk/typescript/tests-ts/scan-resume.test.ts+++ b/sdk/typescript/tests-ts/scan-resume.test.ts@@ -447,7 +447,8 @@ test("CLI resumes through native execution with current permissions and preservelet resumedThread: string | undefined;const { stderr, runCli } = createCliTest(main);- const code = await runCli(["scans", "resume", f.scanId, "--json"], {+ const flags = ["scans", "resume", f.scanId, "--json", "--verbose"];+ const code = await runCli(flags, {...dependencies({ environment: f.environment, currentDirectory: f.root }),runWorkbench: f.command,createSecurity: (config) =>@@ -532,6 +533,7 @@ test("CLI resumes through native execution with current permissions and preserve}),});expect(stderr.text()).toContain("Synthetic transport disconnected");+ expect(stderr.text()).not.toContain("debug: scan.lifecycle ");expect(stderr.text()).toContain(`scans show ${f.scanId}`);expect(stderr.text()).toContain(`scans logs ${f.scanId}`);expect(code).not.toBe(0);@@ -655,6 +657,38 @@ test.each([false, true])(},);+test("resuming reports a committed cancellation once without another launch", async () => {+ const f = await interruptedScan();+ const { stderr, runCli } = createCliTest(main);+ const code = await runCli(+ ["scans", "resume", f.scanId, "--json", "--verbose"],+ resumeDependencies(f, () => ({+ startThread: () => fail("Unexpected new session"),+ resumeThread: (threadId) => ({+ id: threadId,+ async runStreamed() {+ await f.command([+ "cancel-scan",+ "--scan-id",+ f.scanId,+ "--thread-id",+ threadId,+ ]);+ throw new Error("Synthetic transport disconnected");+ },+ }),+ })),+ );+ expect(code).not.toBe(0);+ const lifecycle = stderr+ .text()+ .split("\n")+ .filter((line) => line.includes("debug: scan.lifecycle "));+ expect(lifecycle).toHaveLength(1);+ expect(lifecycle[0]).toContain(`scan_id=${JSON.stringify(f.scanId)}`);+ expect(lifecycle[0]).toContain('status="canceled"');+});+test("resumed Bedrock scans retain provider context for the account advisory", async () => {const f = await interruptedScan("deep", false, {}, false, "amazon-bedrock");const { stderr, runCli } = createCliTest(main);