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(workbench): preserve finding queries and timestamp order (#1505)

mldangelo-oaic0c7f1223440
diff --git a/plugins/codex-security/mcp-app/src/workbench/dashboard.ts b/plugins/codex-security/mcp-app/src/workbench/dashboard.ts
index f6025aa33..006486981 100644
--- a/plugins/codex-security/mcp-app/src/workbench/dashboard.ts
+++ b/plugins/codex-security/mcp-app/src/workbench/dashboard.ts
@@ -1,12 +1,12 @@
import type { DatabaseSync, SQLOutputValue } from "node:sqlite";
import { parseJson } from "../helpers/json";
-import { requireSqliteText } from "./database";
+import { requireSqliteText, timestampOrder } from "./database";
import { listDedupeGroups } from "./duplicates";
import { transaction } from "./transaction";
const records = {
findings: `
- SELECT findings.id, json_extract(dashboard_title(details_json), '$') AS title,
+ SELECT findings.id, details_json -> '$.title' AS title,
COALESCE(repositories.ids, '[]') AS repositoryIds,
json_extract(details_json, '$.severity.level') AS severity,
findings.created_at AS createdAt, findings.updated_at AS updatedAt
@@ -16,7 +16,7 @@ const records = {
) AS repositories ON repositories.finding_id = findings.id
WHERE details_json IS NOT NULL`,
groups: `
- SELECT groups.id, groups.id AS title,
+ SELECT groups.id, json_quote(groups.id) AS title,
(SELECT json_group_array(DISTINCT repository_id)
FROM finding_dedupe_group_members AS members
JOIN finding_repositories ON finding_repositories.finding_id = members.finding_id
@@ -29,7 +29,7 @@ const records = {
const sorts = {
activity: "records.updatedAt",
newest: "records.createdAt",
- title: "dashboard_lower(json_quote(records.title))",
+ title: "dashboard_lower(records.title)",
repository: "repository_label(records.repositoryIds)",
severity:
"CASE records.severity WHEN 'informational' THEN 0 WHEN 'low' THEN 1 " +
@@ -101,16 +101,16 @@ function detail(
export function dashboard(database: DatabaseSync, query: DashboardQuery) {
requireSqliteText([query.query, query.repository, query.id]);
// JSON preserves text across Node 22 SQLite result and callback boundaries.
- database.function("dashboard_title", { deterministic: true }, (value) =>
- JSON.stringify(
- (JSON.parse(value as string).title as string).toWellFormed(),
- ),
- );
database.function("dashboard_lower", { deterministic: true }, (value) =>
(JSON.parse(value as string) as string).toLowerCase(),
);
- database.function("dashboard_upper", { deterministic: true }, (value) =>
- (JSON.parse(value as string) as string).toUpperCase(),
+ const search = query.query?.toUpperCase() ?? "";
+ database.function("dashboard_contains", { deterministic: true }, (value) =>
+ Number(
+ ((JSON.parse(value as string) as string | null) ?? "")
+ .toUpperCase()
+ .includes(search),
+ ),
);
database.function("repository_label", { deterministic: true }, (value) =>
repositoryIds(JSON.parse(value as string))
@@ -120,11 +120,12 @@ export function dashboard(database: DatabaseSync, query: DashboardQuery) {
const clauses: string[] = [];
const values: string[] = [];
if (query.query) {
- const columns = ["id", "title", "repositoryIds"];
+ const columns = ["json_quote(records.id)", "records.title"];
clauses.push(
- `(${columns.map((column) => `instr(dashboard_upper(json_quote(COALESCE(records.${column}, ''))), ?) > 0`).join(" OR ")})`,
+ `(${columns.map((column) => `dashboard_contains(${column})`).join(" OR ")} OR
+ EXISTS (SELECT 1 FROM json_each(records.repositoryIds)
+ WHERE dashboard_contains(json_quote(value))))`,
);
- values.push(...columns.map(() => query.query!.toUpperCase()));
}
if (query.repository) {
clauses.push(
@@ -133,14 +134,19 @@ export function dashboard(database: DatabaseSync, query: DashboardQuery) {
values.push(query.repository);
}
const where = clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
- const direction = { asc: "ASC", desc: "DESC" }[query.direction ?? "desc"];
- let order = `${sorts[query.sort]} ${direction}`;
+ const direction = ({ asc: "ASC", desc: "DESC" } as const)[
+ query.direction ?? "desc"
+ ];
+ let order =
+ query.sort === "activity" || query.sort === "newest"
+ ? timestampOrder(database, sorts[query.sort], direction)
+ : `${sorts[query.sort]} ${direction}`;
if (query.view === "findings" && query.sort === "activity")
order += `, ${sorts.severity} DESC`;
order += ", records.id";
const source = records[query.view];
const field = query.view === "findings" ? "severity" : "memberCount";
- const projection = `json_object('id', records.id, 'title', records.title,
+ const projection = `json_object('id', records.id, 'title', json(records.title),
'repositoryIds', json(repositoryIds), 'createdAt', createdAt, 'updatedAt', updatedAt,
'${field}', ${field}) AS item`;
return transaction(database, "BEGIN", () => {
diff --git a/plugins/codex-security/mcp-app/src/workbench/database.ts b/plugins/codex-security/mcp-app/src/workbench/database.ts
index 49bcf82e4..3fd5ccdce 100644
--- a/plugins/codex-security/mcp-app/src/workbench/database.ts
+++ b/plugins/codex-security/mcp-app/src/workbench/database.ts
@@ -21,6 +21,28 @@ export function requireSqliteText(
throw new TypeError("SQLite text keys must contain valid Unicode.");
}
+export function timestampOrder(
+ database: DatabaseSync,
+ column: string,
+ direction: "ASC" | "DESC" = "ASC",
+): string {
+ database.function("timestamp_seconds", { deterministic: true }, (value) => {
+ const timestamp = value as string;
+ const zone = timestamp.slice(-6);
+ const minutes = /[Zz]$/u.test(timestamp)
+ ? 0
+ : (Number(zone.slice(1, 3)) * 60 + Number(zone.slice(4))) *
+ (zone[0] === "-" ? -1 : 1);
+ // Keep Python's accepted offset arithmetic separate from date parsing.
+ return Date.parse(timestamp.slice(0, 19) + "Z") - minutes * 60_000;
+ });
+ // Fractional digits retain their precision; trailing zeros denote the same instant.
+ database.function("timestamp_fraction", { deterministic: true }, (value) =>
+ ((value as string).match(/\.(\d+)/u)?.[1] ?? "").replace(/0+$/u, ""),
+ );
+ return `timestamp_seconds(${column}) ${direction}, timestamp_fraction(${column}) ${direction}`;
+}
+
function createStateDirectory(path: string): void {
if (process.platform !== "win32") path = path.replace(/\/+$/u, "") || "/";
const nativePath =
diff --git a/plugins/codex-security/mcp-app/src/workbench/duplicates.ts b/plugins/codex-security/mcp-app/src/workbench/duplicates.ts
index fe36efc91..6ada81bb1 100644
--- a/plugins/codex-security/mcp-app/src/workbench/duplicates.ts
+++ b/plugins/codex-security/mcp-app/src/workbench/duplicates.ts
@@ -3,7 +3,7 @@ import { isDeepStrictEqual } from "node:util";
import type { DatabaseSync } from "node:sqlite";
import { parseJson } from "../helpers/json";
import { transaction } from "./transaction";
-import { requireSqliteText } from "./database";
+import { requireSqliteText, timestampOrder } from "./database";
export interface DedupeGroup {
groupId: string;
@@ -63,7 +63,7 @@ export function findPotentialDuplicates(
JOIN findings ON findings.id = embeddings.finding_id
WHERE ${predicate}embeddings.model = (SELECT model FROM ${table} WHERE finding_id = ?)
AND embeddings.finding_id != ?
- ORDER BY findings.created_at, findings.id`,
+ ORDER BY ${timestampOrder(database, "findings.created_at")}, findings.id`,
);
const ranked: { id: string; similarity: number }[] = [];
try {
@@ -242,7 +242,7 @@ export function listDedupeGroups(database: DatabaseSync, findingId: string) {
JOIN finding_dedupe_groups AS groups ON groups.id = matched.group_id
JOIN finding_dedupe_group_members AS members ON members.group_id = groups.id
WHERE matched.finding_id = ?
- GROUP BY groups.id ORDER BY groups.created_at, groups.id
+ GROUP BY groups.id ORDER BY ${timestampOrder(database, "groups.created_at")}, groups.id
`);
return {
groups: rows
diff --git a/plugins/codex-security/mcp-app/src/workbench/findings.ts b/plugins/codex-security/mcp-app/src/workbench/findings.ts
index 77b5cb24b..ed785d94a 100644
--- a/plugins/codex-security/mcp-app/src/workbench/findings.ts
+++ b/plugins/codex-security/mcp-app/src/workbench/findings.ts
@@ -1,7 +1,7 @@
import type { DatabaseSync } from "node:sqlite";
import { isDeepStrictEqual } from "node:util";
import { parseJson, stringifyJson } from "../helpers/json";
-import { requireSqliteText } from "./database";
+import { requireSqliteText, timestampOrder } from "./database";
import { transaction } from "./transaction";
export interface Finding {
@@ -127,7 +127,7 @@ export function listStoredFindings(
const rows = database
.prepare(
`SELECT details_json FROM findings WHERE details_json IS NOT NULL
- ORDER BY created_at, id LIMIT ? OFFSET ?`,
+ ORDER BY ${timestampOrder(database, "created_at")}, id LIMIT ? OFFSET ?`,
)
.all(limit, offset);
const nextOffset = offset + rows.length;
diff --git a/plugins/codex-security/mcp-app/tests/test_workbench_dashboard.ts b/plugins/codex-security/mcp-app/tests/test_workbench_dashboard.ts
index 4dc6eb23b..661635830 100644
--- a/plugins/codex-security/mcp-app/tests/test_workbench_dashboard.ts
+++ b/plugins/codex-security/mcp-app/tests/test_workbench_dashboard.ts
@@ -167,6 +167,43 @@ test("dashboard preserves NUL text through display, filters, search, and sorting
assert.deepEqual(groups.detail?.group?.findingIds, [first, second]);
});
+test("dashboard searches decoded repository names in findings and groups", (t) => {
+ const db = database(t);
+ const names = [
+ "repo\\folder",
+ 'repo"quote',
+ "repo\0nul",
+ "repo\nline",
+ "répo/ΟΣ",
+ ];
+ names.forEach((name, index) => {
+ insert(db, String(index), name);
+ db.prepare("INSERT INTO finding_dedupe_groups VALUES (?, 'created')").run(
+ `group-${index}`,
+ );
+ db.prepare("INSERT INTO finding_dedupe_group_members VALUES (?, ?)").run(
+ `group-${index}`,
+ String(index),
+ );
+ });
+ for (const view of ["findings", "groups"] as const) {
+ for (const name of names) {
+ const query = { view, sort: "title", limit: 50, offset: 0 } as const;
+ const found = dashboard(db, { ...query, query: name.toUpperCase() });
+ assert.equal(found.total, 1, name);
+ assert.deepEqual(found.items[0].repositoryIds, [name]);
+ assert.deepEqual(
+ found.items,
+ dashboard(db, { ...query, repository: name }).items,
+ );
+ assert.equal(
+ dashboard(db, { ...query, query: JSON.stringify(name) }).total,
+ 0,
+ );
+ }
+ }
+});
+
test("dashboard rejects malformed Unicode query keys without aliasing stored values", (t) => {
const db = database(t);
const stored = insert(db, "record-\ufffd", "scope-\ufffd", "Title\ufffd");
@@ -229,7 +266,63 @@ test("dashboard reads its counts and rows from one WAL snapshot", async (t) => {
assert.equal(dashboard(db, query).total, 2);
});
-test("dashboard preserves the existing lone-surrogate display behavior", (t) => {
+test("dashboard preserves JSON-escaped surrogate titles without replacement-character search hits", (t) => {
+ const db = database(t);
+ const titles = [
+ "Title\ud800",
+ "Title\udfff",
+ "Title�",
+ "Title🙂",
+ "Title\0value",
+ ];
+ const documents = titles.map((title, index) =>
+ insert(db, String(index), "repository", title),
+ );
+ const query = {
+ view: "findings",
+ sort: "title",
+ limit: 50,
+ offset: 0,
+ } as const;
+ for (const [index, title] of titles.entries()) {
+ const result = dashboard(db, { ...query, id: String(index) });
+ assert.equal(
+ result.items.find((item) => item.id === String(index))?.title,
+ title,
+ );
+ assert.equal(result.detail?.item.title, title);
+ assert.deepEqual(result.detail?.finding, documents[index]);
+ }
+ assert.deepEqual(
+ dashboard(db, { ...query, query: "�" }).items.map((item) => item.id),
+ ["2"],
+ );
+});
+
+test("dashboard searches legacy records with missing or null titles", (t) => {
+ const db = database(t);
+ insert(db, "missing", "repository");
+ insert(db, "null", "repository");
+ db.exec(`
+ UPDATE findings SET details_json = json_remove(details_json, '$.title') WHERE id = 'missing';
+ UPDATE findings SET details_json = json_set(details_json, '$.title', NULL) WHERE id = 'null';
+ `);
+ const query = {
+ view: "findings",
+ sort: "activity",
+ limit: 50,
+ offset: 0,
+ } as const;
+ assert.deepEqual(
+ dashboard(db, { ...query, query: "repository" }).items.map(
+ (item) => item.id,
+ ),
+ ["missing", "null"],
+ );
+ assert.equal(dashboard(db, { ...query, query: "absent" }).total, 0);
+});
+
+test("dashboard preserves exact lone-surrogate display without lossy search matches", (t) => {
const db = database(t);
const titles = [
"high\ud800title",
@@ -246,7 +339,7 @@ test("dashboard preserves the existing lone-surrogate display behavior", (t) =>
offset: 0,
id,
});
- assert.equal(result.detail?.item.title, title.toWellFormed());
+ assert.equal(result.detail?.item.title, title);
assert.deepEqual(
result.detail?.finding,
stored,
@@ -261,7 +354,7 @@ test("dashboard preserves the existing lone-surrogate display behavior", (t) =>
});
assert.deepEqual(
matches.items.map((item) => item.id),
- [id],
+ title.isWellFormed() ? [id] : [],
);
}
});
diff --git a/plugins/codex-security/mcp-app/tests/test_workbench_findings.ts b/plugins/codex-security/mcp-app/tests/test_workbench_findings.ts
index ee381e682..9d141e186 100644
--- a/plugins/codex-security/mcp-app/tests/test_workbench_findings.ts
+++ b/plugins/codex-security/mcp-app/tests/test_workbench_findings.ts
@@ -17,6 +17,12 @@ const { applyMigrations } = (await importSource(
"src/workbench/migrations.ts",
)) as typeof Migrations;
const { parseJson, stringifyJson } = await importSource("src/helpers/json.ts");
+const { dashboard } = (await importSource(
+ "src/workbench/dashboard.ts",
+)) as typeof import("../src/workbench/dashboard.ts");
+const { findPotentialDuplicates, listDedupeGroups } = (await importSource(
+ "src/workbench/duplicates.ts",
+)) as typeof import("../src/workbench/duplicates.ts");
const temporary = createTemporaryDirectories(true);
after(() => temporary.cleanup());
@@ -202,6 +208,131 @@ test("import batches preserve identity, repository memberships and stable pages"
assert.equal(listStoredFindings(database, { limit: 10, offset: 0 }).total, 2);
});
+test("historical timestamp spellings retain exact chronology, page boundaries, and ties", (t) => {
+ const database = open(t);
+ const timestamps = [
+ ["microsecond", "2026-10-08T01:00:00.123456Z"],
+ ["zero-b", "2026-10-08t01:00:00.000000000z"],
+ ["nanosecond", "2026-10-08T01:00:00.123456001Z"],
+ ["bare", "2026-10-08T01:00:00Z"],
+ ["offset", "2026-10-08T03:00:00.123456000+02:00"],
+ ["offset-overflow", "2026-10-08T03:00:00.123456+01:60"],
+ ["native", "2026-10-08T01:00:00.123Z"],
+ ["zero-a", "2026-10-08T01:00:00.000Z"],
+ ["later", "2026-10-08T01:00:01Z"],
+ ["upper-year", "9999-12-31T23:59:59.999999999-23:59"],
+ ["lower-year", "0001-01-01T00:00:00.000000001+23:59"],
+ ];
+ const expected = [
+ "lower-year",
+ "bare",
+ "zero-a",
+ "zero-b",
+ "native",
+ "microsecond",
+ "offset",
+ "offset-overflow",
+ "nanosecond",
+ "later",
+ "upper-year",
+ ];
+ for (const [id, timestamp] of timestamps) {
+ const item = entry(id);
+ item.finding.severity = {
+ level: id === "zero-b" ? "critical" : id === "zero-a" ? "low" : "high",
+ };
+ storeFindings(database, [item], timestamp, "repository");
+ }
+ for (const [id, timestamp] of timestamps) {
+ database
+ .prepare("INSERT INTO finding_dedupe_groups VALUES (?, ?)")
+ .run(id, timestamp);
+ database
+ .prepare("INSERT INTO finding_dedupe_group_members VALUES (?, 'native')")
+ .run(id);
+ }
+ const before = database
+ .prepare(
+ "SELECT id, created_at, updated_at, details_json FROM findings ORDER BY id",
+ )
+ .all();
+ assert.deepEqual(
+ expected.flatMap((_, offset) =>
+ listStoredFindings(database, { limit: 1, offset }).findings.map(
+ (finding) => finding.findingId,
+ ),
+ ),
+ expected,
+ );
+ assert.deepEqual(
+ listDedupeGroups(database, "native").groups.map((group) => group.groupId),
+ expected,
+ );
+ for (const repository of [undefined, "repository"]) {
+ const result = findPotentialDuplicates(database, "native", repository);
+ assert.ok(result.potentialDuplicates);
+ assert.deepEqual(
+ result.potentialDuplicates.map(
+ (finding) => (finding as Findings.Finding).findingId,
+ ),
+ expected.filter((id) => id !== "native"),
+ );
+ }
+ for (const view of ["findings", "groups"] as const) {
+ for (const sort of ["newest", "activity"] as const) {
+ for (const direction of ["asc", "desc"] as const) {
+ const chronological =
+ direction === "asc"
+ ? expected
+ : [
+ "upper-year",
+ "later",
+ "nanosecond",
+ "microsecond",
+ "offset",
+ "offset-overflow",
+ "native",
+ "bare",
+ "zero-a",
+ "zero-b",
+ "lower-year",
+ ];
+ const ordered = [...chronological];
+ if (view === "findings" && sort === "activity")
+ ordered.splice(
+ ordered.indexOf("bare"),
+ 3,
+ "zero-b",
+ "bare",
+ "zero-a",
+ );
+ const items = expected.flatMap(
+ (_, offset) =>
+ dashboard(database, { view, sort, direction, limit: 1, offset })
+ .items,
+ );
+ assert.deepEqual(
+ items.map((item) => item.id),
+ ordered,
+ `${view}/${sort}/${direction}`,
+ );
+ assert.deepEqual(
+ items.map((item) => item.createdAt),
+ ordered.map((id) => timestamps.find(([key]) => key === id)![1]),
+ );
+ }
+ }
+ }
+ assert.deepEqual(
+ database
+ .prepare(
+ "SELECT id, created_at, updated_at, details_json FROM findings ORDER BY id",
+ )
+ .all(),
+ before,
+ );
+});
+
test("mixed writers retain unchanged Python embeddings and replace supplied Node embeddings", async (t) => {
const directory = await temporary.create("workbench-findings-");
const path = join(directory, "workbench.sqlite3");
diff --git a/plugins/codex-security/scripts/finalize_scan_contract.py b/plugins/codex-security/scripts/finalize_scan_contract.py
index d7c99b106..12218d7cb 100644
--- a/plugins/codex-security/scripts/finalize_scan_contract.py
+++ b/plugins/codex-security/scripts/finalize_scan_contract.py
@@ -881,8 +881,13 @@ def _validate_remote(remote: str, context: str) -> None:
def _validate_date_time(value: str, context: str) -> None:
if not RFC3339_RE.fullmatch(value):
raise ContractError(f"{context}: expected an RFC 3339 timestamp")
+ # Python 3.10 only parses 3 or 6 fractional digits. Validate the calendar and
+ # offset without a complete ASCII fraction, leaving the original text intact.
+ parser_value = re.sub(r"\.[0-9]+(?=[Zz+-])", "", value)
try:
- parsed = datetime.fromisoformat(value[:-1] + "+00:00" if value[-1] in "Zz" else value)
+ parsed = datetime.fromisoformat(
+ parser_value[:-1] + "+00:00" if parser_value[-1] in "Zz" else parser_value
+ )
except ValueError as exc:
raise ContractError(f"{context}: expected an RFC 3339 timestamp") from exc
if parsed.tzinfo is None:
diff --git a/plugins/codex-security/scripts/workbench_feedback.py b/plugins/codex-security/scripts/workbench_feedback.py
index 51b08a161..906ee0c95 100644
--- a/plugins/codex-security/scripts/workbench_feedback.py
+++ b/plugins/codex-security/scripts/workbench_feedback.py
@@ -16,10 +16,11 @@ from workbench_constants import (
FINDING_SUMMARY_BYTES,
FINDING_TITLE_BYTES,
)
-from workbench_validation import bounded_output_text
+from workbench_validation import bounded_output_text, register_timestamp_collation
def get_scan_feedback(connection: sqlite3.Connection, scan: sqlite3.Row) -> dict[str, Any]:
+ register_timestamp_collation(connection)
rows = connection.execute(
"""
WITH ranked_decisions AS (
@@ -33,8 +34,10 @@ def get_scan_feedback(connection: sqlite3.Connection, scan: sqlite3.Row) -> dict
locations.relative_path, locations.start_line, locations.end_line, locations.role,
ROW_NUMBER() OVER (
PARTITION BY findings.id
- ORDER BY COALESCE(triage.updated_at, source_scans.completed_at) DESC,
- source_scans.completed_at DESC,
+ ORDER BY
+ COALESCE(triage.updated_at, source_scans.completed_at)
+ COLLATE codex_security_timestamp DESC,
+ source_scans.completed_at COLLATE codex_security_timestamp DESC,
source_scans.id DESC, occurrences.id DESC
) AS decision_rank
FROM finding_occurrences AS occurrences
@@ -60,7 +63,9 @@ def get_scan_feedback(connection: sqlite3.Connection, scan: sqlite3.Row) -> dict
AND close_reason = 'false_positive'
AND note IS NOT NULL
AND trim(note) != ''
- ORDER BY updated_at DESC, source_completed_at DESC, source_scan_id DESC, finding_id DESC
+ ORDER BY updated_at COLLATE codex_security_timestamp DESC,
+ source_completed_at COLLATE codex_security_timestamp DESC,
+ source_scan_id DESC, finding_id DESC
LIMIT 50
""",
(scan["target_id"], scan["id"]),
diff --git a/plugins/codex-security/scripts/workbench_native_indexes.py b/plugins/codex-security/scripts/workbench_native_indexes.py
index ce4be2e88..f11eb8cda 100644
--- a/plugins/codex-security/scripts/workbench_native_indexes.py
+++ b/plugins/codex-security/scripts/workbench_native_indexes.py
@@ -13,7 +13,7 @@ from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parent))
import workbench_scan_history as scan_history
from workbench_constants import FINDING_SUMMARY_BYTES, FINDING_TITLE_BYTES, FINDINGS_PAGE_MAX
-from workbench_validation import bounded_output_text
+from workbench_validation import bounded_output_text, register_timestamp_collation, timestamp_key
def list_global_findings(
@@ -75,6 +75,7 @@ def list_global_findings(
def _indexed_findings(connection: sqlite3.Connection) -> Iterator[dict[str, Any]]:
+ register_timestamp_collation(connection)
parents: dict[tuple[str, str], tuple[str, str]] = {}
def group(identity: tuple[str, str]) -> tuple[str, str]:
@@ -101,7 +102,7 @@ def _indexed_findings(connection: sqlite3.Connection) -> Iterator[dict[str, Any]
latest_scan_by_target = dict(
connection.execute(
- "SELECT target_id, id FROM scans WHERE status = 'complete' ORDER BY started_at, id"
+ "SELECT target_id, id FROM scans WHERE status = 'complete' ORDER BY started_at COLLATE codex_security_timestamp, id"
)
)
@@ -118,7 +119,7 @@ def _indexed_findings(connection: sqlite3.Connection) -> Iterator[dict[str, Any]
scans.target_id,
targets.current_path AS target_path,
scans.scope,
- MAX(scans.updated_at, COALESCE(triage.updated_at, '')) AS updated_at,
+ scans.updated_at,
triage.status AS decision_status,
triage.close_reason,
triage.updated_at AS decision_updated_at,
@@ -143,20 +144,26 @@ def _indexed_findings(connection: sqlite3.Connection) -> Iterator[dict[str, Any]
findings = []
for occurrences in grouped.values():
- latest = max(occurrences, key=lambda row: (row["created_at"], row["occurrence_id"]))
+ latest = max(
+ occurrences,
+ key=lambda row: (timestamp_key(row["created_at"]), row["occurrence_id"]),
+ )
decision = max(
(row for row in occurrences if row["decision_status"] is not None),
- key=lambda row: (row["decision_updated_at"], row["occurrence_id"]),
+ key=lambda row: (timestamp_key(row["decision_updated_at"]), row["occurrence_id"]),
default=None,
)
status = decision["decision_status"] if decision is not None else "open"
if (
status == "closed"
and decision["close_reason"] == "already_fixed"
- and latest["created_at"] > decision["decision_updated_at"]
+ and timestamp_key(latest["created_at"]) > timestamp_key(decision["decision_updated_at"])
):
status = "open"
- scans = sorted({(row["scan_started_at"], row["scan_id"]) for row in occurrences})
+ scans = sorted(
+ {(row["scan_started_at"], row["scan_id"]) for row in occurrences},
+ key=lambda scan: (timestamp_key(scan[0]), scan[1]),
+ )
findings.append(
{
**dict(latest),
@@ -169,9 +176,14 @@ def _indexed_findings(connection: sqlite3.Connection) -> Iterator[dict[str, Any]
"matched_finding_ids": sorted({row["finding_id"] for row in occurrences}),
"occurrence_count": len(occurrences),
"status": status,
- "updated_at": max(
- latest["updated_at"],
- decision["decision_updated_at"] if decision is not None else "",
+ "updated_at": (
+ max(
+ latest["updated_at"],
+ decision["decision_updated_at"],
+ key=lambda value: (timestamp_key(value), value),
+ )
+ if decision is not None
+ else latest["updated_at"]
),
}
)
@@ -181,7 +193,7 @@ def _indexed_findings(connection: sqlite3.Connection) -> Iterator[dict[str, Any]
key=lambda finding: (
finding["status"] == "open",
-scan_history.SEVERITY_ORDER.get(finding["severity"], 5),
- finding["created_at"],
+ timestamp_key(finding["created_at"]),
),
reverse=True,
)
@@ -192,13 +204,14 @@ def list_repositories(
connection: sqlite3.Connection,
args: argparse.Namespace | None = None,
) -> dict[str, Any]:
+ register_timestamp_collation(connection)
scans = scan_history.list_scans(connection)["scans"]
scans_by_id = {scan["scanId"]: scan for scan in scans}
scan_count_by_target = dict(Counter(scan["targetId"] for scan in scans))
latest_scan_by_target: dict[str, dict[str, Any]] = {}
for row in connection.execute(
- "SELECT id, target_id FROM scans ORDER BY started_at DESC, id DESC"
+ "SELECT id, target_id FROM scans ORDER BY started_at COLLATE codex_security_timestamp DESC, id DESC"
):
latest_scan_by_target.setdefault(row["target_id"], scans_by_id[row["id"]])
diff --git a/plugins/codex-security/scripts/workbench_scan_history.py b/plugins/codex-security/scripts/workbench_scan_history.py
index 9e3202c02..7b9a84ec4 100644
--- a/plugins/codex-security/scripts/workbench_scan_history.py
+++ b/plugins/codex-security/scripts/workbench_scan_history.py
@@ -20,7 +20,7 @@ from workbench_constants import ARTIFACTS, FINDINGS_PAGE_MAX
from workbench_scan_start import scan_target_identity
from workbench_scan_usage import stored_scan_cost_fields
from workbench_target import git_output, require_scan_target_identity
-from workbench_validation import reject_non_finite_json
+from workbench_validation import register_timestamp_collation, reject_non_finite_json, timestamp_key
def rename_scan(connection: sqlite3.Connection, scan: sqlite3.Row, name: str) -> dict[str, Any]:
@@ -204,6 +204,7 @@ def _repository_origin(target: Path) -> tuple[str, str] | None:
def list_scans(
connection: sqlite3.Connection, args: argparse.Namespace | None = None
) -> dict[str, Any]:
+ register_timestamp_collation(connection)
connection.create_function("casefold", 1, str.casefold, deterministic=True)
if os.name == "nt":
connection.create_function("codex_security_path_key", 1, _windows_path_key)
@@ -297,8 +298,9 @@ def list_scans(
{where}
ORDER BY
CASE WHEN scans.status = 'running' AND scans.canceled_at IS NULL THEN 0 ELSE 1 END,
- MAX(scans.updated_at, progress.updated_at) DESC,
- scans.started_at DESC,
+ MAX(scans.updated_at COLLATE codex_security_timestamp, progress.updated_at)
+ COLLATE codex_security_timestamp DESC,
+ scans.started_at COLLATE codex_security_timestamp DESC,
scans.id
{pagination}
""",
@@ -337,7 +339,11 @@ def list_scans(
"targetPath": row["target_path"],
"targetRevision": row["target_revision"],
"targetSummary": row["target_summary"],
- "updatedAt": max(row["updated_at"], row["progress_updated_at"]),
+ "updatedAt": max(
+ row["updated_at"],
+ row["progress_updated_at"],
+ key=lambda value: (timestamp_key(value), value),
+ ),
**(
{"warnings": json.loads(row["completion_warnings_json"])}
if row["completion_warnings_json"] != "[]"
diff --git a/plugins/codex-security/scripts/workbench_validation.py b/plugins/codex-security/scripts/workbench_validation.py
index 9fd6988ed..36b51dc44 100644
--- a/plugins/codex-security/scripts/workbench_validation.py
+++ b/plugins/codex-security/scripts/workbench_validation.py
@@ -9,6 +9,7 @@ import re
import sqlite3
import sys
import uuid
+from datetime import datetime
from pathlib import Path, PurePosixPath
from typing import Any
@@ -20,6 +21,25 @@ from workbench_scan_usage import _reject_nonstandard_json_number as reject_nonst
reject_non_finite_json = finalizer._reject_non_finite_json
+def timestamp_key(value: str) -> tuple[datetime, str]:
+ """Compare accepted timestamps without rounding fractions or rewriting text."""
+ utc = value[-1] in "Zz"
+ whole_second = datetime.fromisoformat(value[:19] + ("+00:00" if utc else value[-6:]))
+ fraction = value[20 : -1 if utc else -6].rstrip("0") if value[19:20] == "." else ""
+ return whole_second, fraction
+
+
+def compare_timestamps(left: str, right: str) -> int:
+ left_key, right_key = timestamp_key(left), timestamp_key(right)
+ return (left_key > right_key) - (left_key < right_key)
+
+
+def register_timestamp_collation(connection: sqlite3.Connection) -> None:
+ name = "codex_security_timestamp"
+ if not any(row[1].lower() == name for row in connection.execute("PRAGMA collation_list")):
+ connection.create_collation(name, compare_timestamps)
+
+
def require_uuid(value: str, label: str) -> str:
try:
return str(uuid.UUID(value))
diff --git a/plugins/codex-security/tests/test_finalize_scan_contract.py b/plugins/codex-security/tests/test_finalize_scan_contract.py
index dc5ec9332..66366bd04 100644
--- a/plugins/codex-security/tests/test_finalize_scan_contract.py
+++ b/plugins/codex-security/tests/test_finalize_scan_contract.py
@@ -12,7 +12,6 @@ import tempfile
import threading
from collections.abc import Iterator
from contextlib import contextmanager
-from datetime import datetime, timezone
from pathlib import Path
from unittest import main, mock, skipIf, skipUnless
@@ -275,33 +274,6 @@ The extraction root is not enforced.
result["partialFingerprints"]["codexSecurity/v1"], finding["fingerprints"]["primary"]
)
- def test_headless_finalization_replaces_model_timestamps_with_machine_clock(self) -> None:
- self.manifest["scan"]["startedAt"] = "2026-07-21T23:20:33Z"
- self.manifest["scan"]["completedAt"] = "2026-07-21T23:30:52Z"
- self.write_scan()
- started_at = "2026-07-22T06:20:33Z"
- before = datetime.now(timezone.utc)
-
- with mock.patch.dict(os.environ, {"CODEX_SECURITY_STARTED_AT": started_at}):
- manifest, _, _ = FINALIZER.finalize_scan(self.scan_dir)
-
- completed_at = manifest["scan"]["completedAt"]
- self.assertEqual(manifest["scan"]["startedAt"], started_at)
- self.assertTrue(completed_at.endswith("Z"))
- completed_datetime = datetime.fromisoformat(completed_at.replace("Z", "+00:00"))
- self.assertGreaterEqual(completed_datetime, before)
- self.assertLessEqual(completed_datetime, datetime.now(timezone.utc))
- self.assertEqual(manifest["scan"]["sealedAt"], completed_at)
-
- def test_headless_finalization_rejects_invalid_authoritative_start(self) -> None:
- self.write_scan()
-
- with mock.patch.dict(os.environ, {"CODEX_SECURITY_STARTED_AT": "not-a-timestamp"}):
- with self.assertRaisesRegex(FINALIZER.ContractError, "RFC 3339 timestamp"):
- FINALIZER.finalize_scan(self.scan_dir)
-
- self.assertNotIn("sealedAt", self.read_json("scan-manifest.json")["scan"])
-
def test_finalizes_canonical_document_beyond_previous_size_limit(self) -> None:
self.manifest["metadata"] = "x" * (16 * 1024 * 1024)
self.write_scan()
@@ -2452,14 +2424,6 @@ The extraction root is not enforced.
)
self.assertEqual(coverage["deferred"][0]["paths"], [path])
- def test_rejects_non_rfc3339_timestamps(self) -> None:
- for timestamp in ("2026-W22-7T18:09:00+00:00", "2026-05-31T18:09:00+0000"):
- with self.subTest(timestamp=timestamp):
- self.manifest["scan"]["startedAt"] = timestamp
- self.write_scan()
- with self.assertRaisesRegex(FINALIZER.ContractError, "RFC 3339 timestamp"):
- FINALIZER.finalize_scan(self.scan_dir)
-
def test_rejects_coverage_scope_mismatch(self) -> None:
self.coverage["includePaths"] = ["other/"]
self.write_scan()
diff --git a/plugins/codex-security/tests/test_finalize_scan_timestamps.py b/plugins/codex-security/tests/test_finalize_scan_timestamps.py
new file mode 100644
index 000000000..71384a295
--- /dev/null
+++ b/plugins/codex-security/tests/test_finalize_scan_timestamps.py
@@ -0,0 +1,86 @@
+from __future__ import annotations
+
+import os
+import unittest
+from datetime import datetime, timezone
+from unittest import mock
+
+import test_finalize_scan_contract as fixtures
+
+FINALIZER = fixtures.FINALIZER
+CANONICAL_FILES = fixtures.CANONICAL_FILES
+
+
+class FinalizeScanTimestampsTest(unittest.TestCase):
+ setUp = fixtures.FinalizeScanContractTest.setUp
+ tearDown = fixtures.FinalizeScanContractTest.tearDown
+ write_scan = fixtures.FinalizeScanContractTest.write_scan
+ write_json = fixtures.FinalizeScanContractTest.write_json
+ read_json = fixtures.FinalizeScanContractTest.read_json
+ scan_file_bytes = fixtures.FinalizeScanContractTest.scan_file_bytes
+
+ def test_headless_finalization_replaces_model_timestamps_with_machine_clock(self) -> None:
+ self.manifest["scan"]["startedAt"] = "2026-07-21T23:20:33Z"
+ self.manifest["scan"]["completedAt"] = "2026-07-21T23:30:52Z"
+ self.write_scan()
+ started_at = "2026-07-22T06:20:33Z"
+ before = datetime.now(timezone.utc)
+
+ with mock.patch.dict(os.environ, {"CODEX_SECURITY_STARTED_AT": started_at}):
+ manifest, _, _ = FINALIZER.finalize_scan(self.scan_dir)
+
+ completed_at = manifest["scan"]["completedAt"]
+ self.assertEqual(manifest["scan"]["startedAt"], started_at)
+ self.assertTrue(completed_at.endswith("Z"))
+ completed_datetime = datetime.fromisoformat(completed_at.replace("Z", "+00:00"))
+ self.assertGreaterEqual(completed_datetime, before)
+ self.assertLessEqual(completed_datetime, datetime.now(timezone.utc))
+ self.assertEqual(manifest["scan"]["sealedAt"], completed_at)
+
+ def test_headless_finalization_rejects_invalid_authoritative_start(self) -> None:
+ self.write_scan()
+
+ with mock.patch.dict(os.environ, {"CODEX_SECURITY_STARTED_AT": "not-a-timestamp"}):
+ with self.assertRaisesRegex(FINALIZER.ContractError, "RFC 3339 timestamp"):
+ FINALIZER.finalize_scan(self.scan_dir)
+
+ self.assertNotIn("sealedAt", self.read_json("scan-manifest.json")["scan"])
+
+ def test_preserves_rfc3339_fractional_timestamps_when_sealing(self) -> None:
+ for fraction in ("", ".1", ".12", ".123", ".1234", ".12345", ".123456", ".1234567"):
+ for offset in ("z", "+02:00", "-07:30"):
+ timestamp = f"2024-02-29t18:09:00{fraction}{offset}"
+ with self.subTest(timestamp=timestamp):
+ self.manifest["scan"]["startedAt"] = timestamp
+ self.manifest["scan"]["completedAt"] = timestamp
+ self.write_scan()
+
+ manifest, _, _ = FINALIZER.finalize_scan(self.scan_dir)
+
+ for field in ("startedAt", "completedAt", "sealedAt"):
+ self.assertEqual(manifest["scan"][field], timestamp)
+ before = self.scan_file_bytes(*CANONICAL_FILES)
+ FINALIZER.finalize_scan(self.scan_dir)
+ self.assertEqual(self.scan_file_bytes(*CANONICAL_FILES), before)
+
+ def test_rejects_non_rfc3339_timestamps(self) -> None:
+ for timestamp in (
+ "2026-W22-7T18:09:00+00:00",
+ "2026-05-31T18:09:00+0000",
+ "2026-02-29T18:09:00.123456789Z",
+ "2026-05-31T24:09:00.1Z",
+ "2026-05-31T18:60:00.1Z",
+ "2026-05-31T18:09:61.1Z",
+ "2026-05-31T18:09:00.123456789+24:00",
+ "2026-05-31T18:09:00.123456789-24:00",
+ "2026-05-31T18:09:00.Z",
+ "2026-05-31T18:09:00,123Z",
+ "2026-05-31T18:09:00.1",
+ "2026-05-31T18:09:00.\u0661Z",
+ "2026-05-31T18:09:00.123\u0664Z",
+ ):
+ with self.subTest(timestamp=timestamp):
+ self.manifest["scan"]["startedAt"] = timestamp
+ self.write_scan()
+ with self.assertRaisesRegex(FINALIZER.ContractError, "RFC 3339 timestamp"):
+ FINALIZER.finalize_scan(self.scan_dir)
diff --git a/plugins/codex-security/tests/test_workbench_completion_binding.py b/plugins/codex-security/tests/test_workbench_completion_binding.py
index 363702874..ed8f5201b 100644
--- a/plugins/codex-security/tests/test_workbench_completion_binding.py
+++ b/plugins/codex-security/tests/test_workbench_completion_binding.py
@@ -411,6 +411,38 @@ def test_prepared_completion_does_not_publish_scan_before_acceptance(tmp_path: P
).fetchone() == ("complete", manifest["scan"]["completedAt"])
+ "timestamp",
+ [
+ "2026-10-08T03:00:00.123456+02:00",
+ "2026-10-08t01:00:00.123456789z",
+ "2026-10-08T01:00:00.1-00:00",
+ "2026-10-07T17:30:00.123456789012345678901234567890-07:30",
+ ],
+)
+def test_sealed_completion_preserves_original_timestamp_text(
+ tmp_path: Path, timestamp: str
+) -> None:
+ state_dir, target = tmp_path / "state", tmp_path / "target"
+ target.mkdir()
+ scan_dir = tmp_path / "scan"
+ scan_id = register_cli_scan(state_dir, target, scan_dir)["scanId"]
+ write_completed_contract(scan_dir, scan_id, target)
+ manifest_path = scan_dir / "scan-manifest.json"
+ manifest = json.loads(manifest_path.read_text())
+ manifest["scan"]["completedAt"] = timestamp
+ manifest_path.write_text(json.dumps(manifest))
+ _seal_draft(scan_dir, target)
+ sealed_manifest_bytes = manifest_path.read_bytes()
+ scan_command(state_dir, "complete-scan", scan_id)
+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
+ assert connection.execute("SELECT created_at, updated_at FROM findings").fetchall() == [
+ (timestamp, timestamp)
+ ]
+ assert manifest_path.read_bytes() == sealed_manifest_bytes
+ assert json.loads(sealed_manifest_bytes)["scan"]["completedAt"] == timestamp
+
+
def test_incompatible_sealed_deep_scan_remains_recoverable(tmp_path: Path) -> None:
state_dir, scan_id, scan_dir = _start_deep_scan_with_draft_findings(tmp_path)
scan_command(state_dir, "prepare-scan-completion", scan_id)
diff --git a/plugins/codex-security/tests/test_workbench_feedback.py b/plugins/codex-security/tests/test_workbench_feedback.py
index 51360a4ed..9e1e34ad3 100644
--- a/plugins/codex-security/tests/test_workbench_feedback.py
+++ b/plugins/codex-security/tests/test_workbench_feedback.py
@@ -3,10 +3,12 @@ from __future__ import annotations
import json
import sqlite3
import uuid
+from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
import pytest
+from test_workbench_completion_binding import _seal_draft, register_cli_scan
from workbench_test_support import (
create_saved_workspace,
get_scan,
@@ -342,3 +344,40 @@ def test_feedback_returns_only_the_50_latest_decisions(tmp_path: Path) -> None:
assert [finding["identity"]["anchor"] for finding in feedback["falsePositives"]] == [
f"false-positive-{index:03d}" for index in range(54, 4, -1)
]
+
+
+def test_later_offset_completion_supersedes_false_positive_feedback(tmp_path: Path) -> None:
+ state, target = tmp_path / "state", tmp_path / "target"
+ target.mkdir()
+ scans = []
+ for index in range(2):
+ scan_dir = tmp_path / f"scan-{index}"
+ scan_id = register_cli_scan(state, target, scan_dir)["scanId"]
+ write_completed_contract(scan_dir, scan_id, target)
+ manifest_path = scan_dir / "scan-manifest.json"
+ manifest = json.loads(manifest_path.read_text())
+ timestamp = datetime.now(timezone.utc)
+ if index == 0:
+ timestamp -= timedelta(minutes=1)
+ else:
+ timestamp = timestamp.astimezone(timezone(timedelta(hours=-5)))
+ manifest["scan"].update(
+ startedAt="2026-10-08T00:00:00Z",
+ completedAt=timestamp.isoformat().replace("+00:00", "Z"),
+ )
+ manifest_path.write_text(json.dumps(manifest))
+ _seal_draft(scan_dir, target)
+ scan_command(state, "complete-scan", scan_id)
+ scans.append(scan_id)
+ if index == 0:
+ occurrence = json.loads((scan_dir / "findings.json").read_text())["findings"][0]
+ _close_finding(
+ state, occurrence["occurrenceId"], "false_positive", "Synthetic prior decision"
+ )
+ current = register_cli_scan(state, target, tmp_path / "scan-current")["scanId"]
+ assert _feedback(state, current)["falsePositives"] == []
+ assert [scan["scanId"] for scan in run_workbench(state, "list-scans")["scans"]] == [
+ current,
+ scans[1],
+ scans[0],
+ ]
diff --git a/plugins/codex-security/tests/test_workbench_native_index_queries.py b/plugins/codex-security/tests/test_workbench_native_index_queries.py
index d3a10c65b..309b0294f 100644
--- a/plugins/codex-security/tests/test_workbench_native_index_queries.py
+++ b/plugins/codex-security/tests/test_workbench_native_index_queries.py
@@ -1,11 +1,19 @@
from __future__ import annotations
+import json
import ntpath
from argparse import Namespace
+from pathlib import Path
from types import SimpleNamespace
import pytest
-from workbench_test_support import stable_target_id
+from test_workbench_completion_binding import _seal_draft, register_cli_scan
+from workbench_test_support import (
+ run_workbench,
+ scan_command,
+ stable_target_id,
+ write_completed_contract,
+)
SCAN_IDS = [f"00000000-0000-4000-8000-{index:012d}" for index in range(3)]
@@ -121,6 +129,193 @@ def test_global_finding_filters_apply_before_pagination(workbench_api, indexed_c
assert len(unfiltered["findings"]) == 3
[email protected]("matched", [False, True])
+def test_latest_scan_confirmation_uses_group_membership(
+ workbench_api, indexed_collections, matched
+):
+ connection, targets = indexed_collections
+ connection.execute(
+ "UPDATE scans SET target_id = ?, started_at = ? WHERE id = ?",
+ (stable_target_id(targets[0]), "2026-08-01T00:10:00Z", SCAN_IDS[1]),
+ )
+ for index, completed_at in [(0, "2026-08-01T00:30:00Z"), (1, "2026-08-01T00:20:00Z")]:
+ connection.execute(
+ "UPDATE finding_occurrences SET created_at = ? WHERE id = ?",
+ (completed_at, f"occurrence-{index}"),
+ )
+ if matched:
+ connection.execute(
+ "INSERT INTO scan_comparisons VALUES (?, ?, '{}', 'now', 'now')", SCAN_IDS[:2]
+ )
+ connection.execute(
+ "INSERT INTO scan_comparison_matches VALUES (?, ?, 'occurrence-0', 'occurrence-1', 'same issue')",
+ SCAN_IDS[:2],
+ )
+ else:
+ connection.execute(
+ "UPDATE finding_occurrences SET finding_id = 'finding-0' WHERE id = 'occurrence-1'"
+ )
+ query = workbench_api["native_indexes"].list_global_findings
+ args = query_args(target_id=stable_target_id(targets[0]))
+ (finding,) = query(connection, args)["findings"]
+ assert finding["scanId"] == SCAN_IDS[0]
+ assert finding["knownScanIds"] == SCAN_IDS[:2]
+ assert finding["confirmedInLatestScan"] is True
+ connection.execute("DELETE FROM finding_occurrences WHERE id = 'occurrence-1'")
+ (finding,) = query(connection, args)["findings"]
+ assert finding["confirmedInLatestScan"] is False
+
+
+ ("older", "later", "equal"),
+ [
+ ("2026-10-08T03:00:00.123456+02:00", "2026-10-08T01:00:02.000Z", False),
+ ("2026-10-08T01:00:00.123Z", "2026-10-08T01:00:00.123456Z", False),
+ (
+ "2026-10-08T01:00:00.123456000000000001Z",
+ "2026-10-08T01:00:00.123456000000000002Z",
+ False,
+ ),
+ ("2026-10-08T03:00:00.123000+02:00", "2026-10-08t01:00:00.123z", True),
+ ],
+)
+def test_global_findings_select_exact_sealed_completion_times(
+ tmp_path: Path, older: str, later: str, equal: bool
+) -> None:
+ state, target = tmp_path / "state", tmp_path / "target"
+ target.mkdir()
+ expected = []
+ sealed = {}
+ for index, timestamp in enumerate((older, later)):
+ scan = tmp_path / f"scan-{index}"
+ scan_id = register_cli_scan(state, target, scan)["scanId"]
+ write_completed_contract(scan, scan_id, target)
+ manifest = json.loads((scan / "scan-manifest.json").read_text())
+ manifest["scan"].update(startedAt="2026-10-08T00:00:00Z", completedAt=timestamp)
+ (scan / "scan-manifest.json").write_text(json.dumps(manifest))
+ findings = json.loads((scan / "findings.json").read_text())
+ findings["findings"][0]["title"] = f"Synthetic observation {index}"
+ findings["findings"][0]["severity"]["level"] = "low" if index == 0 else "high"
+ (scan / "findings.json").write_text(json.dumps(findings))
+ _seal_draft(scan, target)
+ sealed.update(
+ {
+ scan / name: (scan / name).read_bytes()
+ for name in ("scan-manifest.json", "findings.json", "coverage.json")
+ }
+ )
+ scan_command(state, "complete-scan", scan_id)
+ expected.append(json.loads((scan / "findings.json").read_text())["findings"][0])
+ selected = max(expected, key=lambda item: item["occurrenceId"]) if equal else expected[1]
+ (finding,) = run_workbench(state, "list-global-findings")["findings"]
+ assert finding["occurrenceId"] == selected["occurrenceId"]
+ assert finding["title"] == selected["title"]
+ assert finding["severity"] == {"level": selected["severity"]["level"]}
+ assert finding["createdAt"] == (older if selected is expected[0] else later)
+ assert {path: path.read_bytes() for path in sealed} == sealed
+
+
+ ("completion", "status", "updated"),
+ [
+ ("2026-10-08T03:00:00+02:00", "closed", "2026-10-08T01:00:01.000001Z"),
+ ("2026-10-07T23:00:02-02:00", "open", "2026-10-07T23:00:02-02:00"),
+ ("2026-10-08T03:00:01.000001000+02:00", "closed", "2026-10-08T03:00:01.000001000+02:00"),
+ (
+ "2026-10-08T01:00:01.000001000000000001Z",
+ "open",
+ "2026-10-08T01:00:01.000001000000000001Z",
+ ),
+ ],
+)
+def test_global_findings_compare_decisions_and_return_original_update_text(
+ workbench_api, indexed_collections, completion, status, updated
+):
+ connection, targets = indexed_collections
+ connection.execute(
+ "UPDATE scans SET target_id = ? WHERE id = ?", (stable_target_id(targets[0]), SCAN_IDS[1])
+ )
+ connection.execute(
+ "UPDATE finding_occurrences SET finding_id = 'finding-0' WHERE id = 'occurrence-1'"
+ )
+ connection.execute(
+ "UPDATE finding_occurrences SET created_at = ? WHERE id = 'occurrence-0'", (completion,)
+ )
+ connection.execute("UPDATE scans SET updated_at = ? WHERE id = ?", (completion, SCAN_IDS[0]))
+ for index, timestamp, reason in [
+ (0, "2026-10-08T01:00:01Z", "false_positive"),
+ (1, "2026-10-08T01:00:01.000001Z", "already_fixed"),
+ ]:
+ connection.execute(
+ "INSERT INTO finding_triage (occurrence_id, status, close_reason, note, updated_at) VALUES (?, 'closed', ?, 'Synthetic decision', ?)",
+ (f"occurrence-{index}", reason, timestamp),
+ )
+ before = connection.execute("SELECT id, updated_at FROM scans ORDER BY id").fetchall()
+ (finding,) = workbench_api["native_indexes"].list_global_findings(
+ connection, query_args(target_id=stable_target_id(targets[0]))
+ )["findings"]
+ assert finding["status"] == status
+ assert finding["updatedAt"] == updated
+ assert connection.execute("SELECT id, updated_at FROM scans ORDER BY id").fetchall() == before
+
+
+ ("timestamps", "order"),
+ [
+ (
+ [
+ "2026-10-08T03:00:00+02:00",
+ "2026-10-08T01:00:00.123Z",
+ "2026-10-08T01:00:00.123456Z",
+ ],
+ [2, 1, 0],
+ ),
+ (
+ [
+ "2026-10-08T01:00:00.123456000000000001Z",
+ "2026-10-08T01:00:00.123456000000000002Z",
+ "2026-10-08T01:00:00.123456000000000003Z",
+ ],
+ [2, 1, 0],
+ ),
+ (
+ [
+ "2026-10-08T01:00:00.000Z",
+ "2026-10-08T01:00:00Z",
+ "2026-10-08t03:00:00.000000+02:00",
+ ],
+ [0, 1, 2],
+ ),
+ (
+ [
+ "0001-01-01T00:00:00.000000001+23:59",
+ "0001-01-01T00:00:00Z",
+ "9999-12-31T23:59:59.999999999-23:59",
+ ],
+ [2, 1, 0],
+ ),
+ ],
+)
+def test_global_finding_pages_follow_exact_completion_order(
+ workbench_api, indexed_collections, timestamps, order
+):
+ connection, _ = indexed_collections
+ for index, timestamp in enumerate(timestamps):
+ connection.execute(
+ "UPDATE finding_occurrences SET created_at = ? WHERE id = ?",
+ (timestamp, f"occurrence-{index}"),
+ )
+ query = workbench_api["native_indexes"].list_global_findings
+ pages = [query(connection, query_args(limit=1, offset=index)) for index in range(3)]
+ assert [page["findings"][0]["occurrenceId"] for page in pages] == [
+ f"occurrence-{index}" for index in order
+ ]
+ assert [page["findings"][0]["createdAt"] for page in pages] == [
+ timestamps[index] for index in order
+ ]
+ assert [page["nextOffset"] for page in pages] == [1, 2, None]
+
+
def test_scan_findings_support_search_severity_and_triage_filters(
workbench_api, indexed_collections
):
@@ -257,3 +452,108 @@ def test_scan_list_probes_requested_repository_once(
("rev-parse", "--path-format=absolute", "--git-common-dir"),
("remote", "get-url", "origin"),
]
+
+
+ ("timestamps", "order"),
+ [
+ (
+ [
+ "2026-10-08T03:00:00+02:00",
+ "2026-10-08T01:00:00.123Z",
+ "2026-10-08T01:00:00.123456Z",
+ ],
+ [2, 1, 0],
+ ),
+ (
+ [
+ "2026-10-08T01:00:00.123456000000000001Z",
+ "2026-10-08T01:00:00.123456000000000002Z",
+ "2026-10-08T01:00:00.123456000000000003Z",
+ ],
+ [2, 1, 0],
+ ),
+ (
+ [
+ "2026-10-08T01:00:00.000Z",
+ "2026-10-08T01:00:00Z",
+ "2026-10-08t03:00:00.000000+02:00",
+ ],
+ [0, 1, 2],
+ ),
+ ],
+)
+def test_scan_pages_compare_exact_updates_and_preserve_ties(
+ workbench_api, indexed_collections, timestamps, order
+):
+ connection, _ = indexed_collections
+ for index, timestamp in enumerate(timestamps):
+ column = "scans" if index % 2 else "scan_progress"
+ identity = "id" if column == "scans" else "scan_id"
+ connection.execute(
+ f"UPDATE {column} SET updated_at = ? WHERE {identity} = ?", (timestamp, SCAN_IDS[index])
+ )
+ before = list(connection.iterdump())
+ query = workbench_api["scan_history"].list_scans
+ # Repeated helpers share a connection.
+ for _ in range(2):
+ pages = [query(connection, query_args(limit=1, offset=index)) for index in range(3)]
+ scan = connection.execute("SELECT * FROM scans LIMIT 1").fetchone()
+ assert workbench_api["get_scan_feedback"](connection, scan)["falsePositives"] == []
+ assert [page["scans"][0]["scanId"] for page in pages] == [
+ SCAN_IDS[index] for index in order
+ ]
+ assert [page["scans"][0]["updatedAt"] for page in pages] == [
+ timestamps[index] for index in order
+ ]
+ assert [page["nextOffset"] for page in pages] == [1, 2, None]
+ assert list(connection.iterdump()) == before
+
+
+ ("older", "newer", "equal"),
+ [
+ ("2026-10-08T01:00:00Z", "2026-10-08T01:00:00.100000Z", False),
+ ("2026-10-08T03:00:00+02:00", "2026-10-08T01:00:00.100000Z", False),
+ ("2026-10-08T01:00:00.000000001Z", "2026-10-08T01:00:00.000000002Z", False),
+ ("2026-10-08T03:00:00.100000+02:00", "2026-10-08t01:00:00.1z", True),
+ ],
+)
+def test_scan_start_chronology_keeps_latest_and_first_seen_queries_consistent(
+ workbench_api, indexed_collections, older, newer, equal
+):
+ connection, targets = indexed_collections
+ target_id = stable_target_id(targets[0])
+ for scan_id, timestamp in zip(SCAN_IDS[:2], (older, newer)):
+ connection.execute(
+ "UPDATE scans SET target_id = ?, started_at = ?, updated_at = ? WHERE id = ?",
+ (target_id, timestamp, "2026-10-08T04:00:00Z", scan_id),
+ )
+ connection.execute(
+ "UPDATE scan_progress SET updated_at = ? WHERE scan_id = ?",
+ ("2026-10-08T04:00:00Z", scan_id),
+ )
+ connection.execute(
+ "UPDATE finding_occurrences SET finding_id = 'finding-0' WHERE id = 'occurrence-1'"
+ )
+ connection.execute(
+ "INSERT INTO finding_occurrences "
+ "(id, finding_id, scan_id, title, summary, severity, confidence, remediation, details_json, created_at) "
+ "SELECT 'latest-only', 'finding-1', scan_id, title, summary, severity, confidence, remediation, details_json, created_at "
+ "FROM finding_occurrences WHERE id = 'occurrence-1'"
+ )
+ before = list(connection.iterdump())
+ indexes = workbench_api["native_indexes"]
+ findings = {finding["finding_id"]: finding for finding in indexes._indexed_findings(connection)}
+ assert findings["finding-1"]["confirmed_in_latest_scan"] is True
+ assert findings["finding-0"]["known_since"] == older
+ assert findings["finding-0"]["known_scan_ids"] == SCAN_IDS[:2]
+ repository = indexes.list_repositories(connection, query_args(target_id=target_id))[
+ "repositories"
+ ][0]
+ assert repository["latestScan"]["scanId"] == SCAN_IDS[1]
+ history = workbench_api["scan_history"].list_scans(connection, query_args(target_id=target_id))[
+ "scans"
+ ]
+ assert [scan["scanId"] for scan in history] == (SCAN_IDS[:2] if equal else SCAN_IDS[1::-1])
+ assert list(connection.iterdump()) == before
diff --git a/plugins/codex-security/tests/test_workbench_scan_history.py b/plugins/codex-security/tests/test_workbench_scan_history.py
index 0d6ddd7a1..34df2a74c 100644
--- a/plugins/codex-security/tests/test_workbench_scan_history.py
+++ b/plugins/codex-security/tests/test_workbench_scan_history.py
@@ -89,6 +89,23 @@ def test_scan_name_search_ignores_unicode_case(tmp_path: Path, name: str, query:
assert [(item["scanId"], item["name"]) for item in listed] == [(scan["scanId"], name)]
+def test_scan_history_search_casefolds_displayed_fields(tmp_path: Path) -> None:
+ state_dir = tmp_path / "state"
+ repository = tmp_path / "Straße"
+ (repository / "Ä").mkdir(parents=True)
+ (repository / "Ä" / "source.py").write_text("pass\n")
+ scan = start_prompt_only_scan(
+ state_dir,
+ repository,
+ tmp_path / "scans",
+ extra_args=("--scope=Ä", "--target-summary=Überblick"),
+ )["scan"]
+ for query in ("Straße", "STRASSE", "Ä", "ä", "Überblick", "ÜBERBLICK"):
+ listed = run_workbench(state_dir, "list-scans", "--query", query)["scans"]
+ assert [item["scanId"] for item in listed] == [scan["scanId"]]
+ assert run_workbench(state_dir, "list-scans", "--query", "unrelated")["scans"] == []
+
+
def test_rename_does_not_reorder_scan_history(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
@@ -96,7 +113,10 @@ def test_rename_does_not_reorder_scan_history(tmp_path: Path) -> None:
older = create_cli_scan(state_dir, tmp_path / "scans", repository)
newer = create_cli_scan(state_dir, tmp_path / "scans", repository)
with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
- for scan, timestamp in ((older, "2026-08-01"), (newer, "2026-08-02")):
+ for scan, timestamp in (
+ (older, "2026-08-01T00:00:00Z"),
+ (newer, "2026-08-02T00:00:00Z"),
+ ):
connection.execute(
"UPDATE scans SET started_at = ?, updated_at = ? WHERE id = ?",
(timestamp, timestamp, scan["scanId"]),
diff --git a/sdk/typescript/src/finding-workflow.ts b/sdk/typescript/src/finding-workflow.ts
index 317d5a158..1acd49f61 100644
--- a/sdk/typescript/src/finding-workflow.ts
+++ b/sdk/typescript/src/finding-workflow.ts
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
import { isAbsolute, relative, sep } from "node:path";
import type { JsonObject } from "./config.js";
import { CodexSecurityError, errorMessage } from "./errors.js";
+import { findingsBaseUrl } from "./findings-client.js";
import type { FindingSearchScope } from "./finding-retrieval.js";
import {
bundledPluginRoot,
@@ -53,11 +54,10 @@ export function workflowDigest(value: unknown): string {
}
export function workflowDestination(url: string): string {
- const route = "v1/bulk/findings";
- const destination = new URL(route, url.endsWith("/") ? url : `${url}/`);
+ const destination = findingsBaseUrl(url);
destination.username = "";
destination.password = "";
- return destination.href.slice(0, -route.length);
+ return destination.href;
}
/** State lives in the workbench database, never in sealed scan artifacts. */
diff --git a/sdk/typescript/src/findings-client.ts b/sdk/typescript/src/findings-client.ts
index 265ff928b..4ab5a03e6 100644
--- a/sdk/typescript/src/findings-client.ts
+++ b/sdk/typescript/src/findings-client.ts
@@ -30,8 +30,18 @@ class FindingsHttpError extends CodexSecurityError {
message: string,
signal?: AbortSignal,
): Promise<FindingsHttpError> {
- // Gateways can return plain text or HTML instead of the service's JSON error.
- const body: unknown = await response.json().catch(() => undefined);
+ // Service errors are JSON; other gateway bodies need not finish to report HTTP failure.
+ const mediaType = response.headers
+ .get("Content-Type")
+ ?.split(";", 1)[0]
+ ?.trim()
+ .toLowerCase();
+ let body: unknown;
+ if (mediaType === "application/json" || mediaType?.endsWith("+json")) {
+ body = await response.json().catch(() => undefined);
+ } else {
+ void response.body?.cancel().catch(() => undefined);
+ }
signal?.throwIfAborted();
const error = parseFindingsErrorResponse(body);
return new FindingsHttpError(
@@ -50,16 +60,27 @@ function isRetryable(error: unknown): boolean {
return error instanceof TypeError || error instanceof SyntaxError;
}
+export function findingsBaseUrl(value: string): URL {
+ const url = new URL(value);
+ if (!url.pathname.endsWith("/")) url.pathname += "/";
+ url.search = "";
+ url.hash = "";
+ return url;
+}
+
export class FindingsClient {
+ private readonly url: URL;
constructor(
- private readonly url: string,
+ url: string,
private readonly signal?: AbortSignal,
private readonly request: FindingsRequest = fetch,
private readonly retries: {
wait?: typeof waitForRetry;
random?: () => number;
} = {},
- ) {}
+ ) {
+ this.url = findingsBaseUrl(url);
+ }
async potentialDuplicates(
findingId: string,
@@ -138,7 +159,7 @@ export class FindingsClient {
}
private endpoint(path: string): URL {
- return new URL(path, this.url.endsWith("/") ? this.url : `${this.url}/`);
+ return new URL(path, this.url);
}
private async post(path: string, body: unknown): Promise<unknown> {
diff --git a/sdk/typescript/tests-ts/findings-client-retry.test.ts b/sdk/typescript/tests-ts/findings-client-retry.test.ts
index beb71c1aa..8c936c021 100644
--- a/sdk/typescript/tests-ts/findings-client-retry.test.ts
+++ b/sdk/typescript/tests-ts/findings-client-retry.test.ts
@@ -1,5 +1,6 @@
import { responding } from "./support/responses.js";
import { expect, test, mock } from "bun:test";
+import { workflowDestination } from "../src/finding-workflow.js";
import { FindingsClient } from "../src/findings-client.js";
import { rejecting } from "./support/errors.js";
@@ -9,13 +10,25 @@ const neighborhood = {
potentialDuplicates: [],
};
-test("lookup preserves the service error code and explanation", async () => {
- const message = "No current embedding exists in the requested repository.";
+const errorMediaTypes = [
+ "Application/JSON; charset=utf-8",
+ "application/problem+json",
+ "Application/vnd.synthetic.findings+JSON; charset=utf-8",
+];
+
+test.each(errorMediaTypes)("lookup retains %s errors", async (mediaType) => {
+ const message = "No current embedding exists in the requested repository. 🧪";
const client = new FindingsClient(
"http://synthetic.test",
undefined,
async () =>
- Response.json({ error: "finding_not_indexed", message }, { status: 404 }),
+ Response.json(
+ { error: "finding_not_indexed", message },
+ {
+ status: 404,
+ headers: { "Content-Type": mediaType },
+ },
+ ),
);
await expect(
client.potentialDuplicates("synthetic", scope),
@@ -48,12 +61,15 @@ test("publishing preserves conflict details without retrying", async () => {
expect(requests).toBe(1);
});
-test("publishing preserves cancellation while reading an error response", async () => {
+test.each(errorMediaTypes)("publish cancels %s reads", async (mediaType) => {
const controller = new AbortController();
const reason = new Error("Synthetic caller cancellation");
const request = mock(async (_url: URL, init: RequestInit) => {
expect(init.signal).toBe(controller.signal);
- const response = new Response(null, { status: 409 });
+ const response = new Response(null, {
+ status: 409,
+ headers: { "Content-Type": mediaType },
+ });
response.json = async () => {
controller.abort(reason);
throw new DOMException("Synthetic aborted body read", "AbortError");
@@ -290,3 +306,54 @@ test("Retry-After accepts an HTTP date", async () => {
await client.potentialDuplicates("synthetic", scope);
expect(sleep.mock.lastCall?.[0] ?? 0).toBeGreaterThan(24 * 60 * 60 * 1000);
});
+
+test.each(["lookup", "publish", "groups"] as const)(
+ "%s delivers HTTP failures without waiting for response cleanup",
+ async (operation) => {
+ const cancel = mock(() => new Promise<void>(() => {}));
+ const client = new FindingsClient(
+ "http://synthetic.test",
+ undefined,
+ async () => new Response(new ReadableStream({ cancel }), { status: 503 }),
+ { wait: async () => {} },
+ );
+ const result =
+ operation === "lookup"
+ ? client.potentialDuplicates("synthetic", scope)
+ : operation === "publish"
+ ? client.publish([], scope.repositoryId)
+ : client.storeDedupeGroups([["synthetic-a", "synthetic-b"]]);
+ await expect(result).rejects.toThrow("HTTP 503");
+ expect(cancel).toHaveBeenCalledTimes(operation === "publish" ? 1 : 3);
+ },
+);
+
+test.each([
+ "/service",
+ "/service/",
+ "/service?source=example",
+ "/service#example",
+ "/service/?source=example",
+ "/service ",
+])(
+ "preserves base pathname %s across requests and workflow identity",
+ async (path) => {
+ const urls: string[] = [];
+ const base = `http://synthetic:[email protected]${path}`;
+ const client = new FindingsClient(base, undefined, async (url) => {
+ urls.push(url.href);
+ return Response.json(
+ url.pathname.endsWith("bulk/findings") ? [] : neighborhood,
+ );
+ });
+ await client.publish([], scope.repositoryId);
+ await client.potentialDuplicates("a/b", scope);
+ await client.storeDedupeGroups([["a", "b"]]);
+ expect(urls).toEqual([
+ "http://synthetic:[email protected]/service/v1/bulk/findings",
+ "http://synthetic:[email protected]/service/v1/finding/a%2Fb/potential-duplicates?repositoryId=synthetic-repository",
+ "http://synthetic:[email protected]/service/v1/dedupe-groups",
+ ]);
+ expect(workflowDestination(base)).toBe("http://synthetic.test/service/");
+ },
+);
diff --git a/sdk/typescript/tests-ts/workbench-scan-root-alias.test.ts b/sdk/typescript/tests-ts/workbench-scan-root-alias.test.ts
index d704084cc..65bdb71e8 100644
--- a/sdk/typescript/tests-ts/workbench-scan-root-alias.test.ts
+++ b/sdk/typescript/tests-ts/workbench-scan-root-alias.test.ts
@@ -25,10 +25,11 @@ test("matches scan-root filters including Windows path aliases", async () => {
"connection.row_factory = sqlite3.Row",
"connection.execute('PRAGMA foreign_keys = ON')",
"apply_migrations(connection)",
- "connection.execute('INSERT INTO workspaces (id, created_at, updated_at) VALUES (?, ?, ?)', ('workspace', '1', '1'))",
+ "timestamp = '2026-10-08T00:00:00Z'",
+ "connection.execute('INSERT INTO workspaces (id, created_at, updated_at) VALUES (?, ?, ?)', ('workspace', timestamp, timestamp))",
"for scan_id, scan_dir in [('scan', sys.argv[2] + '/scan'), ('sibling', sys.argv[2] + ' Other/scan')]:",
- " connection.execute('INSERT INTO scans (id, workspace_id, target_path, target_revision, scope, mode, scan_dir, status, phase, started_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (scan_id, 'workspace', 'repository', 'revision', '.', 'standard', scan_dir, 'complete', 'reporting', '1', '1', '1'))",
- " connection.execute('INSERT INTO scan_progress (scan_id, scope_file_count, review_items_completed, review_items_total, updated_at) VALUES (?, 1, 1, 1, ?)', (scan_id, '1'))",
+ " connection.execute('INSERT INTO scans (id, workspace_id, target_path, target_revision, scope, mode, scan_dir, status, phase, started_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (scan_id, 'workspace', 'repository', 'revision', '.', 'standard', scan_dir, 'complete', 'reporting', timestamp, timestamp, timestamp))",
+ " connection.execute('INSERT INTO scan_progress (scan_id, scope_file_count, review_items_completed, review_items_total, updated_at) VALUES (?, 1, 1, 1, ?)', (scan_id, timestamp))",
"args = argparse.Namespace(repository=None, scan_root=sys.argv[3], target_id=None, mode=None, status=None, query=None, limit=None, offset=0)",
"print(json.dumps(history.list_scans(connection, args)))",
].join("\n");