Skip to content

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

fix: keep workbench lifecycle results scoped to the selected scan (#2421)

Michael D'Angelo1d586acc2bce
diff --git a/plugins/codex-security/mcp-app/server.ts b/plugins/codex-security/mcp-app/server.ts
index d2c940442..a28fcd41f 100644
--- a/plugins/codex-security/mcp-app/server.ts
+++ b/plugins/codex-security/mcp-app/server.ts
@@ -399,6 +399,8 @@ const scanReadSchema = {
};
const scanContextSchema = {
...scanReadSchema,
+ requestId: z.string().uuid().optional(),
+ actionToken: z.string().uuid().optional(),
handoffClaimToken: handoffClaimTokenSchema
.optional()
.describe(
@@ -652,7 +654,7 @@ export function createCodexSecurityServer(): McpServer {
});
return scanActionResult(
{
- ...redactHandoffClaimToken(started),
+ ...modelScanContext(started, { omitHandoffClaim: true }),
scanId,
scanDir,
handoffClaimToken,
@@ -1034,6 +1036,7 @@ export function createCodexSecurityServer(): McpServer {
userContext: normalizedUserContext,
handoffClaimToken,
threadId,
+ modelThreadId: threadId,
projectConfigPath,
...modelSettings,
serviceTier:
@@ -1241,7 +1244,9 @@ export function createCodexSecurityServer(): McpServer {
"Open the scan's continuation thread and try again, or cancel it from the Codex Security workbench.",
);
}
- return cancelSecurityScan(scanId, threadId);
+ const canceled = await cancelSecurityScan(scanId, threadId);
+ modelScanContext(canceled.structuredContent);
+ return canceled;
},
);
@@ -1376,12 +1381,31 @@ export function createCodexSecurityServer(): McpServer {
{
title: "Get Codex Security Scan Context",
description:
- "Load the authoritative target, mode, optional user context, artifact directory, live progress, and optional selected finding for a launched scan. Validated legacy finding details may be migrated.",
+ "Load the authoritative target, mode, optional user context, artifact directory, live progress, and optional selected finding for a launched scan. For a remediation stage, pass the supplied occurrenceId, requestId and actionToken to read only its assigned finding. Validated legacy finding details may be migrated.",
inputSchema: scanContextSchema,
annotations: writingAnnotations,
_meta: modelActionMeta,
},
- async ({ scanId, occurrenceId, handoffClaimToken }, extra) => {
+ async (
+ { scanId, occurrenceId, requestId, actionToken, handoffClaimToken },
+ extra,
+ ) => {
+ if (requestId || actionToken) {
+ if (!occurrenceId || !requestId || !actionToken) {
+ throw new Error(
+ "Remediation context requires occurrenceId, requestId and actionToken.",
+ );
+ }
+ return scanActionResult(
+ await workbench("get-scan", {
+ scanId,
+ occurrenceId,
+ requestId,
+ actionToken,
+ }),
+ "Loaded the assigned remediation finding.",
+ );
+ }
const threadId = threadIdFromExtra(extra);
if (handoffClaimToken) {
await workbench("mark-handoff-delivered", {
@@ -1390,19 +1414,18 @@ export function createCodexSecurityServer(): McpServer {
threadId,
});
}
- const scanContext = await workbench("get-scan", { scanId, occurrenceId });
+ const cached = authenticatedArtifactClaims.get(scanId);
+ const scanContext = await workbench("get-scan", {
+ scanId,
+ occurrenceId,
+ modelThreadId: threadId ?? "",
+ contextClaimToken:
+ handoffClaimToken ??
+ (threadId && cached?.threadId === threadId ? cached.claimToken : ""),
+ });
const scan = isJsonObject(scanContext.scan)
? scanContext.scan
: undefined;
- if (!handoffClaimToken && scan?.handoffStatus === "pending") {
- const detail =
- typeof scan.handoffClaimToken === "string"
- ? "Pass the handoffClaimToken returned by the Codex Security scan launcher."
- : "Claim the pending Codex Security scan handoff before loading its context.";
- throw new Error(
- `This Codex Security scan handoff has not been delivered. ${detail}`,
- );
- }
if (
handoffClaimToken &&
threadId &&
@@ -1417,7 +1440,7 @@ export function createCodexSecurityServer(): McpServer {
});
}
return scanActionResult(
- redactHandoffClaimToken(scanContext),
+ modelScanContext(scanContext, { omitHandoffClaim: true }),
"Loaded Codex Security scan context.",
);
},
@@ -1457,7 +1480,10 @@ export function createCodexSecurityServer(): McpServer {
},
input.userContext,
);
- return scanActionResult(updated, "Updated Codex Security scan context.");
+ return scanActionResult(
+ input.threadId ? modelScanContext(updated) : updated,
+ "Updated Codex Security scan context.",
+ );
};
server.registerTool(
@@ -1540,7 +1566,8 @@ export function createCodexSecurityServer(): McpServer {
extra,
) => {
const modelSettings = codexModelSettingsFromExtra(extra);
- const current = await workbench("get-scan", { scanId });
+ const modelThreadId = threadIdFromExtra(extra) ?? "";
+ const current = await workbench("get-scan", { scanId, modelThreadId });
const scan = isJsonObject(current.scan) ? current.scan : undefined;
const progress =
scan && isJsonObject(scan.progress) ? scan.progress : undefined;
@@ -1559,28 +1586,31 @@ export function createCodexSecurityServer(): McpServer {
progress.status === "running"
) {
return scanActionResult(
- redactHandoffClaimToken(current),
+ modelScanContext(current, { omitHandoffClaim: true }),
"Deep Scan is still preparing. Discovery progress begins after its setup worker succeeds.",
);
}
return scanActionResult(
- await workbench("update-progress", {
- scanId,
- coordinatorGeneration:
- scan?.mode === "deep"
- ? deepScanStore.coordinatorGeneration(scanId)
- : undefined,
- ...modelSettings,
- claimToken: handoffClaimToken,
- deepReviewPass,
- phase,
- phaseItemsTotal,
- phaseItemsCompleted,
- phaseProgressUnit,
- reviewItemsTotal,
- reviewItemsCompleted,
- reportableFindingsCount,
- }),
+ modelScanContext(
+ await workbench("update-progress", {
+ scanId,
+ modelThreadId,
+ coordinatorGeneration:
+ scan?.mode === "deep"
+ ? deepScanStore.coordinatorGeneration(scanId)
+ : undefined,
+ ...modelSettings,
+ claimToken: handoffClaimToken,
+ deepReviewPass,
+ phase,
+ phaseItemsTotal,
+ phaseItemsCompleted,
+ phaseProgressUnit,
+ reviewItemsTotal,
+ reviewItemsCompleted,
+ reportableFindingsCount,
+ }),
+ ),
"Updated Codex Security scan progress.",
);
},
@@ -1598,14 +1628,16 @@ export function createCodexSecurityServer(): McpServer {
},
async ({ scanId, handoffClaimToken }, extra) => {
try {
+ const threadId = threadIdFromExtra(extra);
const completed = await workbench("complete-scan", {
scanId,
claimToken: handoffClaimToken,
- threadId: threadIdFromExtra(extra),
+ threadId,
+ modelThreadId: threadId ?? "",
turnId: securityScanTurnId(extra),
});
return scanActionResult(
- completed,
+ modelScanContext(completed),
"Validated and indexed the completed Codex Security scan.",
isJsonObject(completed.scan) ? completed.scan.scanId : undefined,
);
@@ -1652,9 +1684,10 @@ export function createCodexSecurityServer(): McpServer {
annotations: destructiveAnnotations,
_meta: modelActionMeta,
},
- async ({ scanId, message, handoffClaimToken }) => {
+ async ({ scanId, message, handoffClaimToken }, extra) => {
const failed = await workbench("fail-scan", {
scanId,
+ modelThreadId: threadIdFromExtra(extra) ?? "",
message,
claimToken: handoffClaimToken,
});
@@ -1663,7 +1696,7 @@ export function createCodexSecurityServer(): McpServer {
if (isJsonObject(progress) && progress["status"] === "failed")
deepScanCoordinators.get(scanId)?.failExternallyPersisted(message);
return scanActionResult(
- failed,
+ modelScanContext(failed),
"Recorded the Codex Security scan failure.",
isJsonObject(scan) ? scan.scanId : undefined,
);
@@ -1806,10 +1839,7 @@ export function createCodexSecurityServer(): McpServer {
scanActionResult(
await workbench(
"set-finding-remediation",
- {
- ...fields,
- patchStdin: patch !== undefined,
- },
+ { ...fields, patchStdin: patch !== undefined, assignedFinding: true },
typeof patch === "object"
? Buffer.from(patch.content, patch.encoding)
: patch,
@@ -1864,6 +1894,7 @@ export function createCodexSecurityServer(): McpServer {
registerFindingIssueTools(server, runWorkbench);
registerCompactArtifactTools(server, {
runWorkbench,
+ threadIdFromExtra,
pluginRoot: PLUGIN_ROOT,
resolveScanRoot: scanRoot,
resolveHandoffClaimToken: (scanId, requestContext) => {
@@ -2028,22 +2059,25 @@ function openWorkspaceResult(workspace: WorkspaceState) {
return result;
}
-function redactHandoffClaimToken(result: JsonObject) {
- const scan = isJsonObject(result.scan) ? result.scan : undefined;
- if (scan) {
- delete scan.handoffClaimToken;
- }
- const workspace = isJsonObject(result.workspace)
- ? result.workspace
+function modelScanContext<T extends JsonObject>(
+ context: T,
+ options?: { omitHandoffClaim: boolean },
+): T {
+ const workspace = isJsonObject(context.workspace)
+ ? context.workspace
: undefined;
- const workspaceResults =
- workspace && isJsonObject(workspace.results)
- ? workspace.results
- : undefined;
- if (workspaceResults) {
- delete workspaceResults.handoffClaimToken;
+ // Only a workbench action handoff authorizes a model to act on a finding.
+ for (const scan of [context.scan, workspace?.results]) {
+ if (!isJsonObject(scan)) continue;
+ if (options?.omitHandoffClaim) delete scan.handoffClaimToken;
+ if (!Array.isArray(scan.findings)) continue;
+ for (const finding of scan.findings) {
+ if (isJsonObject(finding) && isJsonObject(finding.remediationState)) {
+ delete finding.remediationState.actionClaimToken;
+ }
+ }
}
- return result;
+ return context;
}
function workspaceResult(workspace: WorkspaceState, scanId?: unknown) {
@@ -2086,7 +2120,7 @@ function promptOnlyScanResult(promptOnly: JsonObject) {
scan: { scanId },
} = start;
return scanActionResult(
- promptOnly,
+ modelScanContext(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,
);
diff --git a/plugins/codex-security/mcp-app/src/artifact-context.ts b/plugins/codex-security/mcp-app/src/artifact-context.ts
index 4db3fa652..d677df826 100644
--- a/plugins/codex-security/mcp-app/src/artifact-context.ts
+++ b/plugins/codex-security/mcp-app/src/artifact-context.ts
@@ -1,3 +1,4 @@
+import { workbenchArgs } from "./workbench-arguments.js";
import { asRecord } from "./record.js";
import { promises as fs } from "node:fs";
import { isAbsolute, resolve } from "node:path";
@@ -13,6 +14,7 @@ export type RunArtifactWorkbench = (
export interface ScanArtifactContextOptions {
requireRunning?: boolean;
requireClaim?: boolean;
+ modelThreadId?: string;
handoffClaimToken?: string;
pluginRoot?: string;
pythonCommand?: string;
@@ -32,7 +34,9 @@ export async function createScanArtifactContext(
);
}
- const result = await runWorkbench(["get-scan", "--scan-id", scanId]);
+ const result = await runWorkbench(
+ workbenchArgs("get-scan", { scanId, modelThreadId: options.modelThreadId }),
+ );
const scan = scanRecord(result, scanId);
const progress = asRecord(scan.progress);
const status =
@@ -89,6 +93,7 @@ export async function createScanArtifactContext(
scanId,
...defined("scope", optionalString(scan.scope)),
...defined("pluginRoot", options.pluginRoot),
+ ...defined("modelThreadId", options.modelThreadId),
...defined("pythonCommand", options.pythonCommand),
...defined("targetContract", targetContract),
...defined("targetRevision", optionalString(scan.targetRevision)),
diff --git a/plugins/codex-security/mcp-app/src/artifact-io.ts b/plugins/codex-security/mcp-app/src/artifact-io.ts
index f58be4d8a..21b97fdc4 100644
--- a/plugins/codex-security/mcp-app/src/artifact-io.ts
+++ b/plugins/codex-security/mcp-app/src/artifact-io.ts
@@ -27,6 +27,7 @@ export interface ArtifactContext {
targetContract?: Readonly<Record<string, unknown>>;
targetRevision?: string;
handoffClaimToken?: string;
+ modelThreadId?: string;
status?: string;
mode?: string;
}
diff --git a/plugins/codex-security/mcp-app/src/artifact-scan-draft.ts b/plugins/codex-security/mcp-app/src/artifact-scan-draft.ts
index a21241876..878c8ec1a 100644
--- a/plugins/codex-security/mcp-app/src/artifact-scan-draft.ts
+++ b/plugins/codex-security/mcp-app/src/artifact-scan-draft.ts
@@ -274,6 +274,9 @@ export async function recordCodexSecurityScanDraftViaWorkbench(
"--checkpoint-path",
checkpointPath,
];
+ if (context.modelThreadId !== undefined) {
+ arguments_.push(`--model-thread-id=${context.modelThreadId}`);
+ }
if (expectedDigest !== undefined) {
arguments_.push("--expected-draft-digest", expectedDigest);
}
diff --git a/plugins/codex-security/mcp-app/src/artifact-storage.ts b/plugins/codex-security/mcp-app/src/artifact-storage.ts
index 012747d33..9faf7bc36 100644
--- a/plugins/codex-security/mcp-app/src/artifact-storage.ts
+++ b/plugins/codex-security/mcp-app/src/artifact-storage.ts
@@ -100,7 +100,10 @@ async function storageContext(
create: boolean,
): Promise<ArtifactContext> {
if (storage === "persistent") return context;
- const identity = createHash("sha256").update(context.root).digest("hex");
+ // A scan keeps its ID when its output directory is archived and reused.
+ const identity = createHash("sha256")
+ .update(context.scanId ?? context.root)
+ .digest("hex");
const root = join(
await fs.realpath(tmpdir()),
`codex-security-artifacts-${identity}`,
@@ -223,6 +226,7 @@ export async function saveCodexSecurityArtifact(
scanId: context.scanId,
artifactPath: parts.join("/"),
claimToken: context.handoffClaimToken || undefined,
+ modelThreadId: context.modelThreadId,
}),
bytes,
);
diff --git a/plugins/codex-security/mcp-app/src/deep-scan/store.ts b/plugins/codex-security/mcp-app/src/deep-scan/store.ts
index b0a6c26a6..8fb0fbfa2 100644
--- a/plugins/codex-security/mcp-app/src/deep-scan/store.ts
+++ b/plugins/codex-security/mcp-app/src/deep-scan/store.ts
@@ -137,11 +137,13 @@ export class WorkbenchDeepScanStore {
reasoningEffort?: string;
serviceTier?: string;
threadId: string;
+ modelThreadId?: string;
scanRoot: string;
}): Promise<DeepScanRunState> {
const userContext = input.userContext;
const args = {
threadId: input.threadId,
+ modelThreadId: input.modelThreadId,
scanId: input.scanId || undefined,
targetPath: input.targetPath || undefined,
projectConfigPath: input.projectConfigPath,
diff --git a/plugins/codex-security/mcp-app/src/server/compact-artifact-tools.ts b/plugins/codex-security/mcp-app/src/server/compact-artifact-tools.ts
index e435fafaa..133b3fc7e 100644
--- a/plugins/codex-security/mcp-app/src/server/compact-artifact-tools.ts
+++ b/plugins/codex-security/mcp-app/src/server/compact-artifact-tools.ts
@@ -52,6 +52,7 @@ import {
} from "../artifact-storage.js";
export interface CompactArtifactToolOptions {
+ threadIdFromExtra: (requestContext: unknown) => string | undefined;
runWorkbench: RunArtifactWorkbench;
pluginRoot: string;
resolveScanRoot: () => Promise<string>;
@@ -353,6 +354,7 @@ async function scanContext(
return createScanArtifactContext(input.scanId, options.runWorkbench, {
requireRunning,
requireClaim: true,
+ modelThreadId: options.threadIdFromExtra(requestContext) ?? "",
handoffClaimToken:
input.handoffClaimToken ??
options.resolveHandoffClaimToken?.(input.scanId, requestContext),
diff --git a/plugins/codex-security/mcp-app/tests/test_artifact_storage_regressions.ts b/plugins/codex-security/mcp-app/tests/test_artifact_storage_regressions.ts
index 1d0040f30..f911ceff4 100644
--- a/plugins/codex-security/mcp-app/tests/test_artifact_storage_regressions.ts
+++ b/plugins/codex-security/mcp-app/tests/test_artifact_storage_regressions.ts
@@ -101,11 +101,12 @@ async function connect(overrides: Record<string, string | undefined> = {}) {
return async <Name extends keyof ArtifactToolResults>(
name: Name,
args: Record<string, unknown>,
+ threadId = "artifact-regression-owner",
): Promise<ArtifactToolResults[Name]> => {
const result = await client.callTool({
name,
arguments: args,
- _meta: { "openai/threadId": "artifact-regression-owner" },
+ _meta: { "openai/threadId": threadId },
});
assert.notEqual(result.isError, true, JSON.stringify(result));
return result.structuredContent as ArtifactToolResults[Name];
@@ -162,6 +163,70 @@ try {
await assert.rejects(fs.stat(scanRoot), { code: "ENOENT" });
});
+ await test("archived and replacement scans keep their own temporary evidence", async () => {
+ const call = await connect();
+ const output = path.join(fixture, "reused-output");
+ await fs.mkdir(output);
+ const recipe = {
+ config: {},
+ mode: "standard",
+ repository,
+ target: { kind: "repository", paths: [] },
+ };
+ const register = async (owner: string, ...options: string[]) => {
+ const { scanId } = await workbench([
+ "register-cli-scan",
+ "--repository",
+ repository,
+ "--scan-dir",
+ output,
+ "--recipe-json",
+ JSON.stringify(recipe),
+ ...options,
+ ]);
+ await workbench([
+ "set-scan-thread",
+ "--scan-id",
+ scanId,
+ "--thread-id",
+ owner,
+ ]);
+ return { scanId, storage: "temporary", path: "evidence.txt" };
+ };
+
+ const first = await register("first-owner");
+ const evidence = await call(
+ "save_codex_security_artifact",
+ { ...first, content: "first scan" },
+ "first-owner",
+ );
+ temporaryDirectories.push(evidence.directory);
+ await workbench([
+ "fail-scan",
+ "--scan-id",
+ first.scanId,
+ "--message",
+ "scan stopped",
+ ]);
+ const next = await register("next-owner", "--archive-existing");
+ const replacement = await call(
+ "save_codex_security_artifact",
+ { ...next, content: "next scan" },
+ "next-owner",
+ );
+ temporaryDirectories.push(replacement.directory);
+ assert.equal(await fs.readFile(evidence.path, "utf8"), "first scan");
+ assert.equal(
+ (await call("read_codex_security_artifact", first, "first-owner"))
+ .content,
+ "first scan",
+ );
+ assert.equal(
+ (await call("read_codex_security_artifact", next, "next-owner")).content,
+ "next scan",
+ );
+ });
+
await test("option-shaped temporary artifact names survive save, read and import", async () => {
const context = await standaloneArtifactContext(
repository,
diff --git a/plugins/codex-security/mcp-app/tests/test_compact_artifact_server.ts b/plugins/codex-security/mcp-app/tests/test_compact_artifact_server.ts
index 1d5e558b5..9b595cabc 100644
--- a/plugins/codex-security/mcp-app/tests/test_compact_artifact_server.ts
+++ b/plugins/codex-security/mcp-app/tests/test_compact_artifact_server.ts
@@ -90,6 +90,8 @@ try {
}
await test("shipped: claimed parent operations", () =>
testClaimedParentArtifactOperations(shipped, "shipped"));
+ await test("shipped: registered scan uses its attached thread", () =>
+ testRegisteredScanOwner(shipped));
await test("shipped: semantic scan draft completion", () =>
testSemanticScanDraftCompletion(shipped, "shipped"));
for (const artifactWriter of [false, true]) {
@@ -113,6 +115,62 @@ async function createScanFixture(label: string) {
return { repoRoot, environment };
}
+async function testRegisteredScanOwner(bundle: string) {
+ const { repoRoot, environment } = await createScanFixture("registered-owner");
+ const runWorkbench = (...args: string[]) =>
+ JSON.parse(
+ execFileSync(
+ fixturePython,
+ [path.join(bundledPluginRoot, "scripts/workbench_db.py"), ...args],
+ { env: { ...process.env, ...environment }, encoding: "utf8" },
+ ),
+ );
+ const scanDir = await realpath(
+ await mkdtemp(path.join(temporaryRoot, "registered-scan-")),
+ );
+ const { scanId } = runWorkbench(
+ "register-cli-scan",
+ "--repository",
+ repoRoot,
+ "--scan-dir",
+ scanDir,
+ "--recipe-json",
+ JSON.stringify({
+ config: {},
+ mode: "standard",
+ repository: repoRoot,
+ target: { kind: "repository", paths: [] },
+ }),
+ );
+ const owner = "registered-scan-thread";
+ const client = await startClient(bundle, environment);
+ const call = toolCaller(client, owner);
+ try {
+ requireToolError(
+ await call("get_codex_security_scan_context", { scanId }),
+ /owning Codex thread/,
+ "the registered scan awaits thread attachment",
+ );
+ runWorkbench("set-scan-thread", "--scan-id", scanId, "--thread-id", owner);
+ const current = requireSuccessfulTool<ScanResult>(
+ await call("get_codex_security_scan_context", { scanId }),
+ "load registered scan context",
+ );
+ assert.equal(current.scan.continuationThreadId, owner);
+ const stop = { scanId, message: "Fixture complete" };
+ requireSuccessfulTool(
+ await call("fail_codex_security_scan", stop),
+ "finish scan",
+ );
+ requireSuccessfulTool(
+ await call("fail_codex_security_scan", stop),
+ "repeat scan update",
+ );
+ } finally {
+ await client.close();
+ }
+}
+
async function testLargeScanDraftCheckpoints(
bundle: string,
runtimeLabel: string,
@@ -429,6 +487,15 @@ async function testCompactDiffScanCompletion(
await call("complete_codex_security_scan", { scanId, handoffClaimToken }),
`${runtimeLabel}: complete compact diff scan`,
);
+ requireSuccessfulTool(
+ await call("complete_codex_security_scan", { scanId, handoffClaimToken }),
+ "the owner can retry completed scans",
+ );
+ requireToolError(
+ await call("complete_codex_security_scan", { scanId }, "previous-thread"),
+ /owned by another continuation/,
+ "a previous continuation cannot complete the scan",
+ );
await rename(repoRoot, repoRoot + "-moved");
const saved = requireSuccessfulTool<{ content: string }>(
await call("read_codex_security_artifact", note),
@@ -972,7 +1039,7 @@ async function testClaimedParentArtifactOperations(
scanDir: scanDirectory,
handoffClaimToken: claimToken,
} = await startScan(
- call,
+ toolCaller(client, null),
ownerThread,
{ targetPath: repoRoot, scope: ".", mode: "deep" },
{
@@ -1021,6 +1088,14 @@ async function testClaimedParentArtifactOperations(
);
assert.equal(delivered.scan.continuationThreadId, ownerThread);
assert.equal(delivered.scan.handoffClaimToken, undefined);
+ requireSuccessfulTool(
+ await call("update_codex_security_scan_progress", {
+ scanId,
+ handoffClaimToken: claimToken,
+ phase: "preflight",
+ }),
+ "the owner can refresh Deep Scan preflight progress",
+ );
for (const [name, arguments_] of [
["prepare_codex_security_review_items", { scanId }],
@@ -1709,7 +1784,7 @@ async function startClient(
return client;
}
-function toolCaller(client: Client, ownerThread: string) {
+function toolCaller(client: Client, ownerThread: string | null) {
return (
name: string,
arguments_: Record<string, unknown>,
diff --git a/plugins/codex-security/mcp-app/tests/test_compact_artifact_wire.ts b/plugins/codex-security/mcp-app/tests/test_compact_artifact_wire.ts
index 4bb47a9d5..36eb17c3a 100644
--- a/plugins/codex-security/mcp-app/tests/test_compact_artifact_wire.ts
+++ b/plugins/codex-security/mcp-app/tests/test_compact_artifact_wire.ts
@@ -65,11 +65,14 @@ for (const raw of [false, true]) {
{
pluginRoot: path.resolve(import.meta.dirname, "../.."),
resolveScanRoot: async () => root,
+ threadIdFromExtra: () => undefined,
runWorkbench: async (args: string[]) => {
assert.deepEqual(args, [
"get-scan",
"--scan-id",
"11111111-1111-4111-8111-111111111111",
+ "--model-thread-id",
+ "",
]);
return {
scan: {
diff --git a/plugins/codex-security/mcp-app/tests/test_deep_scan_terminal_race.ts b/plugins/codex-security/mcp-app/tests/test_deep_scan_terminal_race.ts
index 1055ade7a..0550c0267 100644
--- a/plugins/codex-security/mcp-app/tests/test_deep_scan_terminal_race.ts
+++ b/plugins/codex-security/mcp-app/tests/test_deep_scan_terminal_race.ts
@@ -268,7 +268,7 @@ for (const ordering of [
failureCommit.release();
await fail(
{ scanId: run.scanId, message: "synthetic no-op failure" },
- {},
+ { _meta: { "openai/threadId": "fixture-owner" } },
);
assert.equal(
(await runWorkbench(["get-scan", "--scan-id", run.scanId])).workspace
@@ -309,7 +309,7 @@ for (const ordering of [
if (ordering !== "lost cancellation response") {
failure = fail(
{ scanId: run.scanId, message: "synthetic committed parent failure" },
- {},
+ { _meta: { "openai/threadId": "fixture-owner" } },
);
void failure!.catch(() => {});
await failureCommit.entered;
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.ts
index c5078ef20..348794eba 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
@@ -2563,6 +2563,46 @@ try {
index === 1 ? null : generationActionToken,
);
}
+ const stageContext = (
+ id: number,
+ fields: { occurrenceId: string; requestId: string; actionToken: string },
+ ) =>
+ testServer.callTool(id, {
+ name: "get_codex_security_scan_context",
+ arguments: { scanId, ...fields },
+ _meta: { "openai/threadId": "synthetic-remediation-thread" },
+ });
+ const generationClaim = {
+ occurrenceId,
+ requestId: remediationRequestId.toUpperCase(),
+ actionToken: generationActionToken.toUpperCase(),
+ };
+ const otherFinding = await stageContext(6301, {
+ ...generationClaim,
+ occurrenceId: results.findings[1].occurrenceId,
+ });
+ assert.equal(otherFinding.result.isError, true);
+ const stage = await stageContext(6300, generationClaim);
+ assertNoError(stage);
+ assert.deepEqual(Object.keys(stage.result.structuredContent), ["scan"]);
+ const scopedScan = stage.result.structuredContent.scan;
+ assert.deepEqual(Object.keys(scopedScan).sort(), [
+ "findings",
+ "scanDir",
+ "scanId",
+ "targetPath",
+ "targetRevision",
+ ]);
+ assert.deepEqual(
+ scopedScan.findings.map(
+ (entry: { occurrenceId: string }) => entry.occurrenceId,
+ ),
+ [occurrenceId],
+ );
+ assert.equal(
+ scopedScan.findings[0].remediationState.actionClaimToken,
+ generationActionToken,
+ );
const rejectedPendingClose = await testServer.callTool(161, {
name: "set_codex_security_finding_triage",
arguments: { occurrenceId, status: "closed", closeReason: "already_fixed" },
@@ -2587,15 +2627,22 @@ try {
const generatedPatch = await testServer.callSuccessfulTool(62, {
name: "set_codex_security_finding_remediation",
arguments: {
- actionToken: generationActionToken,
+ actionToken: generationActionToken.toUpperCase(),
occurrenceId,
- requestId: remediationRequestId,
+ requestId: remediationRequestId.toUpperCase(),
expectedVersion: 1,
state: "generated",
patch: remediationPatch,
summary: "Contain archive extraction under the output root.",
},
});
+ assert.deepEqual(Object.keys(generatedPatch.structuredContent), ["scan"]);
+ assert.deepEqual(
+ generatedPatch.structuredContent.scan.findings.map(
+ (entry: { occurrenceId: string }) => entry.occurrenceId,
+ ),
+ [occurrenceId],
+ );
const generatedFinding = generatedPatch.structuredContent.scan.findings[0];
const remediation = generatedFinding.remediationState;
const savedPatchPath = path.join(initializedScanDir, remediation.patchPath);
@@ -2716,6 +2763,16 @@ try {
"verify",
);
+ const refreshedStage = await stageContext(6322, {
+ ...generationClaim,
+ actionToken: verifyActionToken,
+ });
+ assertNoError(refreshedStage);
+ assert.equal(
+ refreshedStage.result.structuredContent.scan.findings[0].remediationState
+ .version,
+ 6,
+ );
const verifiedPatch = await testServer.callSuccessfulTool(170, {
name: "set_codex_security_finding_remediation",
arguments: {
@@ -2780,7 +2837,7 @@ try {
},
});
const { patchDigest, patchPath } =
- generatedLatin1.structuredContent.scan.findings[1].remediationState;
+ generatedLatin1.structuredContent.scan.findings[0].remediationState;
const latin1PatchPath = path.join(initializedScanDir, patchPath);
assert.equal(patchDigest, `sha256:${hash("sha256", latin1Patch)}`);
assert.deepEqual(await readFile(latin1PatchPath), latin1Patch);
@@ -3016,6 +3073,19 @@ try {
fallbackContext.structuredContent.workspace.results.handoffClaimToken,
undefined,
);
+ const cancelReplay = await testServer.callSuccessfulTool(22192, {
+ name: "cancel_codex_security_scan",
+ arguments: { scanId: canceledScanId },
+ _meta: { "openai/threadId": "fixture-thread" },
+ });
+ assert.equal(
+ cancelReplay.structuredContent.workspace.results.scanId,
+ canceledScanId,
+ );
+ assert.equal(
+ cancelReplay.structuredContent.workspace.results.progress.status,
+ "canceled",
+ );
const recoveryArtifactRead = (id: number) =>
testServer.callTool(id, {
name: "list_codex_security_review_items",
@@ -3053,6 +3123,11 @@ try {
.handoffClaimToken,
undefined,
);
+ await testServer.callSuccessfulTool(20176, {
+ name: "get_codex_security_scan_context",
+ arguments: { scanId: fallbackScanId },
+ _meta: { "openai/threadId": "fixture-replacement-recovery-thread" },
+ });
const afterRecovery = await recoveryArtifactRead(20175);
assert.equal(afterRecovery.result.isError, true);
assert.match(
diff --git a/plugins/codex-security/scripts/deep_scan_workbench.py b/plugins/codex-security/scripts/deep_scan_workbench.py
index e60098c2a..c15896d7a 100644
--- a/plugins/codex-security/scripts/deep_scan_workbench.py
+++ b/plugins/codex-security/scripts/deep_scan_workbench.py
@@ -15,7 +15,7 @@ from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parent))
import workbench_saved_results as saved_results
from deep_scan_config import resolve_deep_scan_setup
-from workbench.handoff import require_current_continuation
+from workbench.handoff import require_current_continuation, require_tokenless_scan_owner
from workbench.storage import (
archived_deep_path,
create_private_directory,
@@ -610,6 +610,8 @@ def begin_deep_scan_for_scan(
) -> dict[str, Any]:
scan_id = require_uuid(scan_id, "scan-id")
candidate = dependencies().require_scan(connection, scan_id)
+ model_thread_id = getattr(args, "model_thread_id", None)
+ require_tokenless_scan_owner(connection, candidate, model_thread_id)
workspace = dependencies().require_workspace(connection, candidate["workspace_id"])
if (
candidate["mode"] == "deep"
@@ -634,8 +636,17 @@ def begin_deep_scan_for_scan(
claimed_scan = connection.execute(
"UPDATE scans SET deep_scan_owner_thread_id = ?, updated_at = ? "
"WHERE id = ? AND deep_scan_owner_thread_id IS NULL "
- "AND handoff_status = 'delivered' AND handoff_claim_token IS ?",
- (thread_id, timestamp, scan_id, candidate["handoff_claim_token"]),
+ "AND handoff_status = 'delivered' AND handoff_claim_token IS ? "
+ "AND (handoff_claim_token IS NOT NULL OR continuation_thread_id = ? "
+ "OR (? IS NULL AND continuation_thread_id IS NULL))",
+ (
+ thread_id,
+ timestamp,
+ scan_id,
+ candidate["handoff_claim_token"],
+ thread_id,
+ model_thread_id,
+ ),
)
if claimed_workspace.rowcount != 1 or claimed_scan.rowcount != 1:
raise SystemExit("A scan can only be orchestrated from its owning Codex thread.")
diff --git a/plugins/codex-security/scripts/workbench/handoff.py b/plugins/codex-security/scripts/workbench/handoff.py
index 1d64d8854..71b8c4980 100644
--- a/plugins/codex-security/scripts/workbench/handoff.py
+++ b/plugins/codex-security/scripts/workbench/handoff.py
@@ -19,6 +19,33 @@ def require_handoff_claim_token(value: str) -> str:
return f"{RECOVERY_HANDOFF_TOKEN_PREFIX}{normalized}" if recovery_token else normalized
+def require_tokenless_scan_owner(
+ connection: sqlite3.Connection,
+ scan: sqlite3.Row,
+ model_thread_id: str | None,
+) -> None:
+ """Check model callers against a recorded owner. Trusted local callers omit model_thread_id."""
+ if model_thread_id is None or scan["handoff_claim_token"] is not None:
+ return
+ if scan["handoff_status"] == "pending":
+ raise SystemExit(
+ "This Codex Security scan handoff has not been delivered. "
+ "Claim the pending Codex Security scan handoff before continuing."
+ )
+ owner = scan["continuation_thread_id"] or scan["deep_scan_owner_thread_id"]
+ if owner is None:
+ owner = connection.execute(
+ "SELECT thread_id FROM workspaces WHERE id = ?", (scan["workspace_id"],)
+ ).fetchone()[0]
+ if owner is None:
+ # Only a completed import is intentionally ownerless among registered scans.
+ completed_import = scan["launch_kind"] == "import" and scan["status"] == "complete"
+ if scan["recipe_json"] is not None and not completed_import:
+ raise SystemExit("This scan is awaiting its owning Codex thread.")
+ elif owner != model_thread_id:
+ raise SystemExit("This scan requires its owning Codex thread.")
+
+
def require_current_continuation(
scan: sqlite3.Row,
claim_token: str | None,
diff --git a/plugins/codex-security/scripts/workbench_cli.py b/plugins/codex-security/scripts/workbench_cli.py
index 5c1c532bb..dd0b84a14 100644
--- a/plugins/codex-security/scripts/workbench_cli.py
+++ b/plugins/codex-security/scripts/workbench_cli.py
@@ -117,6 +117,7 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
)
begin_deep_scan = add_command("begin-deep-scan", "--thread-id")
+ begin_deep_scan.add_argument("--model-thread-id")
begin_target = begin_deep_scan.add_mutually_exclusive_group(required=True)
begin_target.add_argument("--scan-id")
begin_target.add_argument("--target-path")
@@ -192,6 +193,10 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
publication_failure.add_argument("--coordinator-generation", type=positive_int)
get_scan = add_command("get-scan", "--scan-id")
+ get_scan.add_argument("--model-thread-id")
+ get_scan.add_argument("--context-claim-token")
+ get_scan.add_argument("--request-id")
+ get_scan.add_argument("--action-token")
detail = get_scan.add_mutually_exclusive_group()
detail.add_argument("--occurrence-id")
detail.add_argument("--progress-only", action="store_true")
@@ -283,6 +288,7 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
list_findings.add_argument("--limit", type=positive_int, default=FINDINGS_PAGE_MAX)
update_progress = add_command("update-progress", "--scan-id")
+ update_progress.add_argument("--model-thread-id")
update_progress.add_argument("--phase", choices=PHASES)
update_progress.add_argument("--phase-items-total", type=non_negative_int)
update_progress.add_argument("--phase-items-completed", type=non_negative_int)
@@ -300,6 +306,7 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
prepare_scan_completion.add_argument("--claim-token")
complete_scan = add_command("complete-scan", "--scan-id")
+ complete_scan.add_argument("--model-thread-id")
complete_scan.add_argument("--claim-token")
complete_scan.add_argument("--cost-json")
complete_scan.add_argument("--thread-id")
@@ -322,6 +329,7 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
cancel_scan.add_argument("--cost-json")
fail_scan = add_command("fail-scan", "--scan-id", "--message")
+ fail_scan.add_argument("--model-thread-id")
fail_scan.add_argument("--claim-token")
fail_scan.add_argument("--cost-json")
@@ -337,11 +345,13 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
recover_scan.add_argument("--scan-id", required=True, help="ID of the stopped scan to recover.")
write_scan_draft = add_command("write-scan-draft", "--scan-id", "--draft-path")
+ write_scan_draft.add_argument("--model-thread-id")
write_scan_draft.add_argument("--checkpoint-path")
write_scan_draft.add_argument("--expected-draft-digest")
write_scan_draft.add_argument("--claim-token")
save_scan_artifact = add_command("save-scan-artifact", "--scan-id", "--artifact-path")
+ save_scan_artifact.add_argument("--model-thread-id")
save_scan_artifact.add_argument("--claim-token")
for command in ("save-artifact", "read-artifact"):
@@ -390,6 +400,7 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
set_finding_remediation.add_argument(
"--state", choices=REMEDIATION_UPDATE_STATES, required=True
)
+ set_finding_remediation.add_argument("--assigned-finding", action="store_true")
set_finding_remediation.add_argument("--summary")
set_finding_remediation.add_argument("--patch-stdin", action="store_true")
set_finding_remediation.add_argument("--patch-path")
diff --git a/plugins/codex-security/scripts/workbench_db.py b/plugins/codex-security/scripts/workbench_db.py
index 8842b9f24..8ff80600b 100644
--- a/plugins/codex-security/scripts/workbench_db.py
+++ b/plugins/codex-security/scripts/workbench_db.py
@@ -854,7 +854,8 @@ def _start_prompt_driven_scan(
"""
SELECT scans.* FROM scans
JOIN workspaces ON workspaces.active_scan_id = scans.id
- WHERE workspaces.thread_id = ? AND workspaces.target_path = ?
+ WHERE COALESCE(scans.continuation_thread_id, workspaces.thread_id) = ?
+ AND scans.recipe_json IS NULL AND workspaces.target_path = ?
AND workspaces.default_scope = ? AND workspaces.default_mode = ?
AND workspaces.user_context IS ? AND workspaces.target_summary IS ?
AND workspaces.diff_target_kind IS ? AND workspaces.diff_base_revision IS ?
@@ -867,7 +868,7 @@ def _start_prompt_driven_scan(
(? = 0 AND scans.handoff_claim_token IS NULL)
OR (
? = 1 AND scans.handoff_claim_token IS NOT NULL
- AND scans.continuation_thread_id = ?
+ AND scans.continuation_thread_id = workspaces.thread_id
)
)
ORDER BY scans.updated_at DESC, scans.started_at DESC, scans.id LIMIT 1
@@ -883,13 +884,12 @@ def _start_prompt_driven_scan(
*target_identity,
int(headless_standard),
int(headless_standard),
- thread_id,
),
).fetchone()
if existing is not None:
connection.commit()
return {
- **scan_context(connection, existing["id"]),
+ **scan_context(connection, existing["id"], model_thread_id=thread_id),
"startDisposition": "joined",
}
create_private_directory(target_root)
@@ -1027,6 +1027,7 @@ def complete_scan(
prepare_only=prepare_only,
thread_id=getattr(args, "thread_id", None),
turn_id=getattr(args, "turn_id", None),
+ model_thread_id=getattr(args, "model_thread_id", None),
)
@@ -1234,19 +1235,21 @@ def complete_scan_locked(
prepare_only: bool = False,
thread_id: str | None = None,
turn_id: str | None = None,
+ model_thread_id: str | None = None,
) -> dict[str, Any]:
scan = require_scan(connection, scan_id)
- if scan["status"] == "complete":
- return saved_results.refresh_completed_scan(
- _WORKBENCH_DB_CONTEXT, connection, scan, cost_json
- )
- if scan["status"] != "running":
+ handoff.require_tokenless_scan_owner(connection, scan, model_thread_id)
+ if scan["status"] not in {"running", "complete"}:
raise SystemExit("Only a running scan can be completed.")
handoff.require_current_continuation(
scan,
claim_token,
error_message="Scan completion is owned by another continuation.",
)
+ if scan["status"] == "complete":
+ return saved_results.refresh_completed_scan(
+ _WORKBENCH_DB_CONTEXT, connection, scan, cost_json
+ )
deep_scan.require_deep_scan_ready_for_parent_completion(connection, scan)
warnings = json.loads(scan["completion_warnings_json"])
target_warnings: list[str] = []
@@ -1413,17 +1416,18 @@ def complete_scan_locked(
with connection:
timestamp = manifest["scan"]["completedAt"]
scan = require_scan(connection, scan["id"])
- if scan["status"] == "complete":
- connection.commit()
- return scan_context(connection, scan["id"])
- if scan["status"] != "running":
+ handoff.require_tokenless_scan_owner(connection, scan, model_thread_id)
+ if scan["status"] not in {"running", "complete"}:
raise SystemExit("Only a running scan can be completed.")
- deep_scan.require_deep_scan_ready_for_parent_completion(connection, scan)
handoff.require_current_continuation(
scan,
claim_token,
error_message="Scan completion is owned by another continuation.",
)
+ if scan["status"] == "complete":
+ connection.commit()
+ return scan_context(connection, scan["id"])
+ deep_scan.require_deep_scan_ready_for_parent_completion(connection, scan)
connection.execute("DELETE FROM scan_artifacts WHERE scan_id = ?", (scan["id"],))
for kind, path in artifacts.items():
if path is not None:
@@ -2265,9 +2269,62 @@ def set_finding_remediation(
)
except (ContractError, OSError, SystemExit) as exc:
raise SystemExit(f"Could not save the remediation patch: {exc}") from exc
- return scan_context(
- connection, occurrence["scan_id"], occurrence["id"] if patch is not None else None
- )
+ if getattr(args, "assigned_finding", False):
+ return assigned_remediation_context(
+ connection,
+ occurrence["scan_id"],
+ occurrence["id"],
+ request_id,
+ action_token,
+ written_version=args.expected_version + 1,
+ )
+ return scan_context(connection, occurrence["scan_id"], occurrence["id"])
+
+
+def assigned_remediation_context(
+ connection: sqlite3.Connection,
+ scan_id: str,
+ occurrence_id: str,
+ request_id: str,
+ action_token: str,
+ *,
+ written_version: int | None = None,
+) -> dict[str, Any]:
+ """After authorization, project only the assigned finding and check the returned action state."""
+ occurrence = require_occurrence(connection, occurrence_id)
+ if occurrence["details_json"] == "{}":
+ backfill_legacy_finding_details(connection, require_scan(connection, scan_id))
+ occurrence = require_occurrence(connection, occurrence_id)
+ if occurrence["scan_id"] != scan_id:
+ raise SystemExit("This finding does not belong to the selected scan.")
+ scan = require_scan(connection, scan_id)
+ finding = finding_result(connection, scan, occurrence, related=None)
+ state = finding["remediationState"]
+ if written_version is None:
+ if not (
+ state.get("requestId") == request_id
+ and state.get("actionClaimToken") == action_token
+ and state.get("pendingAction")
+ ):
+ raise SystemExit(
+ "This remediation action is no longer owned by the supplied request and action token."
+ )
+ elif (
+ state.get("requestId") != request_id
+ or state.get("version") != written_version
+ or state.get("actionClaimToken") not in (None, action_token)
+ ):
+ # The next action may already have started since this write committed.
+ return {"occurrenceId": occurrence_id, "requestId": request_id, "version": written_version}
+ return {
+ "scan": {
+ "scanId": scan["id"],
+ "targetPath": scan["target_path"],
+ "targetRevision": scan["target_revision"],
+ "scanDir": scan["scan_dir"],
+ "findings": [finding],
+ }
+ }
def require_reviewed_patch_applied(
@@ -2455,11 +2512,10 @@ def workspace_state(
}
selected_scan_id = result_scan_id or workspace["active_scan_id"]
if selected_scan_id:
- selected_scan = require_scan(connection, selected_scan_id)
- result["userContext"] = selected_scan["user_context"]
- result["results"] = (
- result_scan if result_scan is not None else scan_result(connection, selected_scan)
- )
+ if result_scan is None:
+ result_scan = scan_result(connection, require_scan(connection, selected_scan_id))
+ result["userContext"] = result_scan["userContext"]
+ result["results"] = result_scan
return result
target_metadata = None
@@ -2500,9 +2556,15 @@ def scan_context(
connection: sqlite3.Connection,
scan_id: str,
occurrence_id: str | None = None,
+ *,
+ model_thread_id: str | None = None,
) -> dict[str, Any]:
scan = require_scan(connection, scan_id)
- result = scan_result(connection, scan, occurrence_id=occurrence_id)
+ # Legacy backfill may write before scan_result reloads the row for its response.
+ handoff.require_tokenless_scan_owner(connection, scan, model_thread_id)
+ result = scan_result(
+ connection, scan, occurrence_id=occurrence_id, model_thread_id=model_thread_id
+ )
workspace_result = result
if len(result["findings"]) > FINDINGS_RESULT_LIMIT:
workspace_result = dict(
@@ -2540,7 +2602,63 @@ def get_scan(connection: sqlite3.Connection, args: argparse.Namespace) -> dict[s
raise SystemExit("Codex Security scan not found.")
progress, _ = scan_progress_result(connection, scan)
return {"scan": {"progress": progress}}
- result = scan_context(connection, args.scan_id, args.occurrence_id)
+ request_id = getattr(args, "request_id", None)
+ action_token = getattr(args, "action_token", None)
+ if request_id is not None or action_token is not None:
+ scan_id = require_uuid(args.scan_id, "scan-id")
+ request_id = require_uuid(request_id or "", "request-id")
+ action_token = require_uuid(action_token or "", "action-token")
+ authorized = connection.execute(
+ """
+ SELECT 1 FROM finding_remediation_attempts AS action
+ JOIN finding_occurrences AS finding ON finding.id = action.occurrence_id
+ WHERE finding.scan_id = ? AND finding.id = ? AND action.request_id = ?
+ AND action.pending_action_claim_token = ? AND action.pending_action IS NOT NULL
+ """,
+ (scan_id, args.occurrence_id, request_id, action_token),
+ ).fetchone()
+ if authorized is None:
+ raise SystemExit(
+ "This remediation action is no longer owned by the supplied request and action token."
+ )
+ return assigned_remediation_context(
+ connection, scan_id, args.occurrence_id, request_id, action_token
+ )
+ context_claim = getattr(args, "context_claim_token", None)
+ model_thread = getattr(args, "model_thread_id", None)
+ if context_claim is not None:
+ scan = require_scan(connection, args.scan_id)
+ handoff.require_tokenless_scan_owner(connection, scan, model_thread)
+ if scan["handoff_status"] == "pending":
+ detail = (
+ "Pass the handoffClaimToken returned by the Codex Security scan launcher."
+ if scan["handoff_claim_token"]
+ else "Claim the pending Codex Security scan handoff before loading its context."
+ )
+ raise SystemExit(f"This Codex Security scan handoff has not been delivered. {detail}")
+ if context_claim:
+ context_claim = handoff.require_handoff_claim_token(context_claim)
+ if scan["handoff_claim_token"] and scan["handoff_claim_token"] != context_claim:
+ if not model_thread:
+ raise SystemExit("Scan context requires its current continuation claim.")
+ owner = (
+ scan["continuation_thread_id"]
+ or require_workspace(connection, scan["workspace_id"])["thread_id"]
+ )
+ if model_thread != owner:
+ raise SystemExit("Scan context is owned by another continuation.")
+ if (
+ args.occurrence_id is not None
+ and connection.execute(
+ "SELECT 1 FROM finding_occurrences WHERE scan_id = ? AND id = ?",
+ (scan["id"], args.occurrence_id),
+ ).fetchone()
+ is None
+ ):
+ raise SystemExit("This finding was not found in the selected scan.")
+ result = scan_context(
+ connection, args.scan_id, args.occurrence_id, model_thread_id=model_thread
+ )
if result["scan"]["progress"]["status"] != "running":
scan = require_scan(connection, args.scan_id)
try:
@@ -2636,6 +2754,7 @@ def scan_result(
scan: sqlite3.Row,
*,
occurrence_id: str | None = None,
+ model_thread_id: str | None = None,
) -> dict[str, Any]:
"""Assemble the workbench view of a saved scan, backfilling older finding details as needed.
@@ -2644,6 +2763,7 @@ def scan_result(
"""
backfill_legacy_finding_details(connection, scan)
scan = scan_history.scan_with_progress(connection, scan["id"])
+ handoff.require_tokenless_scan_owner(connection, scan, model_thread_id)
artifact_rows = connection.execute(
"SELECT kind, path FROM scan_artifacts WHERE scan_id = ?", (scan["id"],)
)
@@ -2848,7 +2968,7 @@ def finding_result(
scan: sqlite3.Row,
occurrence: sqlite3.Row,
*,
- related: list[dict[str, Any]],
+ related: list[dict[str, Any]] | None,
) -> dict[str, Any]:
details = bounded_finding_details(read_finding_details(occurrence["details_json"]))
confidence = details.get("confidence")
@@ -2917,15 +3037,16 @@ def finding_result(
"title": bounded_output_text(occurrence["title"], FINDING_TITLE_BYTES),
"triage": finding_triage_result(connection, occurrence["id"]),
}
- matches, known_since, known_scan_ids = scan_history.finding_matches(
- connection, occurrence["id"], scan["id"], scan["started_at"]
- )
- if matches:
- result["matches"] = matches
- result["knownSince"] = known_since
- result["knownScanIds"] = known_scan_ids
- if related:
- result["related"] = related
+ if related is not None:
+ matches, known_since, known_scan_ids = scan_history.finding_matches(
+ connection, occurrence["id"], scan["id"], scan["started_at"]
+ )
+ if matches:
+ result["matches"] = matches
+ result["knownSince"] = known_since
+ result["knownScanIds"] = known_scan_ids
+ if related:
+ result["related"] = related
source_excerpt = finding_source_excerpt(
scan, target, excerpt_locations, requested_scan_paths(scan)
)
diff --git a/plugins/codex-security/scripts/workbench_progress.py b/plugins/codex-security/scripts/workbench_progress.py
index 7727bb8d3..ea1c3d195 100644
--- a/plugins/codex-security/scripts/workbench_progress.py
+++ b/plugins/codex-security/scripts/workbench_progress.py
@@ -8,7 +8,7 @@ from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parent))
from deep_scan_workbench import require_current_coordinator
-from workbench.handoff import require_current_continuation
+from workbench.handoff import require_current_continuation, require_tokenless_scan_owner
from workbench_constants import PHASES
from workbench_validation import optional_text, require_uuid, user_context_argument
@@ -87,6 +87,7 @@ def update_progress(
with connection:
timestamp = wb.now()
scan = wb.require_scan(connection, scan_id)
+ require_tokenless_scan_owner(connection, scan, getattr(args, "model_thread_id", None))
if scan["status"] != "running":
raise SystemExit("Only a running scan can update progress.")
if scan["mode"] == "deep":
diff --git a/plugins/codex-security/scripts/workbench_saved_results.py b/plugins/codex-security/scripts/workbench_saved_results.py
index 83ebfd87e..d98ae9e3b 100644
--- a/plugins/codex-security/scripts/workbench_saved_results.py
+++ b/plugins/codex-security/scripts/workbench_saved_results.py
@@ -974,6 +974,9 @@ def save_scan_artifact(db: Any, connection: Any, args: Any) -> dict[str, Any]:
scan_id = db.require_uuid(args.scan_id, "scan-id")
with db.scan_completion_lock(scan_id):
scan = db.require_scan(connection, scan_id)
+ db.handoff.require_tokenless_scan_owner(
+ connection, scan, getattr(args, "model_thread_id", None)
+ )
db.handoff.require_current_continuation(
scan,
args.claim_token,
@@ -1011,6 +1014,9 @@ def write_scan_draft(db: Any, connection: Any, args: Any) -> dict[str, Any]:
scan_id = db.require_uuid(args.scan_id, "scan-id")
with db.scan_completion_lock(scan_id):
scan = db.require_scan(connection, scan_id)
+ db.handoff.require_tokenless_scan_owner(
+ connection, scan, getattr(args, "model_thread_id", None)
+ )
db.handoff.require_current_continuation(
scan, args.claim_token, error_message="Scan draft is owned by another continuation."
)
@@ -1264,10 +1270,9 @@ def fail_scan_locked(db: Any, connection: Any, args: Any) -> dict[str, Any]:
with connection:
timestamp = db.now()
scan = db.require_scan(connection, scan_id)
- if scan["status"] == "failed":
- connection.commit()
- record_stopped_scan_usage(db, connection, scan_id, cost_json)
- return db.scan_context(connection, scan["id"])
+ db.handoff.require_tokenless_scan_owner(
+ connection, scan, getattr(args, "model_thread_id", None)
+ )
if scan["status"] == "complete":
raise SystemExit("A completed scan cannot be marked failed.")
db.handoff.require_current_continuation(
@@ -1275,6 +1280,10 @@ def fail_scan_locked(db: Any, connection: Any, args: Any) -> dict[str, Any]:
args.claim_token,
error_message="Scan failure is owned by another continuation.",
)
+ if scan["status"] == "failed":
+ connection.commit()
+ record_stopped_scan_usage(db, connection, scan_id, cost_json)
+ return db.scan_context(connection, scan["id"])
message = db.optional_text(args.message)
if not mark_running_scan_failed(connection, scan_id, message, timestamp):
raise SystemExit("Only a running scan can be marked failed.")
@@ -1295,6 +1304,8 @@ def cancel_scan_locked(db: Any, connection: Any, args: Any) -> dict[str, Any]:
scan_id = db.require_uuid(args.scan_id, "scan-id")
thread_id = db.optional_text(args.thread_id, maximum=512)
cost_json = db.parse_scan_cost(getattr(args, "cost_json", None))
+ # The app displays the active scan. A conversation may only receive the scan it canceled.
+ result_scan_id = scan_id if thread_id is not None else None
connection.execute("BEGIN IMMEDIATE")
with connection:
timestamp = db.now()
@@ -1307,7 +1318,9 @@ def cancel_scan_locked(db: Any, connection: Any, args: Any) -> dict[str, Any]:
connection.commit()
record_stopped_scan_usage(db, connection, scan_id, cost_json)
return {
- **db.workspace_state(connection, scan["workspace_id"]),
+ **db.workspace_state(
+ connection, scan["workspace_id"], result_scan_id=result_scan_id
+ ),
"canceledScanId": scan["id"],
}
if scan["status"] != "running":
@@ -1327,7 +1340,10 @@ def cancel_scan_locked(db: Any, connection: Any, args: Any) -> dict[str, Any]:
raise SystemExit("Codex Security scan progress not found.")
record_stopped_scan_usage(db, connection, scan_id, cost_json)
preserve_stopped_results_after_transition(db, connection, scan["id"])
- return {**db.workspace_state(connection, scan["workspace_id"]), "canceledScanId": scan["id"]}
+ return {
+ **db.workspace_state(connection, scan["workspace_id"], result_scan_id=result_scan_id),
+ "canceledScanId": scan["id"],
+ }
def record_stopped_scan_usage(
diff --git a/plugins/codex-security/skills/fix-finding/SKILL.md b/plugins/codex-security/skills/fix-finding/SKILL.md
index 9ff694a95..839dbc6f7 100644
--- a/plugins/codex-security/skills/fix-finding/SKILL.md
+++ b/plugins/codex-security/skills/fix-finding/SKILL.md
@@ -53,7 +53,7 @@ Confirm review concerns against source or, in standard mode, focused execution b
## Workbench Remediation Stages
-When a Codex Security workbench request includes a scan ID, occurrence ID, remediation request ID, action token, and expected version, follow only the requested remediation stage. The stage boundary changes when code may be written, but it does not weaken the validation requirements above.
+When a Codex Security workbench request includes a scan ID, occurrence ID, remediation request ID, action token, and expected version, pass the supplied `scanId`, `occurrenceId`, `requestId`, and `actionToken` to `get_codex_security_scan_context` when loading or refreshing the assigned finding. Follow only the requested remediation stage. The stage boundary changes when code may be written, but it does not weaken the validation requirements above.
Before creating or entering any work copy, select Python and Git from a controlled empty directory outside all checkouts. Verify that each trusted tool's absolute invocation path, resolved parent directory, and resolved executable are outside the selected target, its enclosing checkout, and all capture and rehearsal workspaces. Use the host-selected Python (`CODEX_SECURITY_PYTHON_COMMAND` in SDK runs). If absent, use a trusted absolute `PYTHON`, a host-managed runtime, or a verified system interpreter. Invoke its quoted absolute path with `-I` to import helpers from the installed plugin's scripts directory. From the same directory call `workbench_target.trusted_git_executable(target)`, which honors `CODEX_SECURITY_GIT` or discovers Git when that variable is absent. Pin the verified absolute invocation path it returns in the helper process's `CODEX_SECURITY_GIT` environment and pass it to child helpers. Stop if either tool cannot be verified. For workbench Generate and Apply Git commands, pass `offline=True` and the real target to `workbench_target.git_command`, use `-C` for the working directory, and set `-c core.hooksPath=<empty private directory>`.
diff --git a/plugins/codex-security/tests/test_workbench_cancellation.py b/plugins/codex-security/tests/test_workbench_cancellation.py
index 2d40c6db5..aad54a5d7 100644
--- a/plugins/codex-security/tests/test_workbench_cancellation.py
+++ b/plugins/codex-security/tests/test_workbench_cancellation.py
@@ -81,8 +81,9 @@ def test_start_scan_returns_selected_scan_when_replaced_before_response(
assert result["results"]["progress"]["status"] == "canceled"
[email protected]("app", [False, True])
def test_cancellation_identifies_committed_scan_when_workspace_has_replacement(
- tmp_path, monkeypatch
+ tmp_path, monkeypatch, app
):
workbench = load_script("workbench_db")
state_dir, target = empty_target_paths(tmp_path)
@@ -106,14 +107,18 @@ def test_cancellation_identifies_committed_scan_when_workspace_has_replacement(
canceled = workbench.saved_results.cancel_scan(
workbench._WORKBENCH_DB_CONTEXT,
connection,
- argparse.Namespace(scan_id=scan_id, thread_id=thread_id),
+ argparse.Namespace(scan_id=scan_id, thread_id=None if app else thread_id),
)
- replay = cancel_scan(state_dir, scan_id, thread_id)
+ replay = (
+ scan_command(state_dir, "cancel-scan", scan_id)
+ if app
+ else 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"
+ assert response["results"]["scanId"] == (replacement_id if app else scan_id)
+ assert response["results"]["progress"]["status"] == ("running" if app else "canceled")
def test_workbench_records_scan_failure(tmp_path: Path) -> None:
diff --git a/plugins/codex-security/tests/test_workbench_deep_scan.py b/plugins/codex-security/tests/test_workbench_deep_scan.py
index 14676dca0..4c0fd173c 100644
--- a/plugins/codex-security/tests/test_workbench_deep_scan.py
+++ b/plugins/codex-security/tests/test_workbench_deep_scan.py
@@ -1310,11 +1310,28 @@ def test_sdk_scan_begin_claims_its_existing_scan(tmp_path: Path) -> None:
)
assert "orchestration must finish and persist its manifest" in str(premature["stderr"])
+ def model_begin(thread: str) -> dict[str, object]:
+ return begin_deep_scan(
+ state_dir,
+ thread,
+ "--scan-id",
+ scan_id,
+ "--model-thread-id",
+ thread,
+ environment=deep_environment(codex_home),
+ check=False,
+ )
+
+ assert "awaiting its owning Codex thread" in str(model_begin("other-thread")["stderr"])
+ scan_command(state_dir, "set-scan-thread", scan_id, "--thread-id", "sdk-thread")
+ assert "owning Codex thread" in str(model_begin("other-thread")["stderr"])
begun = begin_deep_scan(
state_dir,
"sdk-thread",
"--scan-id",
scan_id,
+ "--model-thread-id",
+ "sdk-thread",
"--service-tier",
"priority",
environment=deep_environment(codex_home),
diff --git a/plugins/codex-security/tests/test_workbench_prompt_only_scan.py b/plugins/codex-security/tests/test_workbench_prompt_only_scan.py
index 25c24b3bd..a7d016f46 100644
--- a/plugins/codex-security/tests/test_workbench_prompt_only_scan.py
+++ b/plugins/codex-security/tests/test_workbench_prompt_only_scan.py
@@ -192,6 +192,33 @@ def test_prompt_only_scan_creates_submitted_delivered_scan(
assert workspace["results"]["scanId"] == scan["scanId"]
+def test_prompt_only_rejoin_follows_the_attached_continuation(tmp_path: Path) -> None:
+ state_dir, target = empty_target_paths(tmp_path)
+ scan_root = tmp_path / "scans"
+ started = start_prompt_only_scan(state_dir, target, scan_root)
+ scan_id = str(started["scan"]["scanId"])
+ continuation = "attached-prompt-thread"
+ scan_command(state_dir, "set-scan-thread", scan_id, "--thread-id", continuation)
+ context = "Review the password-reset flow."
+ scan_command(
+ state_dir,
+ "update-scan-context",
+ scan_id,
+ "--thread-id",
+ continuation,
+ "--user-context",
+ context,
+ )
+
+ replacement = start_prompt_only_scan(state_dir, target, scan_root)
+ assert replacement["startDisposition"] == "created"
+ assert replacement["scan"]["scanId"] != scan_id
+ joined = start_prompt_only_scan(state_dir, target, scan_root, thread_id=continuation)
+ assert joined["startDisposition"] == "joined"
+ assert joined["scan"]["scanId"] == scan_id
+ assert joined["scan"]["userContext"] == context
+
+
def test_prompt_only_standard_phase_uses_latest_persisted_scan_context(
tmp_path: Path,
) -> None:
diff --git a/sdk/typescript/tests-ts/deep-scan-workbench.test.ts b/sdk/typescript/tests-ts/deep-scan-workbench.test.ts
index e2bed886c..475ab82a2 100644
--- a/sdk/typescript/tests-ts/deep-scan-workbench.test.ts
+++ b/sdk/typescript/tests-ts/deep-scan-workbench.test.ts
@@ -26,12 +26,12 @@ const deepScanOwnershipProbe = [
"connection.row_factory = sqlite3.Row",
"connection.executescript('''",
"CREATE TABLE workspaces (id TEXT PRIMARY KEY, thread_id TEXT, updated_at TEXT);",
- "CREATE TABLE scans (id TEXT PRIMARY KEY, workspace_id TEXT, mode TEXT, status TEXT, recipe_json TEXT, handoff_status TEXT, handoff_claim_token TEXT, deep_scan_owner_thread_id TEXT, updated_at TEXT);",
+ "CREATE TABLE scans (id TEXT PRIMARY KEY, workspace_id TEXT, mode TEXT, status TEXT, recipe_json TEXT, handoff_status TEXT, handoff_claim_token TEXT, deep_scan_owner_thread_id TEXT, continuation_thread_id TEXT, updated_at TEXT);",
"CREATE TABLE deep_scan_runs (scan_id TEXT PRIMARY KEY);",
"''')",
"scan_id = '11111111-1111-4111-8111-111111111111'",
"connection.execute(\"INSERT INTO workspaces VALUES ('workspace', NULL, 'before')\")",
- "connection.execute(\"INSERT INTO scans VALUES (?, 'workspace', 'deep', 'running', '{}', 'delivered', ?, NULL, 'before')\", (scan_id, case['storedToken']))",
+ "connection.execute(\"INSERT INTO scans VALUES (?, 'workspace', 'deep', 'running', '{}', 'delivered', ?, NULL, NULL, 'before')\", (scan_id, case['storedToken']))",
"connection.execute('INSERT INTO deep_scan_runs VALUES (?)', (scan_id,))",
"connection.commit()",
"if case.get('mutation') == 'rotate':",