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(logs): persist terminal scan boundaries (#1527)

Peter1deca2d70eda
diff --git a/plugins/codex-security/mcp-app/tests/test_workbench_database.ts b/plugins/codex-security/mcp-app/tests/test_workbench_database.ts
index a06cc4f8b..5f9c73d69 100644
--- a/plugins/codex-security/mcp-app/tests/test_workbench_database.ts
+++ b/plugins/codex-security/mcp-app/tests/test_workbench_database.ts
@@ -175,6 +175,47 @@ test("every released schema upgrades to the same current schema and remains idem
}
});
+test("log completion migration leaves legacy terminal boundaries unknown", (t) => {
+ const database = memory(t, 49);
+ insertScan(database);
+ database.exec(
+ "UPDATE scans SET status = 'complete', completed_at = 'artifact-time', updated_at = 'later-edit'",
+ );
+
+ applyMigrations(database);
+
+ assert.deepEqual(
+ {
+ ...database
+ .prepare("SELECT completed_at, updated_at, log_completed_at FROM scans")
+ .get(),
+ },
+ {
+ completed_at: "artifact-time",
+ updated_at: "later-edit",
+ log_completed_at: null,
+ },
+ );
+});
+
+for (const version of [48, 50, 63]) {
+ test(`preserves terminal logs from preview migration ${version}`, (t) => {
+ const database = memory(t, version - 1);
+ const boundary = migrations.find((item) => item.version === 64)!;
+ applyMigrations(database, [{ ...boundary, version }]);
+ insertScan(database);
+ database.exec("UPDATE scans SET log_completed_at = 'saved-boundary'");
+ applyMigrations(database);
+ applyMigrations(database);
+ assertMigrationNames(database, version, 63, 64);
+ assert.equal(
+ database.prepare("SELECT log_completed_at FROM scans").get()
+ ?.log_completed_at,
+ "saved-boundary",
+ );
+ });
+}
+
for (const previewVersion of [58, 59]) {
test(`preserves the saved rubric from preview migration ${previewVersion}`, (t) => {
const database = memory(t, previewVersion - 1);
diff --git a/plugins/codex-security/scripts/workbench_db.py b/plugins/codex-security/scripts/workbench_db.py
index f66ccc6e1..ee4cee6eb 100644
--- a/plugins/codex-security/scripts/workbench_db.py
+++ b/plugins/codex-security/scripts/workbench_db.py
@@ -1454,12 +1454,14 @@ def complete_scan_locked(
"""
UPDATE scans
SET status = 'complete', phase = 'reporting', completed_at = ?, updated_at = ?,
- seal_manifest_digest = ?, cost_json = ?, completion_warnings_json = ?
+ log_completed_at = ?, seal_manifest_digest = ?, cost_json = ?,
+ completion_warnings_json = ?
WHERE id = ? AND status = 'running'
""",
(
timestamp,
timestamp,
+ now(),
manifest_digest,
cost_json,
json.dumps(warnings),
@@ -2819,6 +2821,7 @@ def scan_result(
"artifacts": artifacts,
**model_fields,
"canceledAt": scan["canceled_at"],
+ "logCompletedAt": scan["log_completed_at"],
**scan_usage.stored_scan_cost_fields(scan["cost_json"]),
"contract": scan_contract(scan),
"continuationThreadId": scan["continuation_thread_id"],
diff --git a/plugins/codex-security/scripts/workbench_saved_results.py b/plugins/codex-security/scripts/workbench_saved_results.py
index d98ae9e3b..f0598f2c6 100644
--- a/plugins/codex-security/scripts/workbench_saved_results.py
+++ b/plugins/codex-security/scripts/workbench_saved_results.py
@@ -1243,10 +1243,11 @@ def mark_running_scan_failed(
) -> bool:
updated = connection.execute(
"""
- UPDATE scans SET status = 'failed', failure_message = ?, completed_at = ?, updated_at = ?
+ UPDATE scans SET status = 'failed', failure_message = ?, completed_at = ?, updated_at = ?,
+ log_completed_at = ?
WHERE id = ? AND status = 'running'
""",
- (message, timestamp, timestamp, scan_id),
+ (message, timestamp, timestamp, timestamp, scan_id),
)
return updated.rowcount == 1
@@ -1328,10 +1329,10 @@ def cancel_scan_locked(db: Any, connection: Any, args: Any) -> dict[str, Any]:
updated = connection.execute(
"""
UPDATE scans
- SET status = 'failed', canceled_at = ?, completed_at = ?, updated_at = ?
+ SET status = 'failed', canceled_at = ?, completed_at = ?, updated_at = ?, log_completed_at = ?
WHERE id = ? AND status = 'running'
""",
- (timestamp, timestamp, timestamp, scan["id"]),
+ (timestamp, timestamp, timestamp, timestamp, scan["id"]),
)
if updated.rowcount != 1:
raise SystemExit("Only a running scan can be canceled.")
diff --git a/plugins/codex-security/scripts/workbench_scan_history.py b/plugins/codex-security/scripts/workbench_scan_history.py
index 78df631a9..aba6045db 100644
--- a/plugins/codex-security/scripts/workbench_scan_history.py
+++ b/plugins/codex-security/scripts/workbench_scan_history.py
@@ -311,6 +311,7 @@ def scan_with_progress(connection: sqlite3.Connection, scan_id: str) -> sqlite3.
def scan_summary(row: sqlite3.Row) -> dict[str, Any]:
return {
"completedAt": row["completed_at"],
+ "logCompletedAt": row["log_completed_at"],
"continuationThreadId": row["continuation_thread_id"],
**stored_scan_cost_fields(row["cost_json"]),
"findingCount": row["finding_count"],
diff --git a/plugins/codex-security/shared/workbench-history-repairs.json b/plugins/codex-security/shared/workbench-history-repairs.json
index 9f2112514..3d292e9bc 100644
--- a/plugins/codex-security/shared/workbench-history-repairs.json
+++ b/plugins/codex-security/shared/workbench-history-repairs.json
@@ -3,6 +3,8 @@
"WITH input AS (SELECT :history AS history),",
"previews AS (",
" SELECT version, CASE",
+ " WHEN version IN (48, 50, 63) AND name = 'persist scan log completion boundaries'",
+ " THEN 'UPDATE schema_migrations SET version = 64'",
" WHEN version IN (58, 59) AND name = 'record classification rubric provenance'",
" THEN 'UPDATE schema_migrations SET version = 60'",
" WHEN version IN (47, 48, 50, 52, 53, 54) AND name = 'freeze stopped scan checkpoint selections'",
diff --git a/plugins/codex-security/shared/workbench-migrations.json b/plugins/codex-security/shared/workbench-migrations.json
index 987ff1e61..b41c16a32 100644
--- a/plugins/codex-security/shared/workbench-migrations.json
+++ b/plugins/codex-security/shared/workbench-migrations.json
@@ -517,5 +517,10 @@
"UPDATE deep_scan_runs SET worker_usage_gap = 1\nWHERE scan_id IN (\n SELECT w.scan_id FROM deep_scan_workers AS w\n WHERE w.kind IN ('discovery', 'dedup') AND w.attempt > 1\n AND w.started_at IS NOT NULL AND w.sdk_thread_id IS NULL\n AND NOT EXISTS (SELECT 1 FROM deep_scan_worker_threads AS t\n WHERE t.scan_id = w.scan_id AND t.worker_id = w.id)\n);",
"CREATE TRIGGER retain_unverified_deep_scan_worker_attempt\nAFTER UPDATE OF attempt ON deep_scan_workers\nWHEN NEW.attempt > OLD.attempt AND OLD.started_at IS NOT NULL\n AND OLD.sdk_thread_id IS NULL AND OLD.kind IN ('discovery', 'dedup')\nBEGIN\n UPDATE deep_scan_runs SET worker_usage_gap = 1 WHERE scan_id = OLD.scan_id;\nEND;"
]
+ },
+ {
+ "version": 64,
+ "name": "persist scan log completion boundaries",
+ "statements": ["ALTER TABLE scans ADD COLUMN log_completed_at TEXT;"]
}
]
diff --git a/plugins/codex-security/tests/test_deep_scan_successful_publication.py b/plugins/codex-security/tests/test_deep_scan_successful_publication.py
index 843e25c24..e3952c1a8 100644
--- a/plugins/codex-security/tests/test_deep_scan_successful_publication.py
+++ b/plugins/codex-security/tests/test_deep_scan_successful_publication.py
@@ -8,6 +8,7 @@ import json
import os
import shutil
from argparse import Namespace
+from datetime import datetime, timedelta
from pathlib import Path
import pytest
@@ -184,18 +185,45 @@ def reviewed_deep_scan(publication_scan, request):
return scan
-def test_deep_prepare_and_complete_preserve_the_same_aggregate(workbench_db, reviewed_deep_scan):
+def test_deep_prepare_and_complete_preserve_the_same_aggregate(
+ workbench_db, reviewed_deep_scan, monkeypatch
+):
scan = reviewed_deep_scan
+ clock = datetime.fromisoformat(scan.timestamp.replace("Z", "+00:00")) + timedelta(minutes=1)
+
+ def now():
+ return clock.isoformat().replace("+00:00", "Z")
+
+ monkeypatch.setitem(scan.api["complete_scan_locked"].__globals__, "now", now)
+ scan.api["set_scan_thread"](
+ workbench_db, Namespace(scan_id=scan.scan_id, thread_id="thread-prepared-resume")
+ )
count = "SELECT terminal_reviewed_surface_count FROM deep_scan_runs WHERE scan_id = ?"
assert workbench_db.execute(count, (scan.scan_id,)).fetchone()[0] is None
prepared = scan.complete(prepare_only=True)
assert prepared["progress"]["status"] == "running"
+ assert prepared["logCompletedAt"] is None
assert workbench_db.execute(count, (scan.scan_id,)).fetchone()[0] == 1
names = ("scan-manifest.json", "findings.json")
published = {name: (scan.scan_dir / name).read_bytes() for name in names}
- scan.complete(prepare_only=True)
- scan.complete()
+ clock += timedelta(minutes=1)
+ current = scan.api["require_scan"](workbench_db, scan.scan_id)
+ resumed = scan.api["scan_history"].cli_scan_resume(
+ scan.api["_WORKBENCH_DB_CONTEXT"],
+ workbench_db,
+ current,
+ scan.api["require_workspace"](workbench_db, current["workspace_id"]),
+ )
+ assert resumed["threadId"] == "thread-prepared-resume"
+ assert scan.complete(prepare_only=True)["logCompletedAt"] is None
+
+ clock += timedelta(minutes=1)
+ terminal_at = now()
+ assert scan.complete()["logCompletedAt"] == terminal_at
+ history = scan.api["scan_history"].list_scans(workbench_db)
+ assert history["scans"][0]["logCompletedAt"] == terminal_at
+ clock += timedelta(minutes=1)
# A capped scan with a failed worker cannot publish anew, but its sealed result can be read.
scan.add_worker(status="failed")
with workbench_db:
@@ -205,6 +233,7 @@ def test_deep_prepare_and_complete_preserve_the_same_aggregate(workbench_db, rev
)
repeated = scan.complete()
+ assert repeated["logCompletedAt"] == terminal_at
assert repeated["progress"]["status"] == "complete"
assert workbench_db.execute(count, (scan.scan_id,)).fetchone()[0] == 1
assert {name: (scan.scan_dir / name).read_bytes() for name in names} == published
diff --git a/plugins/codex-security/tests/test_workbench_cancellation.py b/plugins/codex-security/tests/test_workbench_cancellation.py
index aad54a5d7..13d661eb8 100644
--- a/plugins/codex-security/tests/test_workbench_cancellation.py
+++ b/plugins/codex-security/tests/test_workbench_cancellation.py
@@ -135,6 +135,11 @@ def test_workbench_records_scan_failure(tmp_path: Path) -> None:
)
assert failed["scan"]["progress"]["status"] == "failed"
assert failed["scan"]["failureMessage"] == "Repository checkout became unavailable."
+ assert failed["scan"]["logCompletedAt"] is not None
+ repeated = fail_scan(
+ state_dir, scan_id, "Ignored repeated failure.", "--claim-token", claim_token
+ )
+ assert repeated["scan"]["logCompletedAt"] == failed["scan"]["logCompletedAt"]
delivered = mark_handoff_delivered(state_dir, scan_id, claim_token)
assert delivered["results"]["handoffStatus"] == "delivered"
@@ -170,11 +175,13 @@ def test_workbench_cancels_running_scan_and_rejects_late_updates(tmp_path: Path)
assert canceled["results"]["cost"] == cost
assert canceled["results"]["progress"]["status"] == "canceled"
assert canceled["results"]["canceledAt"]
+ assert canceled["results"]["logCompletedAt"] == canceled["results"]["canceledAt"]
assert canceled["results"]["handoffClaimToken"] == claim_token
replayed = cancel_scan(state_dir, scan_id, thread_id)
assert replayed["results"]["cost"] == cost
assert replayed["results"]["canceledAt"] == canceled["results"]["canceledAt"]
+ assert replayed["results"]["logCompletedAt"] == canceled["results"]["logCompletedAt"]
for command in (
("update-progress", "--phase", "discovery"),
@@ -191,6 +198,7 @@ def test_workbench_cancels_running_scan_and_rejects_late_updates(tmp_path: Path)
restarted_scan_id = str(restarted["scanId"])
assert restarted_scan_id != scan_id
assert restarted["progress"]["status"] == "running"
+ assert restarted["logCompletedAt"] is None
previous_scan = get_scan(state_dir, scan_id)
lifecycle = previous_scan["scan"]["lifecycle"]
assert lifecycle["status"] == "canceled"
diff --git a/plugins/codex-security/tests/test_workbench_deep_scan.py b/plugins/codex-security/tests/test_workbench_deep_scan.py
index 4c0fd173c..9885462af 100644
--- a/plugins/codex-security/tests/test_workbench_deep_scan.py
+++ b/plugins/codex-security/tests/test_workbench_deep_scan.py
@@ -133,6 +133,7 @@ def restore_v53_schema(state_dir: Path) -> None:
connection.execute("ALTER TABLE deep_scan_runs DROP COLUMN worker_usage_gap")
connection.execute("DROP TRIGGER classify_legacy_scan_recipe")
connection.execute("DROP VIEW scan_lifecycles")
+ connection.execute("ALTER TABLE scans DROP COLUMN log_completed_at")
connection.execute("ALTER TABLE scans DROP COLUMN launch_kind")
connection.execute("ALTER TABLE scans DROP COLUMN launch_plugin_version")
connection.execute("ALTER TABLE scans DROP COLUMN launch_package_version")
@@ -3159,6 +3160,7 @@ def test_saturated_run_without_manifest_can_be_marked_failed_or_interrupted(
assert scan["progress"]["status"] == "failed"
assert scan["progress"]["independentReviews"]["consolidating"] is False
assert scan["failureMessage"] == terminal["error"]
+ assert scan["logCompletedAt"] == terminal["completedAt"]
def test_succeeded_run_with_manifest_cannot_be_marked_interrupted(tmp_path: Path) -> None:
diff --git a/plugins/codex-security/tests/test_workbench_setup_and_migrations.py b/plugins/codex-security/tests/test_workbench_setup_and_migrations.py
index 24a257fc8..9568bbc3f 100644
--- a/plugins/codex-security/tests/test_workbench_setup_and_migrations.py
+++ b/plugins/codex-security/tests/test_workbench_setup_and_migrations.py
@@ -108,6 +108,7 @@ EXPECTED_MIGRATIONS = [
(61, "record scan launch attribution"),
(62, "project scan lifecycle snapshots"),
(63, "retain unverified Deep Scan worker attempts"),
+ (64, "persist scan log completion boundaries"),
]
@@ -1146,6 +1147,58 @@ def test_scan_model_migration_preserves_existing_scans(complete: bool) -> None:
}
[email protected]("preview_version", [48, 50, 63])
+def test_log_boundary_preview_preserves_saved_boundary_and_repairs_history(preview_version):
+ name = "persist scan log completion boundaries"
+ connection, apply_migrations = create_historical_database(
+ preview_version,
+ ((preview_version, name, "ALTER TABLE scans ADD COLUMN log_completed_at TEXT;"),),
+ )
+ insert_historical_row(connection, "workspaces", "created", id="workspace")
+ insert_legacy_scan(
+ connection, "created", id="preview", workspace_id="workspace", log_completed_at="boundary"
+ )
+
+ apply_migrations(connection)
+ apply_migrations(connection)
+
+ assert (
+ connection.execute("SELECT log_completed_at FROM scans WHERE id = 'preview'").fetchone()[0]
+ == "boundary"
+ )
+ assert [
+ tuple(row)
+ for row in connection.execute(
+ "SELECT version, name FROM schema_migrations WHERE version IN (63,64) ORDER BY version"
+ )
+ ] == [(63, "retain unverified Deep Scan worker attempts"), (64, name)]
+ assert "worker_usage_gap" in {
+ row["name"] for row in connection.execute("PRAGMA table_info(deep_scan_runs)")
+ }
+
+
+def test_log_completion_migration_preserves_unknown_legacy_boundaries() -> None:
+ connection, apply_migrations = create_historical_database(64)
+ insert_historical_row(connection, "workspaces", "created", id="legacy-workspace")
+ for case in ("running", "complete", "failed", "canceled"):
+ insert_legacy_scan(
+ connection,
+ "later-edit",
+ id=case,
+ scan_dir=f"/legacy/{case}",
+ status="failed" if case == "canceled" else case,
+ completed_at=None if case == "running" else "artifact-time",
+ canceled_at="cancel-time" if case == "canceled" else None,
+ )
+ connection.commit()
+ before = [dict(row) for row in connection.execute("SELECT * FROM scans ORDER BY id")]
+
+ apply_migrations(connection)
+
+ after = [dict(row) for row in connection.execute("SELECT * FROM scans ORDER BY id")]
+ assert after == [{**row, "log_completed_at": None} for row in before]
+
+
@pytest.mark.parametrize(
("recipe", "kind", "mode", "is_mock", "plugin_version", "registered_version"),
(
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index 82eadf250..3d2b6d2a8 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -2100,6 +2100,12 @@ History lives in `$CODEX_SECURITY_STATE_DIR/workbench.sqlite3`, or
writable, and outside the target repository. Session logs may contain sensitive
data even though scan recipes do not store credentials.
+Saved scan logs retain the finishing turn, including its final response, and
+exclude later turns once the scan records a completion boundary. Older scans
+retain the full history of their attributed sessions and keep their existing
+worker-selection boundaries. This also applies to logs attached with
+`feedback --include-logs`.
+
Codex may compress saved session logs to `.jsonl.zst`. Plain and compressed logs
work on all supported Node.js versions, including logs, feedback attachments,
usage accounting, and saved-session discovery for resume. A bundled decoder
diff --git a/sdk/typescript/src/feedback.ts b/sdk/typescript/src/feedback.ts
index 13be1e434..7ff635553 100644
--- a/sdk/typescript/src/feedback.ts
+++ b/sdk/typescript/src/feedback.ts
@@ -11,7 +11,11 @@ import {
resolveCodexCommand,
type StartCodex,
} from "./runtime.js";
-import { readSavedScanLogs, type ScanLogSource } from "./scan-logs.js";
+import {
+ readSavedScanLogs,
+ savedScanLogBoundaries,
+ type ScanLogSource,
+} from "./scan-logs.js";
import {
BUNDLED_PLUGIN_VERSION,
CODEX_EXECUTABLE_VERSION,
@@ -135,13 +139,14 @@ export async function sendFeedback(
params: {
classification: "bug",
reason: options.reason,
- // Codex also collects this thread's descendants. Shared owners
- // belong only in the explicit attachment, not in that subtree.
+ // Codex collects the whole thread and its descendants. Use the
+ // scoped attachment for shared owners and completed scan turns.
threadId:
!includeLogs ||
- scan?.executionThreadIds?.includes(
+ (scan?.executionThreadIds?.includes(
scan.continuationThreadId ?? "",
- )
+ ) &&
+ savedScanLogBoundaries(scan).logCompletedAt === null)
? scan?.continuationThreadId
: undefined,
includeLogs,
diff --git a/sdk/typescript/src/scan-logs.ts b/sdk/typescript/src/scan-logs.ts
index c422392f2..c83a3fc3a 100644
--- a/sdk/typescript/src/scan-logs.ts
+++ b/sdk/typescript/src/scan-logs.ts
@@ -12,6 +12,7 @@ import {
sessionParentThreadId,
sessionStartedAt,
} from "./scan-sessions.js";
+import { compareTimestamps } from "./timestamps.js";
interface ScanLogOptions {
scanId: string;
@@ -22,6 +23,7 @@ interface ScanLogOptions {
scanDirectory?: string;
startedAt?: string;
completedAt?: string | null;
+ logCompletedAt?: string | null;
allowMissingRoot?: boolean;
}
@@ -32,10 +34,28 @@ export type ScanLogSource = JsonObject & {
executionThreadIds?: string[];
mode?: string;
scanDir?: string;
+ logCompletedAt?: string | null;
lifecycle?: { startedAt: string; finishedAt?: string | null };
progress?: { status?: string; updatedAt?: string };
};
+export function savedScanLogBoundaries(scan: ScanLogSource) {
+ const status = scan.progress?.status;
+ const terminal =
+ status === "complete" || status === "failed" || status === "canceled";
+ return {
+ // Legacy completion still bounds inferred workers, but cannot identify the
+ // final scan turn when sealed artifacts were completed before a resume.
+ completedAt:
+ status === "running"
+ ? null
+ : terminal
+ ? (scan.lifecycle?.finishedAt ?? scan.progress?.updatedAt ?? "")
+ : "",
+ logCompletedAt: terminal ? (scan.logCompletedAt ?? null) : null,
+ };
+}
+
export function readSavedScanLogs(
scan: ScanLogSource,
codexHome: string | readonly string[],
@@ -56,14 +76,7 @@ export function readSavedScanLogs(
allowMissingRoot: options.allowMissingRoot,
scanDirectory: scan.mode === "deep" ? scan.scanDir : undefined,
startedAt: scan.lifecycle?.startedAt,
- completedAt:
- scan.progress?.status === "running"
- ? null
- : scan.progress?.status === "complete" ||
- scan.progress?.status === "failed" ||
- scan.progress?.status === "canceled"
- ? (scan.lifecycle?.finishedAt ?? scan.progress.updatedAt ?? "")
- : "",
+ ...savedScanLogBoundaries(scan),
});
}
@@ -81,6 +94,10 @@ async function* scanSessions(codexHome: string, directory = "sessions") {
threadId,
parentThreadId: sessionParentThreadId(metadata),
startedAt: sessionStartedAt(metadata["timestamp"]),
+ timestamp:
+ typeof metadata["timestamp"] === "string"
+ ? metadata["timestamp"]
+ : null,
workingDirectory:
typeof metadata["cwd"] === "string" ? metadata["cwd"] : null,
path,
@@ -119,6 +136,11 @@ export async function readScanLogs(options: ScanLogOptions) {
);
}
+ const startsAfterCompletion = (timestamp: unknown) =>
+ typeof options.logCompletedAt === "string" &&
+ typeof timestamp === "string" &&
+ compareTimestamps(timestamp, options.logCompletedAt) >= 0;
+
const included = new Set([
...(options.threadId ? [options.threadId] : []),
...(options.threadIds ?? []),
@@ -163,7 +185,7 @@ export async function readScanLogs(options: ScanLogOptions) {
for (const session of children.get(null) ?? []) {
if (
session !== root &&
- belongsToScan(session, directories, startedAt, options.completedAt)
+ belongsToScan(session, directories, startedAt, options)
) {
included.add(session.threadId);
traversed.add(session.threadId);
@@ -172,6 +194,7 @@ export async function readScanLogs(options: ScanLogOptions) {
}
for (const parentId of traversed) {
for (const session of children.get(parentId) ?? []) {
+ if (startsAfterCompletion(session.timestamp)) continue;
included.add(session.threadId);
traversed.add(session.threadId);
}
@@ -187,6 +210,8 @@ export async function readScanLogs(options: ScanLogOptions) {
sessions.push(session);
}
const events: Record<string, unknown>[] = [];
+ // Recorded completion can precede the scan turn's final response. Keep that
+ // turn's remaining events, then stop before a post-completion turn starts.
for (const session of sessions) {
let replaying = false;
for await (const event of sessionEvents(session.path)) {
@@ -194,17 +219,15 @@ export async function readScanLogs(options: ScanLogOptions) {
if (event["type"] === "session_meta" && isRecord(payload)) {
replaying = payload["id"] !== session.threadId;
}
+ const taskStarted =
+ event["type"] === "event_msg" &&
+ isRecord(payload) &&
+ payload["type"] === "task_started";
if (replaying) {
- if (
- event["type"] !== "event_msg" ||
- !isRecord(payload) ||
- payload["type"] !== "task_started" ||
- !sessionOwnsTurn(session, payload)
- ) {
- continue;
- }
+ if (!taskStarted || !sessionOwnsTurn(session, payload)) continue;
replaying = false;
}
+ if (taskStarted && startsAfterCompletion(event["timestamp"])) break;
events.push({ threadId: session.threadId, event });
}
}
@@ -225,7 +248,7 @@ function belongsToScan(
session: SessionLog,
directories: string[],
startedAt: number,
- completedAt: string | null | undefined,
+ options: ScanLogOptions,
): boolean {
if (
session.workingDirectory === null ||
@@ -234,12 +257,12 @@ function belongsToScan(
) {
return false;
}
- if (completedAt !== undefined && completedAt !== null) {
- const completed = Date.parse(completedAt);
- if (!Number.isFinite(completed) || session.startedAt >= completed) {
- return false;
- }
- }
+ const beforeCompletion =
+ typeof options.logCompletedAt === "string" && session.timestamp !== null
+ ? compareTimestamps(session.timestamp, options.logCompletedAt) < 0
+ : options.completedAt == null ||
+ session.startedAt < Date.parse(options.completedAt);
+ if (!beforeCompletion) return false;
for (const directoryRoot of directories) {
if (isScanArtifactDirectory(directoryRoot, session.workingDirectory)) {
diff --git a/sdk/typescript/tests-ts/feedback.test.ts b/sdk/typescript/tests-ts/feedback.test.ts
index 87325d259..35e667c5b 100644
--- a/sdk/typescript/tests-ts/feedback.test.ts
+++ b/sdk/typescript/tests-ts/feedback.test.ts
@@ -11,6 +11,7 @@ import { sendFeedback } from "../src/feedback.js";
import { codexSecurityCredentialHome } from "../src/runtime.js";
import { VERSION, BUNDLED_PLUGIN_VERSION } from "../src/version.js";
import { throwing } from "./support/errors.js";
+import { writeJsonLines } from "./support/json.js";
const fixture = fileURLToPath(
new URL("fixtures/feedback.mjs", import.meta.url),
@@ -43,10 +44,32 @@ async function setup() {
source: { subagent: { thread_spawn: { parent_thread_id: "thread-1" } } },
},
};
- await writeFile(
- join(home, "sessions", "rollout-root.jsonl"),
- JSON.stringify(root),
- );
+ await writeJsonLines(join(home, "sessions", "rollout-root.jsonl"), [
+ root,
+ {
+ type: "event_msg",
+ timestamp: "2026-08-21T12:01:59Z",
+ payload: { type: "task_started", turn_id: "scan-turn" },
+ },
+ {
+ type: "event_msg",
+ timestamp: "2026-08-21T12:02:01Z",
+ payload: { type: "agent_message", message: "The scan is complete." },
+ },
+ {
+ type: "event_msg",
+ timestamp: "2026-08-21T12:03:00Z",
+ payload: { type: "task_started", turn_id: "configured-followup" },
+ },
+ {
+ type: "event_msg",
+ timestamp: "2026-08-21T12:03:01Z",
+ payload: {
+ type: "user_message",
+ message: "Configured follow-up prompt.",
+ },
+ },
+ ]);
await writeFile(
join(home, "sessions", "rollout-worker.jsonl"),
JSON.stringify(worker),
@@ -77,6 +100,8 @@ async function setup() {
includeLogs: true,
scan: {
scanId: "scan-1",
+ progress: { status: "complete" },
+ logCompletedAt: "2026-08-21T12:02:00Z",
continuationThreadId: "thread-1",
threadIds: ["thread-1"],
executionThreadIds: ["thread-1"],
@@ -105,7 +130,6 @@ test("uploads selected scan and worker logs through Codex and removes temporary
expect(requests[2].params).toMatchObject({
classification: "bug",
reason: "Scan stopped",
- threadId: "thread-1",
includeLogs: true,
tags: {
codex_security_version: VERSION,
@@ -113,16 +137,43 @@ test("uploads selected scan and worker logs through Codex and removes temporary
codex_security_scan_id: "scan-1",
},
});
+ expect(requests[2].params).not.toHaveProperty("threadId");
expect(attachments).toHaveLength(1);
expect(
JSON.parse(attachments[0].content).sessions.map(
(session: { threadId: string }) => session.threadId,
),
).toEqual(["thread-1", "worker-1"]);
+ expect(attachments[0].content).toContain("The scan is complete.");
+ expect(attachments[0].content).not.toContain("Configured follow-up prompt.");
expect(existsSync(attachments[0].path)).toBe(false);
context.expectClosed();
});
+test.each([
+ ["complete", null],
+ ["running", "2026-08-21T12:02:00Z"],
+] as const)(
+ "uploads the full execution thread for a %s scan without an active log cutoff",
+ async (status, logCompletedAt) => {
+ const context = await setup();
+ await sendFeedback(
+ {
+ ...context.options,
+ scan: {
+ ...context.options.scan,
+ progress: { status },
+ logCompletedAt,
+ },
+ },
+ context.startCodex,
+ );
+ const { requests, attachments } = await context.transcript();
+ expect(requests[2].params.threadId).toBe("thread-1");
+ expect(attachments[0].content).toContain("Configured follow-up prompt.");
+ },
+);
+
for (const missingParent of [false, true]) {
test(`uploads only the selected Desktop scan logs with parent ${missingParent ? "missing" : "available"}`, async () => {
const context = await setup();
@@ -245,6 +296,7 @@ test("without log opt-in, does not read or attach saved sessions", async () => {
).toBe(false);
const { requests, attachments } = await context.transcript();
expect(requests[2].params.includeLogs).toBe(false);
+ expect(requests[2].params.threadId).toBe("thread-1");
expect(requests[2].params.extraLogFiles).toEqual([]);
expect(attachments).toEqual([]);
});
diff --git a/sdk/typescript/tests-ts/scan-logs.test.ts b/sdk/typescript/tests-ts/scan-logs.test.ts
index 491445dcc..cd5bed3f4 100644
--- a/sdk/typescript/tests-ts/scan-logs.test.ts
+++ b/sdk/typescript/tests-ts/scan-logs.test.ts
@@ -62,6 +62,14 @@ function commandEvent(command: string, id: string, timestamp?: string) {
};
}
+function taskStarted(turnId: string, timestamp?: string) {
+ return {
+ type: "event_msg",
+ ...(timestamp === undefined ? {} : { timestamp }),
+ payload: { type: "task_started", turn_id: turnId },
+ };
+}
+
describe("saved scan logs", () => {
test.each([
["prefix first", [0], [0, 1, 1, 2], 1, false, false],
@@ -321,6 +329,91 @@ describe("saved scan logs", () => {
},
);
+ const justBeforeCompletion = "2026-08-11T12:03:00.123Z";
+ const preciseCompletion = "2026-08-11T12:03:00.123789Z";
+ test.each([
+ ["complete", preciseCompletion],
+ ["failed", preciseCompletion],
+ ["canceled", preciseCompletion],
+ ["complete", null],
+ ["complete", undefined],
+ ] as const)(
+ "preserves resumed workers with status %s and log boundary %p",
+ async (status, logCompletedAt) => {
+ const home = await temporaryHome();
+ const scanDirectory = join(home, "scans", "resumed");
+ const artifacts = join(scanDirectory, "artifacts");
+ const afterCompletion = "2026-08-11T12:04:00.000Z";
+ const resumed = [
+ taskStarted("resume-turn", "2026-08-11T12:02:00.000Z"),
+ commandEvent("resumed scan work", "resume-call"),
+ ];
+ const followup = [
+ taskStarted("followup-turn", afterCompletion),
+ commandEvent("post-scan followup", "post-call"),
+ ];
+ await writeSession(
+ home,
+ "parent",
+ [...resumed, ...followup],
+ undefined,
+ "2026-08-11T12:00:00.000Z",
+ scanDirectory,
+ );
+ for (const [threadId, startedAt, directory] of [
+ ["recorded-worker", afterCompletion, artifacts],
+ ["resumed-worker", justBeforeCompletion, artifacts],
+ ["followup-worker", afterCompletion, artifacts],
+ [
+ "unrelated-worker",
+ justBeforeCompletion,
+ join(home, "other-scan", "artifacts"),
+ ],
+ ] as const) {
+ await writeSession(home, threadId, [], undefined, startedAt, directory);
+ }
+
+ await writeSession(
+ home,
+ "followup-child",
+ [commandEvent("post-scan child work", "child-call")],
+ "parent",
+ afterCompletion,
+ );
+
+ const result = await readSavedScanLogs(
+ {
+ scanId: "resumed-scan",
+ mode: "deep",
+ scanDir: scanDirectory,
+ continuationThreadId: "parent",
+ executionThreadIds: ["parent", "recorded-worker"],
+ progress: {
+ status,
+ updatedAt: "2026-08-11T12:01:00.000Z",
+ },
+ updatedAt: "2026-08-11T12:05:00.000Z",
+ ...(logCompletedAt === undefined ? {} : { logCompletedAt }),
+ },
+ home,
+ );
+
+ const expected =
+ logCompletedAt == null ? [...resumed, ...followup] : resumed;
+ expect(
+ result.events.filter(({ threadId }) => threadId === "parent").slice(1),
+ ).toEqual(expected.map((event) => ({ threadId: "parent", event })));
+ expect(result.sessions.map(({ threadId }) => threadId).sort()).toEqual(
+ logCompletedAt == null
+ ? ["followup-child", "parent", "recorded-worker"]
+ : ["parent", "recorded-worker", "resumed-worker"],
+ );
+ expect(
+ result.events.some(({ threadId }) => threadId === "followup-child"),
+ ).toBe(logCompletedAt == null);
+ },
+ );
+
test("feedback returns an empty log set when no scan threads are recorded", async () => {
const home = await temporaryHome();
await writeSession(home, "unrelated", []);
@@ -740,6 +833,22 @@ describe("saved scan logs", () => {
expect(JSON.stringify(archivedLogs)).toContain("review archived scan");
expect(JSON.stringify(archivedLogs)).not.toContain("PRIVATE REPLACEMENT");
+ for (const logCompletedAt of [null, undefined]) {
+ const legacyLogs = await readSavedScanLogs(
+ {
+ scanId: "archived-scan",
+ mode: "deep",
+ scanDir: archived,
+ continuationThreadId: "archived-parent",
+ executionThreadIds: ["archived-parent"],
+ progress: { status: "complete", updatedAt: completedAt },
+ ...(logCompletedAt === undefined ? {} : { logCompletedAt }),
+ },
+ home,
+ );
+ expect(legacyLogs).toEqual(archivedLogs);
+ }
+
const unrelatedRoot = await readScanLogs({
...options,
scanDirectory: join(home, "scans", "unrelated.previous-fixture"),
@@ -762,6 +871,84 @@ describe("saved scan logs", () => {
);
});
+ const scanCompletion = "2026-08-11T12:02:00.000Z";
+ const followupStart = "2026-08-11T12:03:00.000Z";
+ test.each([
+ ["without a follow-up", scanCompletion, null, false],
+ ["with a follow-up", scanCompletion, followupStart, true],
+ ["with a follow-up at completion", followupStart, followupStart, true],
+ [
+ "with a turn just before completion",
+ preciseCompletion,
+ justBeforeCompletion,
+ false,
+ ],
+ ["while running", null, followupStart, false],
+ ["without completion", undefined, followupStart, false],
+ ["with invalid completion", "invalid", followupStart, false],
+ ["without a turn timestamp", scanCompletion, undefined, false],
+ ["with an invalid turn timestamp", scanCompletion, "invalid", false],
+ ] as const)(
+ "preserves the finishing scan turn %s",
+ async (_label, completedAt, followupAt, excludeFollowup) => {
+ const home = await temporaryHome();
+ const scanEvents = [
+ taskStarted("scan-turn", "2026-08-11T12:00:00.000Z"),
+ {
+ timestamp: "2026-08-11T12:01:59.000Z",
+ type: "response_item",
+ payload: {
+ type: "function_call",
+ name: "mcp__codex_security__complete_codex_security_scan",
+ call_id: "completion-call",
+ arguments: "{}",
+ },
+ },
+ {
+ timestamp: "2026-08-11T12:02:01.000Z",
+ type: "response_item",
+ payload: {
+ type: "function_call_output",
+ call_id: "completion-call",
+ output: "Scan completed.",
+ },
+ },
+ {
+ timestamp: "2026-08-11T12:02:02.000Z",
+ type: "event_msg",
+ payload: { type: "agent_message", message: "Scan report is ready." },
+ },
+ {
+ timestamp: "2026-08-11T12:02:03.000Z",
+ type: "event_msg",
+ payload: { type: "task_complete", turn_id: "scan-turn" },
+ },
+ ];
+ const followup =
+ followupAt === null
+ ? []
+ : [
+ taskStarted("followup-turn", followupAt),
+ commandEvent("post-scan followup", "post-call"),
+ ];
+ await writeSession(home, "parent", [...scanEvents, ...followup]);
+
+ const result = await readScanLogs({
+ scanId: "scan-555",
+ threadId: "parent",
+ codexHome: home,
+ logCompletedAt: completedAt,
+ });
+
+ const expected = excludeFollowup
+ ? scanEvents
+ : [...scanEvents, ...followup];
+ expect(result.events.slice(1)).toEqual(
+ expected.map((event) => ({ threadId: "parent", event })),
+ );
+ },
+ );
+
test.each([false, true])(
"does not parse event bodies from unrelated saved sessions (copied: %p)",
async (copied) => {