diff --git a/plugins/codex-security/mcp-app/scripts/generate-artifact-schemas.mjs b/plugins/codex-security/mcp-app/scripts/generate-artifact-schemas.mjs index 0b3ec471e..6c2fa1ab2 100644 --- a/plugins/codex-security/mcp-app/scripts/generate-artifact-schemas.mjs +++ b/plugins/codex-security/mcp-app/scripts/generate-artifact-schemas.mjs @@ -8,6 +8,7 @@ import * as z from "zod/v4"; const bundled = await build({ stdin: { contents: `export * from "../src/artifact-contracts.ts"; + export { forbiddenProperty } from "../src/artifact-schema-loader.ts"; export * from "./canonical-schemas.mts";`, resolveDir: fileURLToPath(new URL(".", import.meta.url)), }, @@ -20,6 +21,7 @@ const { artifactSchemaDocuments, artifactJsonMetadata, canonicalSchemaDocuments, + forbiddenProperty, } = await import( `data:text/javascript;base64,${Buffer.from(bundled.outputFiles[0].contents).toString("base64")}` ); @@ -80,8 +82,7 @@ for (const [path, { $defs, ...header }] of Object.entries( ...header, $defs: definitions, }, - (_key, schema) => - JSON.stringify(schema) === '{"not":{}}' ? false : schema, + (_key, schema) => (forbiddenProperty(schema) ? false : schema), ); } for (const [path, { title, schema, definitions = {} }] of Object.entries( diff --git a/plugins/codex-security/mcp-app/server.ts b/plugins/codex-security/mcp-app/server.ts index b247bbdd5..a5b5750f7 100644 --- a/plugins/codex-security/mcp-app/server.ts +++ b/plugins/codex-security/mcp-app/server.ts @@ -215,9 +215,9 @@ const startHeadlessStandardScanSchema = { .optional() .describe("Optional security focus supplied by the user."), }; -type PromptOnlyScanInput = z.output< - z.ZodObject ->; +type ConversationScanInput = + | z.output> + | z.output>; const userInputOptionSchema = z.strictObject({ description: requiredText.max(1200), label: requiredText.max(200), @@ -600,21 +600,14 @@ export function createCodexSecurityServer(): McpServer { annotations: writingAnnotations, _meta: modelActionMeta, }, - async ( - { targetPath, scope, targetSummary, userContext, projectConfigPath }, - extra, - ) => { + async (input, extra) => { const threadId = threadIdFromExtra(extra); if (!threadId) { return toolErrorResult( "Starting a Standard scan requires the owning Codex thread context.", ); } - const started = await startHeadlessStandardScan( - { targetPath, scope, targetSummary, userContext, projectConfigPath }, - threadId, - codexModelSettingsFromExtra(extra), - ); + const started = await startConversationScan(input, threadId, extra); const scan = startedScanSchema.safeParse(started).data?.scan; const progress = isJsonObject(scan?.progress) ? scan.progress : undefined; const handoffClaimToken = scan?.handoffClaimToken; @@ -671,18 +664,8 @@ export function createCodexSecurityServer(): McpServer { annotations: writingAnnotations, _meta: modelActionMeta, }, - async ( - { - mode, - targetPath, - scope, - targetSummary, - userContext, - diffTarget, - projectConfigPath, - }, - extra, - ) => { + async (input, extra) => { + const { mode, diffTarget, scope, targetPath } = input; if (mode === "diff" && !diffTarget) { return toolErrorResult( "Review changes prompt-only scans require diffTarget.", @@ -704,20 +687,9 @@ export function createCodexSecurityServer(): McpServer { "Starting a prompt-only scan requires the owning Codex thread context.", ); } - const promptOnly = await startPromptOnlyScan( - { - mode, - targetPath, - scope, - targetSummary, - userContext, - diffTarget, - projectConfigPath, - }, - threadId, - codexModelSettingsFromExtra(extra), + return promptOnlyScanResult( + await startConversationScan(input, threadId, extra), ); - return promptOnlyScanResult(promptOnly); }, ); @@ -1345,16 +1317,9 @@ export function createCodexSecurityServer(): McpServer { annotations: readingAnnotations, _meta: appMeta, }, - async ({ limit, mode, offset, query, status, targetId }) => + async (input) => scanActionResult( - await workbench("list-scans", { - query, - targetId, - status, - mode, - offset, - limit, - }), + await workbench("list-scans", input), "Loaded Codex Security scan summaries.", ), ); @@ -1369,16 +1334,9 @@ export function createCodexSecurityServer(): McpServer { annotations: readingAnnotations, _meta: appMeta, }, - async ({ limit, offset, query, severity, status, targetId }) => + async (input) => scanActionResult( - await workbench("list-global-findings", { - query, - severity, - status, - targetId, - offset, - limit, - }), + await workbench("list-global-findings", input), "Loaded Codex Security global findings.", ), ); @@ -1393,15 +1351,9 @@ export function createCodexSecurityServer(): McpServer { annotations: readingAnnotations, _meta: appMeta, }, - async ({ limit, offset, query, status, targetId }) => + async (input) => scanActionResult( - await workbench("list-repositories", { - query, - targetId, - status, - offset, - limit, - }), + await workbench("list-repositories", input), "Loaded Codex Security repositories.", ), ); @@ -1584,37 +1536,16 @@ export function createCodexSecurityServer(): McpServer { annotations: writingAnnotations, _meta: modelActionMeta, }, - async ( - { - scanId, - deepReviewPass, - phase, - phaseItemsTotal, - phaseItemsCompleted, - phaseProgressUnit, - reviewItemsTotal, - reviewItemsCompleted, - reportableFindingsCount, - handoffClaimToken, - }, - extra, - ) => { - const modelSettings = codexModelSettingsFromExtra(extra); + async ({ handoffClaimToken, ...progress }, extra) => { const { scan, deepPreflight } = await workbench("update-progress", { - scanId, + ...progress, modelUpdate: true, modelThreadId: threadIdFromExtra(extra) ?? "", - coordinatorGeneration: deepScanStore.coordinatorGeneration(scanId), - ...modelSettings, + coordinatorGeneration: deepScanStore.coordinatorGeneration( + progress.scanId, + ), + ...codexModelSettingsFromExtra(extra), claimToken: handoffClaimToken, - deepReviewPass, - phase, - phaseItemsTotal, - phaseItemsCompleted, - phaseProgressUnit, - reviewItemsTotal, - reviewItemsCompleted, - reportableFindingsCount, }); return scanActionResult( { scan }, @@ -1682,14 +1613,9 @@ export function createCodexSecurityServer(): McpServer { annotations: writingAnnotations, _meta: appMeta, }, - async ({ scanId, threadId, turnId, turnStatus }) => + async (input) => scanActionResult( - await workbench("finalize-scan-usage", { - scanId, - threadId, - turnId, - turnStatus, - }), + await workbench("finalize-scan-usage", input), "Recorded final Codex Security scan usage.", ), ); @@ -1733,14 +1659,9 @@ export function createCodexSecurityServer(): McpServer { annotations: writingAnnotations, _meta: appMeta, }, - async ({ occurrenceId, status, closeReason, note }) => + async (input) => scanActionResult( - await workbench("set-finding-triage", { - occurrenceId, - status, - closeReason, - note, - }), + await workbench("set-finding-triage", input), "Updated the local Codex Security finding status.", ), ); @@ -1755,13 +1676,9 @@ export function createCodexSecurityServer(): McpServer { annotations: writingAnnotations, _meta: appMeta, }, - async ({ occurrenceId, requestId, actionToken }) => + async (input) => scanActionResult( - await workbench("request-finding-remediation", { - occurrenceId, - requestId, - actionToken, - }), + await workbench("request-finding-remediation", input), "Queued the local Codex Security finding remediation request.", ), ); @@ -1776,16 +1693,10 @@ export function createCodexSecurityServer(): McpServer { annotations: writingAnnotations, _meta: appMeta, }, - async ({ occurrenceId, requestId, expectedVersion, action, actionToken }) => + async (input) => scanActionResult( - await workbench("request-finding-remediation-action", { - occurrenceId, - requestId, - expectedVersion: String(expectedVersion), - action, - actionToken, - }), - `Queued the local Codex Security finding remediation ${action} request.`, + await workbench("request-finding-remediation-action", input), + `Queued the local Codex Security finding remediation ${input.action} request.`, ), ); @@ -1837,11 +1748,8 @@ export function createCodexSecurityServer(): McpServer { annotations, _meta: appMeta, }, - async ({ occurrenceId, requestId, actionToken }) => - scanActionResult( - await workbench(command, { occurrenceId, requestId, actionToken }), - message, - ), + async (input) => + scanActionResult(await workbench(command, input), message), ); } @@ -1897,16 +1805,9 @@ export function createCodexSecurityServer(): McpServer { annotations: writingAnnotations, _meta: appMeta, }, - async ({ limit, offset, query, scanId, severity, status }) => + async (input) => scanActionResult( - await workbench("list-findings", { - scanId, - query, - severity, - status, - offset, - limit, - }), + await workbench("list-findings", input), "Loaded a local Codex Security findings page.", ), ); @@ -1967,51 +1868,23 @@ async function getWorkspace( })) as WorkspaceState; } -async function startPromptOnlyScan( - input: PromptOnlyScanInput, +async function startConversationScan( + input: ConversationScanInput, threadId: string, - modelSettings: { model?: string; reasoningEffort?: string } = {}, + extra: unknown, ): Promise { - const { mode, targetPath, scope, targetSummary, userContext, diffTarget } = - input; + const prompt = "mode" in input ? input : undefined; return startWithValidation( - "start-prompt-only-scan", - { - threadId, - targetPath, - scope, - mode, - ...modelSettings, - targetSummary, - userContextStdin: Boolean(userContext), - ...diffTargetFields(diffTarget), - scanRoot: await scanRoot(), - }, - input.projectConfigPath, - userContext, - ); -} - -async function startHeadlessStandardScan( - input: { - targetPath: string; - scope?: string; - targetSummary?: string; - userContext?: string; - projectConfigPath?: string; - }, - threadId: string, - modelSettings: { model?: string; reasoningEffort?: string } = {}, -): Promise { - return startWithValidation( - "start-headless-standard-scan", + prompt ? "start-prompt-only-scan" : "start-headless-standard-scan", { threadId, targetPath: input.targetPath, scope: input.scope ?? ".", - ...modelSettings, + mode: prompt?.mode, + ...codexModelSettingsFromExtra(extra), targetSummary: input.targetSummary || undefined, userContextStdin: Boolean(input.userContext), + ...diffTargetFields(prompt?.diffTarget), scanRoot: await scanRoot(), }, input.projectConfigPath, diff --git a/plugins/codex-security/mcp-app/src/artifact-schema-loader.ts b/plugins/codex-security/mcp-app/src/artifact-schema-loader.ts index e3895733a..eaa3baf02 100644 --- a/plugins/codex-security/mcp-app/src/artifact-schema-loader.ts +++ b/plugins/codex-security/mcp-app/src/artifact-schema-loader.ts @@ -1,69 +1,46 @@ import * as z from "zod/v4"; - -export type ArtifactSchemaObject = Record; +import { isRecord } from "./record.js"; /** Project a native contract for tools/list while preserving its validator and type. */ export function projectArtifactToolSchema( schema: Schema, ): Schema { - return schema.meta( - modelFacingSchema(z.toJSONSchema(schema, { io: "input" })), - ); + // Zod exports fresh JSON. Copy the root to omit its non-enumerable ~standard. + const declaration = { ...z.toJSONSchema(schema, { io: "input" }) }; + hideForbiddenProperties(declaration); + return schema.meta(declaration); } -/** Keep forbidden fields out of native tool declarations without allowing them. */ -function modelFacingSchema(schema: ArtifactSchemaObject): ArtifactSchemaObject { - function visit(value: unknown): unknown { - if (Array.isArray(value)) return value.map(visit); - if (!value || typeof value !== "object") return value; - const object = Object.fromEntries( - Object.entries(value).map(([key, child]) => [ - key, - ["const", "enum", "default", "examples"].includes(key) - ? child - : visit(child), - ]), - ); - const properties = object.properties; - if ( - !properties || - typeof properties !== "object" || - Array.isArray(properties) - ) - return object; - const forbidden = Object.entries(properties) - .filter(([, property]) => forbiddenProperty(property)) - .map(([name]) => name); - if (forbidden.length === 0) return object; - - // Zod renders false properties as {not:{}}, which the native declaration - // projects as optional unknown fields. Exclude their names instead. This - // is equivalent JSON Schema; the original validator remains unchanged. - object.properties = Object.fromEntries( - Object.entries(properties).filter( - ([, property]) => !forbiddenProperty(property), - ), - ); - const names = { not: { enum: forbidden } }; - object.propertyNames = - object.propertyNames === undefined - ? names - : { allOf: [object.propertyNames, names] }; - return object; +function hideForbiddenProperties(value: unknown): void { + if (Array.isArray(value)) return value.forEach(hideForbiddenProperties); + if (!isRecord(value)) return; + for (const [key, child] of Object.entries(value)) { + if (!["const", "enum", "default", "examples"].includes(key)) + hideForbiddenProperties(child); } - return visit(schema) as ArtifactSchemaObject; + + // Native tool declarations treat Zod's {not:{}} as an optional unknown field. + // Forbid the name without advertising the property. + const properties = value.properties; + if (!isRecord(properties)) return; + const forbidden = Object.keys(properties).filter((key) => + forbiddenProperty(properties[key]), + ); + if (!forbidden.length) return; + for (const key of forbidden) delete properties[key]; + const names = { not: { enum: forbidden } }; + value.propertyNames = + value.propertyNames === undefined + ? names + : { allOf: [value.propertyNames, names] }; } -function forbiddenProperty(property: unknown): boolean { - if (property === false) return true; - if (!property || typeof property !== "object" || Array.isArray(property)) - return false; - const not = (property as ArtifactSchemaObject).not; +export function forbiddenProperty(value: unknown): boolean { return ( - Object.keys(property).length === 1 && - not !== null && - typeof not === "object" && - !Array.isArray(not) && - Object.keys(not).length === 0 + value === false || + (isRecord(value) && + isRecord(value.not) && + Object.keys(value).length === 1 && + Object.keys(value.not).length === 0) ); } diff --git a/plugins/codex-security/mcp-app/src/server/handoff-tools.ts b/plugins/codex-security/mcp-app/src/server/handoff-tools.ts index f5d6f945d..b1afd68ba 100644 --- a/plugins/codex-security/mcp-app/src/server/handoff-tools.ts +++ b/plugins/codex-security/mcp-app/src/server/handoff-tools.ts @@ -86,17 +86,12 @@ export function registerScanHandoffTools( annotations: writingAnnotations, _meta: appMeta, }, - async (input: z.infer) => { - const arguments_ = workbenchArgs(command, { - scanId: input.scanId, - claimToken: input.claimToken, - takeOverStale: "takeOverStale" in input && input.takeOverStale, - threadId: "threadId" in input ? input.threadId : undefined, - }); - return workspaceResult( - (await runWorkbench(arguments_)) as HandoffWorkspaceState, - ); - }, + async (input: z.infer) => + workspaceResult( + (await runWorkbench( + workbenchArgs(command, input), + )) as HandoffWorkspaceState, + ), ); } } 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 a44366eae..e48edce1c 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 @@ -508,7 +508,7 @@ async function assertHeadlessStandardScanWorksWithoutUiCapability() { await headlessServer.initialize("codex-security-headless-smoke"); const withoutOwner = await headlessServer.callTool(2, { name: "start_codex_security_standard_scan", - arguments: { targetPath: target }, + arguments: { targetPath: target, threadId: ownerThread }, }); assert.equal(withoutOwner.result.isError, true); assert.equal(withoutOwner.result._meta, undefined); @@ -522,6 +522,9 @@ async function assertHeadlessStandardScanWorksWithoutUiCapability() { arguments: { targetPath: target, userContext: headlessContext, + mode: "diff", + threadId: "untrusted-thread", + model: "untrusted-model", }, _meta: { "openai/threadId": ownerThread, @@ -2256,7 +2259,11 @@ try { ].entries()) { const claimedHandoff = await testServer.callSuccessfulTool(200200 + index, { name, - arguments: { claimToken: handoffClaimToken, scanId }, + arguments: { + claimToken: handoffClaimToken, + scanId, + threadId: "untrusted-thread", + }, }); assert.equal( claimedHandoff.structuredContent.workspace.results.handoffClaimToken, @@ -3367,6 +3374,7 @@ with sqlite3.connect(sys.argv[1]) as connection: query: "SRC/A.PY", severity: "high", status: "open", + repository: "--unexpected-filter", targetId: indexedFinding.targetId, }, }); @@ -3442,7 +3450,11 @@ with sqlite3.connect(sys.argv[1]) as connection: for (const operation of [ { name: "update_codex_security_scan_progress", - arguments: { phase: "discovery" }, + arguments: { + phase: "discovery", + modelThreadId: "fixture-rotated-recovery-thread", + claimToken: rotatedFallbackClaimToken, + }, }, { name: "complete_codex_security_scan", arguments: {} }, { diff --git a/plugins/codex-security/scripts/workbench/retained_coverage.py b/plugins/codex-security/scripts/workbench/retained_coverage.py index 6a5993246..34ee11ac6 100644 --- a/plugins/codex-security/scripts/workbench/retained_coverage.py +++ b/plugins/codex-security/scripts/workbench/retained_coverage.py @@ -1650,10 +1650,7 @@ def merge_saved_results( represented_history.setdefault(retained_key, set()).add( _digest(_finding_content(retained)) ) - previous_key = represented.get(retained_key) - if retained_key not in represented: - represented[retained_key] = canonical_key - elif previous_key != canonical_key: + if represented.setdefault(retained_key, canonical_key) != canonical_key: # Ambiguous history cannot suppress an independent source. represented[retained_key] = None originals = finding["provenance"].get("sourceFindings", []) @@ -1667,13 +1664,11 @@ def merge_saved_results( candidate_id, original["finding"], ) - previous_key = represented_candidates.get(candidate_key) - if candidate_key not in represented_candidates: - represented_candidates[candidate_key] = canonical_key - elif previous_key != canonical_key: - # Candidate ids are only authoritative within one - # logical worker. Multiple canonical owners make - # that worker-local identity ambiguous. + # Candidate IDs are authoritative only within one worker. + owner_key = represented_candidates.setdefault( + candidate_key, canonical_key + ) + if owner_key != canonical_key: represented_candidates[candidate_key] = None represented_candidate_history.setdefault(candidate_key, set()).add( _digest(_finding_content(original["finding"])) @@ -2163,13 +2158,12 @@ def merge_saved_results( destinations = set() for value in group["rows"]: history_key = _finding_key(value) - if _digest(_finding_content(value)) in represented_history.get(history_key, set()): + content_digest = _digest(_finding_content(value)) + if content_digest in represented_history.get(history_key, ()): destinations.add(represented.get(history_key)) elif group["owner"] and (candidate_id := finding_candidate_id(value)): candidate_key = _worker_candidate_key(group["owner"], candidate_id, value) - if _digest(_finding_content(value)) in represented_candidate_history.get( - candidate_key, set() - ): + if content_digest in represented_candidate_history.get(candidate_key, ()): destinations.add(represented_candidates[candidate_key]) if len(destinations) == 1 and None not in destinations: group["parent_key"] = destinations.pop() @@ -2499,23 +2493,22 @@ def merge_saved_results( history_key = _finding_key(value) # A singleton key is not evidence that a new batch sibling was # absorbed. Only recorded content may reuse that historical edge. - if _digest(_finding_content(value)) not in represented_history.get( - history_key, set() - ): + content_digest = _digest(_finding_content(value)) + if content_digest not in represented_history.get(history_key, ()): history_key = key if history_key in represented: mapped_key = represented[history_key] - historical_contents = represented_history.get(history_key, set()) + historical_contents = represented_history.get(history_key, ()) elif worker_id and candidate_id: candidate_key = _worker_candidate_key(worker_id, candidate_id, finding) mapped_key = represented_candidates.get(candidate_key) - historical_contents = represented_candidate_history.get(candidate_key, set()) + historical_contents = represented_candidate_history.get(candidate_key, ()) else: mapped_key = None - historical_contents = set() + historical_contents = () if mapped_key is not None: key = mapped_key - represented_by_parent = _digest(_finding_content(value)) in historical_contents + represented_by_parent = content_digest in historical_contents if key in finding_positions: position, retained_group = finding_positions[key] retained = findings[position] @@ -2739,20 +2732,7 @@ def merge_saved_results( if draft.get("complete") is not False or relative in selected_observations }, ) - replaced_rows = { - "surfaces": replaced_surfaces, - "deferred": { - id(row) - for relative, _, owner in all_sources - for row in deferred_rows[relative] - if isinstance(row, dict) - and isinstance(identity := row.get("id"), str) - and (key := record_key("deferred", owner, row)) not in candidate_ids - and key not in ambiguous_deferred - and (updated := accepted_deferred_orders.get(key)) is not None - and updated > candidate_order(relative, key[0], row) - }, - } + replaced_rows = {"surfaces": replaced_surfaces, "deferred": replaced_deferred} for field, replaced in replaced_rows.items(): if parent and isinstance(coverage.get(field), list): previous = parent["reviewState"].get(field, []) diff --git a/plugins/codex-security/scripts/workbench_native_indexes.py b/plugins/codex-security/scripts/workbench_native_indexes.py index 195f4af3f..6389a3e9c 100644 --- a/plugins/codex-security/scripts/workbench_native_indexes.py +++ b/plugins/codex-security/scripts/workbench_native_indexes.py @@ -19,11 +19,7 @@ from workbench_constants import ( FINDINGS_PAGE_MAX, PRIMARY_FINDING_LOCATION_SQL, ) -from workbench_target_state import ( - RepositoryIdentityCache, - RepositoryScanScope, - scan_repository_group, -) +from workbench_target_state import RepositoryIdentityCache, RepositoryScanScope from workbench_validation import bounded_output_text, timestamp_key @@ -137,31 +133,28 @@ def _indexed_findings( if legacy_generations is None: legacy_generations = _legacy_generations(connection, identities) - def repository_group(scan: sqlite3.Row | dict) -> tuple[str, str]: - identity = scan_repository_group(scan) - generation = legacy_generations.get(scan["target_id"]) - return ( - ("repository", generation) - if identity[0] == "target" and generation is not None - else identity - ) + def repository_group( + row: sqlite3.Row, prefix: str = "", *, infer_legacy: bool = True + ) -> tuple[str, str]: + target_id = row[prefix + "target_id"] + generation = row[prefix + "repository_generation"] + if generation is None and infer_legacy: + generation = legacy_generations.get(target_id) + return ("repository", generation) if generation is not None else ("target", target_id) target_filter, target_values = scope_sql("scans") before_filter, before_values = scope_sql("before_scans") after_filter, after_values = scope_sql("after_scans") - parents: dict[tuple[tuple[str, str], str], tuple[tuple[str, str], str]] = {} - - def group(identity: tuple[tuple[str, str], str]) -> tuple[tuple[str, str], str]: - while identity in parents: - identity = parents[identity] - return identity - - for match in connection.execute( + before_generation = generation_sql("before_scans") + after_generation = generation_sql("after_scans") + # Check the saved generations before inferring groups for legacy scans. + # If either generation is missing, only the same target can share a match. + matches = connection.execute( f""" SELECT before_scans.target_id AS before_target_id, after_scans.target_id AS after_target_id, - {generation_sql("before_scans")} AS before_generation, - {generation_sql("after_scans")} AS after_generation, + {before_generation} AS before_repository_generation, + {after_generation} AS after_repository_generation, before.finding_id AS before_finding_id, after.finding_id AS after_finding_id FROM scan_comparison_matches AS matches @@ -172,46 +165,19 @@ def _indexed_findings( JOIN scans AS after_scans ON after_scans.id = after.scan_id JOIN security_targets AS after_targets ON after_targets.id = after_scans.target_id WHERE {before_filter} AND {after_filter} + AND COALESCE({before_generation} = {after_generation}, + before_scans.target_id = after_scans.target_id) """, (*before_values, *after_values), - ): - if match["before_target_id"] != match["after_target_id"] and ( - match["before_generation"] is None or match["after_generation"] is None - ): - continue - before_repository = repository_group( - { - "target_id": match["before_target_id"], - "repository_generation": match["before_generation"], - } - ) - after_repository = repository_group( - { - "target_id": match["after_target_id"], - "repository_generation": match["after_generation"], - } - ) - if before_repository != after_repository and ( - match["before_target_id"] != match["after_target_id"] - or match["before_generation"] is not None - and match["after_generation"] is not None - ): - continue - before = group( - ( - before_repository, - match["before_finding_id"], - ) - ) - after = group( - ( - after_repository, - match["after_finding_id"], - ) - ) - if before != after: - parents[after] = before + ) + aliases = scan_history._finding_aliases( + ( + (repository_group(match, "before_"), match["before_finding_id"]), + (repository_group(match, "after_"), match["after_finding_id"]), + ) + for match in matches + ) completion_column = ( "scans.completion_sequence" if "completion_sequence" in identities.scan_columns else "NULL" ) @@ -265,15 +231,8 @@ def _indexed_findings( """, target_values, ): - grouped.setdefault( - group( - ( - repository_group(row), - row["finding_id"], - ) - ), - [], - ).append(row) + key = (repository_group(row), row["finding_id"]) + grouped.setdefault(aliases.get(key, key), []).append(row) # When a match group spans current targets, keep decisions within each verified # generation or legacy target in that group. Scoped queries already select their history. @@ -287,7 +246,7 @@ def _indexed_findings( continue partitions: dict[tuple[str, str], list[sqlite3.Row]] = {} for row in occurrences: - partitions.setdefault(scan_repository_group(row), []).append(row) + partitions.setdefault(repository_group(row, infer_legacy=False), []).append(row) finding_groups.extend(partitions.values()) findings = [] diff --git a/plugins/codex-security/scripts/workbench_scan_history.py b/plugins/codex-security/scripts/workbench_scan_history.py index 01488ee0c..0cc2bff1d 100644 --- a/plugins/codex-security/scripts/workbench_scan_history.py +++ b/plugins/codex-security/scripts/workbench_scan_history.py @@ -12,7 +12,7 @@ from fractions import Fraction from functools import cache from itertools import chain from pathlib import Path, PurePosixPath -from typing import Any, Callable +from typing import Any, Callable, TypeVar # Some plugin hosts launch Python with safe-path isolation enabled. sys.path.insert(0, str(Path(__file__).resolve().parent)) @@ -743,10 +743,15 @@ def _saved_finding_links(connection: sqlite3.Connection, scan_ids: set[str]) -> ] -def _finding_aliases(links: Iterable[tuple[str, str]]) -> dict[str, str]: - parents: dict[str, str] = {} +_FindingKey = TypeVar("_FindingKey") - def root(value: str) -> str: + +def _finding_aliases( + links: Iterable[tuple[_FindingKey, _FindingKey]], +) -> dict[_FindingKey, _FindingKey]: + parents: dict[_FindingKey, _FindingKey] = {} + + def root(value: _FindingKey) -> _FindingKey: parents.setdefault(value, value) while parents[value] != value: parents[value] = parents[parents[value]] @@ -755,7 +760,9 @@ def _finding_aliases(links: Iterable[tuple[str, str]]) -> dict[str, str]: for before_id, after_id in links: parents[root(after_id)] = root(before_id) - return {finding_id: root(finding_id) for finding_id in parents} + for finding in parents: + parents[finding] = root(finding) + return parents def _known_finding_groups(links: list[sqlite3.Row], scan_ids: set[str]) -> list[list[str]]: diff --git a/plugins/codex-security/scripts/workbench_target_state.py b/plugins/codex-security/scripts/workbench_target_state.py index db6a09cec..136ef27af 100644 --- a/plugins/codex-security/scripts/workbench_target_state.py +++ b/plugins/codex-security/scripts/workbench_target_state.py @@ -587,11 +587,6 @@ def scan_repository_generation(scan: sqlite3.Row | dict) -> str | None: return scan["repository_generation"] if "repository_generation" in scan.keys() else None -def scan_repository_group(scan: sqlite3.Row | dict) -> tuple[str, str]: - generation = scan_repository_generation(scan) - return ("repository", generation) if generation is not None else ("target", scan["target_id"]) - - @dataclass(frozen=True) class RepositoryScanScope: """A verified generation and, separately, its exact target's legacy scans.""" diff --git a/plugins/codex-security/tests/test_workbench_native_indexes.py b/plugins/codex-security/tests/test_workbench_native_indexes.py index d3b23e3c6..fcbf519e9 100644 --- a/plugins/codex-security/tests/test_workbench_native_indexes.py +++ b/plugins/codex-security/tests/test_workbench_native_indexes.py @@ -4,7 +4,6 @@ from __future__ import annotations import json import sqlite3 -import subprocess from datetime import datetime, timezone from pathlib import Path @@ -13,6 +12,7 @@ import test_workbench_scan_history as producer from workbench_test_support import ( create_saved_workspace, create_workspace, + get_scan, initialize_git_repository, run_workbench, save_workspace, @@ -59,13 +59,7 @@ def complete_scan( findings["findings"] = [] findings_path.write_text(json.dumps(findings)) if follow_up: - coverage_path = scan_dir / "coverage.json" - coverage = json.loads(coverage_path.read_text()) - coverage["surfaces"][0]["disposition"] = "needs_follow_up" - coverage["deferred"] = [ - {"id": "unreviewed-path", "reason": "Review incomplete", "paths": ["src/extract.py"]} - ] - coverage_path.write_text(json.dumps(coverage)) + producer.mark_incomplete_coverage(scan_dir) return scan_command(state_dir, "complete-scan", scan_id)["scan"] @@ -303,6 +297,38 @@ def test_repository_index_reports_latest_scan_open_findings_and_missing_checkout assert second["scanCount"] == 1 +def use_current_completion_times(state: Path, monkeypatch: pytest.MonkeyPatch) -> None: + original_write = producer.write_completed_contract + + def write_current_completion(scan_dir, scan_id, target, **values): + original_write(scan_dir, scan_id, target, **values) + path = scan_dir / "scan-manifest.json" + manifest = json.loads(path.read_text()) + with sqlite3.connect(state / "workbench.sqlite3") as connection: + started_at = connection.execute( + "SELECT started_at FROM scans WHERE id=?", (scan_id,) + ).fetchone()[0] + manifest["scan"]["startedAt"] = started_at + manifest["scan"]["completedAt"] = ( + datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + ) + path.write_text(json.dumps(manifest)) + + monkeypatch.setattr(producer, "write_completed_contract", write_current_completion) + + +def close_false_positive(state: Path, occurrence: str) -> None: + set_triage( + state, + occurrence, + "closed", + "--close-reason", + "false_positive", + "--note", + "Synthetic checked guard.", + ) + + @pytest.mark.parametrize("legacy", (False, True)) @pytest.mark.parametrize("same_target", (False, True)) def test_native_completion_keeps_same_target_legacy_triage_without_matching( @@ -318,7 +344,7 @@ def test_native_completion_keeps_same_target_legacy_triage_without_matching( identity_anchor="same-stable-finding", target_revision=revision, ) - first = run_workbench(state, "get-scan", "--scan-id", first["scanId"])["scan"] + first = get_scan(state, first["scanId"])["scan"] with sqlite3.connect(state / "workbench.sqlite3") as connection: assert ( connection.execute( @@ -331,18 +357,7 @@ def test_native_completion_keeps_same_target_legacy_triage_without_matching( "UPDATE scans SET repository_generation = NULL WHERE id = ?", (first["scanId"],), ) - run_workbench( - state, - "set-finding-triage", - "--occurrence-id", - str(first["findings"][0]["occurrenceId"]), - "--status", - "closed", - "--close-reason", - "false_positive", - "--note", - "Synthetic checked guard.", - ) + close_false_positive(state, str(first["findings"][0]["occurrenceId"])) next_target = repository if not same_target: next_target = tmp_path / "other" @@ -368,41 +383,20 @@ def test_legacy_linked_comparison_keeps_unbound_triage_target_local( tmp_path: Path, saved_comparison: bool ) -> None: state = tmp_path / "state" - repository = tmp_path / "repository" - revision = initialize_git_repository(repository) - linked = tmp_path / "linked" - subprocess.run( - ["git", "-C", str(repository), "worktree", "add", "-q", "--detach", str(linked)], - check=True, - ) + repository, linked, revision = producer.linked_checkouts(tmp_path) first = producer.create_cli_scan( state, tmp_path / "results", repository, target_revision=revision ) later = producer.create_cli_scan(state, tmp_path / "results", linked, target_revision=revision) - first_finding = run_workbench(state, "get-scan", "--scan-id", first["scanId"])["scan"][ - "findings" - ][0] - later_finding = run_workbench(state, "get-scan", "--scan-id", later["scanId"])["scan"][ - "findings" - ][0] + first_finding = get_scan(state, first["scanId"])["scan"]["findings"][0] + later_finding = get_scan(state, later["scanId"])["scan"]["findings"][0] assert first_finding["findingId"] != later_finding["findingId"] with sqlite3.connect(state / "workbench.sqlite3") as connection: connection.execute( "UPDATE scans SET repository_generation=NULL WHERE id IN (?,?)", (first["scanId"], later["scanId"]), ) - run_workbench( - state, - "set-finding-triage", - "--occurrence-id", - first_finding["occurrenceId"], - "--status", - "closed", - "--close-reason", - "false_positive", - "--note", - "Synthetic checked guard.", - ) + close_false_positive(state, first_finding["occurrenceId"]) if saved_comparison: match = producer.save_scan_matches( state, @@ -432,62 +426,21 @@ def test_sealed_legacy_recurrence_match_keeps_linked_scope_status( tmp_path, monkeypatch, legacy_first, saved_current_match ): state = tmp_path / "state" - repository = tmp_path / "repository" - linked = tmp_path / "linked" - revision = initialize_git_repository(repository) - subprocess.run( - ["git", "-C", str(repository), "worktree", "add", "-q", "--detach", str(linked)], check=True - ) - original_write = producer.write_completed_contract - - def write_current_completion(scan_dir, scan_id, target, **values): - original_write(scan_dir, scan_id, target, **values) - p = scan_dir / "scan-manifest.json" - manifest = json.loads(p.read_text()) - with sqlite3.connect(state / "workbench.sqlite3") as connection: - started_at = connection.execute( - "SELECT started_at FROM scans WHERE id=?", (scan_id,) - ).fetchone()[0] - manifest["scan"]["startedAt"] = started_at - manifest["scan"]["completedAt"] = ( - datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") - ) - p.write_text(json.dumps(manifest)) - - monkeypatch.setattr(producer, "write_completed_contract", write_current_completion) + repository, linked, revision = producer.linked_checkouts(tmp_path) + use_current_completion_times(state, monkeypatch) first = producer.create_cli_scan( state, tmp_path / "results", repository, target_revision=revision ) - first_finding = run_workbench(state, "get-scan", "--scan-id", first["scanId"])["scan"][ - "findings" - ][0] + first_finding = get_scan(state, first["scanId"])["scan"]["findings"][0] if legacy_first: - with sqlite3.connect(state / "workbench.sqlite3") as connection: - connection.execute( - "UPDATE scans SET repository_generation=NULL WHERE id=?", (first["scanId"],) - ) - run_workbench( - state, - "set-finding-triage", - "--occurrence-id", - first_finding["occurrenceId"], - "--status", - "closed", - "--close-reason", - "false_positive", - "--note", - "Synthetic checked guard.", - ) + producer.clear_scan_generation(state, first) + close_false_positive(state, first_finding["occurrenceId"]) current = producer.create_cli_scan( state, tmp_path / "results", repository, target_revision=revision ) - current_finding = run_workbench(state, "get-scan", "--scan-id", current["scanId"])["scan"][ - "findings" - ][0] + current_finding = get_scan(state, current["scanId"])["scan"]["findings"][0] later = producer.create_cli_scan(state, tmp_path / "results", linked, target_revision=revision) - later_finding = run_workbench(state, "get-scan", "--scan-id", later["scanId"])["scan"][ - "findings" - ][0] + later_finding = get_scan(state, later["scanId"])["scan"]["findings"][0] assert first_finding["findingId"] == current_finding["findingId"] assert first_finding["findingId"] != later_finding["findingId"] assert current_finding["triage"]["status"] == later_finding["triage"]["status"] == "open" @@ -531,69 +484,20 @@ def test_saved_legacy_alias_survives_current_linked_match( tmp_path, monkeypatch, saved_legacy_alias, saved_current_match ): state = tmp_path / "state" - repository = tmp_path / "repository" - linked = tmp_path / "linked" - revision = initialize_git_repository(repository) - subprocess.run( - ["git", "-C", str(repository), "worktree", "add", "-q", "--detach", str(linked)], check=True - ) - original_write = producer.write_completed_contract + repository, linked, revision = producer.linked_checkouts(tmp_path) + use_current_completion_times(state, monkeypatch) - def write_current_completion(scan_dir, scan_id, target, **values): - original_write(scan_dir, scan_id, target, **values) - p = scan_dir / "scan-manifest.json" - manifest = json.loads(p.read_text()) - with sqlite3.connect(state / "workbench.sqlite3") as connection: - started_at = connection.execute( - "SELECT started_at FROM scans WHERE id=?", (scan_id,) - ).fetchone()[0] - manifest["scan"]["startedAt"] = started_at - manifest["scan"]["completedAt"] = ( - datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + def scan_with_finding(target: Path, anchor: str): + scan = producer.create_cli_scan( + state, tmp_path / "results", target, target_revision=revision, identity_anchor=anchor ) - p.write_text(json.dumps(manifest)) + return scan, get_scan(state, scan["scanId"])["scan"]["findings"][0] - monkeypatch.setattr(producer, "write_completed_contract", write_current_completion) - first = producer.create_cli_scan( - state, - tmp_path / "results", - repository, - target_revision=revision, - identity_anchor="synthetic-first-control", - ) - first_finding = run_workbench(state, "get-scan", "--scan-id", first["scanId"])["scan"][ - "findings" - ][0] - with sqlite3.connect(state / "workbench.sqlite3") as connection: - connection.execute( - "UPDATE scans SET repository_generation=NULL WHERE id=?", (first["scanId"],) - ) - run_workbench( - state, - "set-finding-triage", - "--occurrence-id", - first_finding["occurrenceId"], - "--status", - "closed", - "--close-reason", - "false_positive", - "--note", - "Synthetic checked guard.", - ) - second = producer.create_cli_scan( - state, - tmp_path / "results", - repository, - target_revision=revision, - identity_anchor="synthetic-second-control", - ) - second_finding = run_workbench(state, "get-scan", "--scan-id", second["scanId"])["scan"][ - "findings" - ][0] - with sqlite3.connect(state / "workbench.sqlite3") as connection: - connection.execute( - "UPDATE scans SET repository_generation=NULL WHERE id=?", (second["scanId"],) - ) + first, first_finding = scan_with_finding(repository, "synthetic-first-control") + producer.clear_scan_generation(state, first) + close_false_positive(state, first_finding["occurrenceId"]) + second, second_finding = scan_with_finding(repository, "synthetic-second-control") + producer.clear_scan_generation(state, second) assert first_finding["findingId"] != second_finding["findingId"] if saved_legacy_alias: result = producer.save_scan_matches( @@ -603,26 +507,8 @@ def test_saved_legacy_alias_survives_current_linked_match( producer.confirmed_match(first_finding["occurrenceId"], second_finding["occurrenceId"]), ) assert result["summary"]["persisting"] == 1 - current = producer.create_cli_scan( - state, - tmp_path / "results", - repository, - target_revision=revision, - identity_anchor="synthetic-second-control", - ) - current_finding = run_workbench(state, "get-scan", "--scan-id", current["scanId"])["scan"][ - "findings" - ][0] - later = producer.create_cli_scan( - state, - tmp_path / "results", - linked, - target_revision=revision, - identity_anchor="synthetic-second-control", - ) - later_finding = run_workbench(state, "get-scan", "--scan-id", later["scanId"])["scan"][ - "findings" - ][0] + current, current_finding = scan_with_finding(repository, "synthetic-second-control") + later, later_finding = scan_with_finding(linked, "synthetic-second-control") assert second_finding["findingId"] == current_finding["findingId"] assert current_finding["findingId"] != later_finding["findingId"] if saved_current_match: diff --git a/plugins/codex-security/tests/test_workbench_scan_history.py b/plugins/codex-security/tests/test_workbench_scan_history.py index 0ae4dfb94..0b124489d 100644 --- a/plugins/codex-security/tests/test_workbench_scan_history.py +++ b/plugins/codex-security/tests/test_workbench_scan_history.py @@ -47,7 +47,7 @@ def test_rename_persists_without_changing_scan_results( ) -> None: state_dir, repository = empty_history_paths(tmp_path) scan = create_cli_scan(state_dir, tmp_path / "scans", repository, complete=complete) - before = run_workbench(state_dir, "get-scan", "--scan-id", scan["scanId"])["scan"] + before = get_scan(state_dir, scan["scanId"])["scan"] if upgrade: with sqlite3.connect(state_dir / "workbench.sqlite3") as connection: connection.execute("ALTER TABLE scans DROP COLUMN name") @@ -58,7 +58,7 @@ def test_rename_persists_without_changing_scan_results( ) assert renamed == {"scanId": scan["scanId"], "name": "Release audit"} - after = run_workbench(state_dir, "get-scan", "--scan-id", scan["scanId"])["scan"] + after = get_scan(state_dir, scan["scanId"])["scan"] assert get_scan(state_dir, scan["scanId"][:8], "--progress-only") == { "scan": {"progress": after["progress"]} } @@ -78,7 +78,7 @@ def test_rename_rejects_blank_names(tmp_path: Path) -> None: ) assert blank["returncode"] != 0 assert "Scan name cannot be empty" in blank["stderr"] - assert run_workbench(state_dir, "get-scan", "--scan-id", scan["scanId"])["scan"]["name"] is None + assert get_scan(state_dir, scan["scanId"])["scan"]["name"] is None def test_scan_history_search_casefolds_displayed_fields(tmp_path: Path) -> None: @@ -132,6 +132,49 @@ def empty_history_paths(tmp_path: Path) -> tuple[Path, Path]: return tmp_path / "state", repository +def mark_incomplete_coverage(scan_dir: Path) -> None: + coverage_path = scan_dir / "coverage.json" + coverage = json.loads(coverage_path.read_text()) + coverage["surfaces"][0]["disposition"] = "needs_follow_up" + coverage["deferred"] = [ + {"id": "unreviewed-path", "reason": "Review incomplete", "paths": ["src/extract.py"]} + ] + coverage_path.write_text(json.dumps(coverage)) + + +def initialize_existing_repository(repository: Path) -> str: + git = ["git", "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test"] + subprocess.run(["git", "init", "-q"], cwd=repository, check=True) + subprocess.run([*git, "add", "."], cwd=repository, check=True) + subprocess.run([*git, "commit", "-qm", "Initialize repository"], cwd=repository, check=True) + return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repository, text=True).strip() + + +def clone_with_origin(repository: Path, clone: Path, *, same_origin: bool) -> None: + origin = "https://example.test/synthetic/project.git" + subprocess.run(["git", "remote", "add", "origin", origin], cwd=repository, check=True) + subprocess.run(["git", "clone", "-q", str(repository), str(clone)], check=True) + clone_origin = origin if same_origin else "https://example.test/synthetic/other.git" + subprocess.run(["git", "remote", "set-url", "origin", clone_origin], cwd=clone, check=True) + + +def linked_checkouts(tmp_path: Path) -> tuple[Path, Path, str]: + repository = tmp_path / "repository" + linked = tmp_path / "linked" + revision = initialize_git_repository(repository) + subprocess.run( + ["git", "-C", str(repository), "worktree", "add", "-q", "--detach", str(linked)], check=True + ) + return repository, linked, revision + + +def clear_scan_generation(state: Path, scan: dict[str, Any]) -> None: + with sqlite3.connect(state / "workbench.sqlite3") as connection: + connection.execute( + "UPDATE scans SET repository_generation = NULL WHERE id = ?", (scan["scanId"],) + ) + + def compare_scan_pair( state_dir: Path, before: dict[str, Any], @@ -268,13 +311,7 @@ def create_cli_scan( findings["findings"].append(additional) findings_path.write_text(json.dumps(findings)) if follow_up: - coverage_path = scan_dir / "coverage.json" - coverage = json.loads(coverage_path.read_text()) - coverage["surfaces"][0]["disposition"] = "needs_follow_up" - coverage["deferred"] = [ - {"id": "unreviewed-path", "reason": "Review incomplete", "paths": ["src/extract.py"]} - ] - coverage_path.write_text(json.dumps(coverage)) + mark_incomplete_coverage(scan_dir) subprocess.run([sys.executable, str(FINALIZER), "--scan-dir", str(scan_dir)], check=True) completion = ["complete-scan", "--scan-id", launched["scanId"]] if cost is not None: @@ -2180,10 +2217,7 @@ def test_history_repair_matches_legacy_generation_in_owned_checkout(tmp_path: Pa revision = initialize_git_repository(repository) first = create_cli_scan(state, tmp_path / "results", repository, target_revision=revision) second = create_cli_scan(state, tmp_path / "results", repository, target_revision=revision) - with sqlite3.connect(state / "workbench.sqlite3") as connection: - connection.execute( - "UPDATE scans SET repository_generation = NULL WHERE id = ?", (first["scanId"],) - ) + clear_scan_generation(state, first) pending = run_workbench(state, "list-unmatched-scan-pairs", "--repository", str(repository)) assert len(pending["batches"]) == 1 assert pending["batches"][0]["afterScanId"] == second["scanId"] @@ -2211,20 +2245,14 @@ def test_history_repair_keeps_triage_across_legacy_match( target_revision=revision, identity_anchor="synthetic-current-anchor", ) - with sqlite3.connect(state / "workbench.sqlite3") as connection: - connection.execute( - "UPDATE scans SET repository_generation = NULL WHERE id = ?", (first["scanId"],) - ) + clear_scan_generation(state, first) inputs = compare_scan_pair(state, first, second, "--include-matching-inputs")["matchingInputs"] prior = inputs["before"][0]["occurrenceId"] current = inputs["after"][0]["occurrenceId"] save_scan_matches(state, first, second, confirmed_match(prior, current)) - run_workbench( + set_triage( state, - "set-finding-triage", - "--occurrence-id", prior, - "--status", "closed", "--close-reason", "false_positive", @@ -2341,17 +2369,9 @@ def test_history_repair_rebinds_only_unscanned_workspace(tmp_path: Path) -> None def test_history_repair_counts_only_each_worktrees_legacy_findings(tmp_path: Path) -> None: state = tmp_path / "state" - repository = tmp_path / "repository" - linked = tmp_path / "linked" - revision = initialize_git_repository(repository) - subprocess.run( - ["git", "-C", str(repository), "worktree", "add", "-q", "--detach", str(linked)], check=True - ) + repository, linked, revision = linked_checkouts(tmp_path) legacy = create_cli_scan(state, tmp_path / "results", repository, target_revision=revision) - with sqlite3.connect(state / "workbench.sqlite3") as connection: - connection.execute( - "UPDATE scans SET repository_generation = NULL WHERE id = ?", (legacy["scanId"],) - ) + clear_scan_generation(state, legacy) create_cli_scan(state, tmp_path / "results", linked, target_revision=revision, finding=False) counts = { row["targetPath"]: row["openFindingsCount"] @@ -2550,29 +2570,7 @@ def test_portable_identity_allows_git_initialization_after_plain_directory_histo ).fetchone()[0] == "unversioned" ) - subprocess.run(["git", "init", "-q"], cwd=repository, check=True) - subprocess.run( - ["git", "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "add", "."], - cwd=repository, - check=True, - ) - subprocess.run( - [ - "git", - "-c", - "user.name=Fixture", - "-c", - "user.email=fixture@example.test", - "commit", - "-qm", - "Initialize repository", - ], - cwd=repository, - check=True, - ) - revision = subprocess.check_output( - ["git", "rev-parse", "HEAD"], cwd=repository, text=True - ).strip() + revision = initialize_existing_repository(repository) after = create_cli_scan( state, tmp_path / "results", repository, mode=mode, target_revision=revision ) @@ -2591,26 +2589,8 @@ def test_portable_identity_explicit_clone_comparison_without_birth_timestamps( repository = tmp_path / "repository" revision = initialize_git_repository(repository) - subprocess.run( - ["git", "remote", "add", "origin", "https://example.test/synthetic/project.git"], - cwd=repository, - check=True, - ) clone = tmp_path / "clone" - subprocess.run(["git", "clone", "-q", str(repository), str(clone)], check=True) - subprocess.run( - [ - "git", - "remote", - "set-url", - "origin", - "https://example.test/synthetic/project.git" - if same_origin - else "https://example.test/synthetic/other.git", - ], - cwd=clone, - check=True, - ) + clone_with_origin(repository, clone, same_origin=same_origin) state = tmp_path / "state" before = create_cli_scan(state, tmp_path / "results", repository, target_revision=revision) after = create_cli_scan(state, tmp_path / "results", clone, target_revision=revision) @@ -2694,29 +2674,7 @@ def test_legacy_aliases_restore_mixed_plain_and_git_history(tmp_path: Path, mode (repository / "README.md").write_text("fixture\n") state = tmp_path / "state" before = create_cli_scan(state, tmp_path / "results", repository, mode=mode) - subprocess.run(["git", "init", "-q"], cwd=repository, check=True) - subprocess.run( - ["git", "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "add", "."], - cwd=repository, - check=True, - ) - subprocess.run( - [ - "git", - "-c", - "user.name=Fixture", - "-c", - "user.email=fixture@example.test", - "commit", - "-qm", - "Initialize repository", - ], - cwd=repository, - check=True, - ) - revision = subprocess.check_output( - ["git", "rev-parse", "HEAD"], cwd=repository, text=True - ).strip() + revision = initialize_existing_repository(repository) after = create_cli_scan( state, tmp_path / "results", repository, mode=mode, target_revision=revision ) @@ -2743,26 +2701,8 @@ def test_legacy_aliases_explicit_comparison_with_mixed_birth_support( repository = tmp_path / "repository" revision = initialize_git_repository(repository) - subprocess.run( - ["git", "remote", "add", "origin", "https://example.test/synthetic/project.git"], - cwd=repository, - check=True, - ) clone = tmp_path / "clone" - subprocess.run(["git", "clone", "-q", str(repository), str(clone)], check=True) - subprocess.run( - [ - "git", - "remote", - "set-url", - "origin", - "https://example.test/synthetic/project.git" - if same_origin - else "https://example.test/synthetic/other.git", - ], - cwd=clone, - check=True, - ) + clone_with_origin(repository, clone, same_origin=same_origin) state = tmp_path / "state" before = create_cli_scan(state, tmp_path / "results", repository, target_revision=revision) after = create_cli_scan(state, tmp_path / "results", clone, target_revision=revision) @@ -3189,12 +3129,7 @@ def test_repository_generation_migration_is_atomic_and_preserves_shared_history( assert git is not None # Keep Git available when the linked checkout below is temporarily absent. monkeypatch.setenv("CODEX_SECURITY_GIT", str(Path(git).absolute())) - repository = tmp_path / "repository" - revision = initialize_git_repository(repository) - linked = tmp_path / "linked" - subprocess.run( - ["git", "-C", str(repository), "worktree", "add", "-q", "--detach", str(linked)], check=True - ) + repository, linked, revision = linked_checkouts(tmp_path) state = tmp_path / "state" first = create_cli_scan(state, tmp_path / "results", repository, target_revision=revision) second = create_cli_scan(state, tmp_path / "results", linked, target_revision=revision) @@ -3321,13 +3256,7 @@ def test_repository_generation_returns_after_offline_migration( import workbench_db as workbench import workbench_target_state as target_state - repository = tmp_path / "repository" - revision = initialize_git_repository(repository) - linked = tmp_path / "linked" - subprocess.run( - ["git", "-C", str(repository), "worktree", "add", "-q", "--detach", str(linked)], - check=True, - ) + repository, linked, revision = linked_checkouts(tmp_path) state = tmp_path / "state" scan = create_cli_scan(state, tmp_path / "results", repository, target_revision=revision) if alias_binding == "legacy":