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(feedback): collect Desktop and worker session logs (#872)

Dane Schneiderd640a182854e
diff --git a/plugins/codex-security/scripts/workbench_db.py b/plugins/codex-security/scripts/workbench_db.py
index cc482f3f1..4ca4460b3 100644
--- a/plugins/codex-security/scripts/workbench_db.py
+++ b/plugins/codex-security/scripts/workbench_db.py
@@ -2846,6 +2846,8 @@ def scan_result(
**scan_usage.stored_scan_cost_fields(scan["cost_json"]),
"contract": scan_contract(scan),
"continuationThreadId": scan["continuation_thread_id"],
+ "threadIds": scan_usage._scan_root_thread_ids(connection, scan, None),
+ "executionThreadIds": scan_usage._scan_execution_thread_ids(connection, scan),
"failureMessage": scan["failure_message"],
"findings": [
finding_result(connection, scan, row, related=relations.get(row["id"], []))
diff --git a/plugins/codex-security/scripts/workbench_scan_usage.py b/plugins/codex-security/scripts/workbench_scan_usage.py
index 3322cb187..648924d92 100644
--- a/plugins/codex-security/scripts/workbench_scan_usage.py
+++ b/plugins/codex-security/scripts/workbench_scan_usage.py
@@ -174,18 +174,21 @@ def _scan_root_thread_ids(
connection: sqlite3.Connection,
scan: sqlite3.Row,
supplied_thread_id: str | None,
+ *,
+ include_owner_threads: bool = True,
) -> list[str]:
candidates: list[str | None] = [supplied_thread_id]
- if "continuation_thread_id" in scan.keys():
- candidates.append(scan["continuation_thread_id"])
- if "deep_scan_owner_thread_id" in scan.keys():
- candidates.append(scan["deep_scan_owner_thread_id"])
- workspace = connection.execute(
- "SELECT thread_id FROM workspaces WHERE id = ?",
- (scan["workspace_id"],),
- ).fetchone()
- if workspace is not None:
- candidates.append(workspace["thread_id"])
+ if include_owner_threads:
+ if "continuation_thread_id" in scan.keys():
+ candidates.append(scan["continuation_thread_id"])
+ if "deep_scan_owner_thread_id" in scan.keys():
+ candidates.append(scan["deep_scan_owner_thread_id"])
+ workspace = connection.execute(
+ "SELECT thread_id FROM workspaces WHERE id = ?",
+ (scan["workspace_id"],),
+ ).fetchone()
+ if workspace is not None:
+ candidates.append(workspace["thread_id"])
if scan["mode"] == "deep":
candidates.extend(
row["sdk_thread_id"]
@@ -208,6 +211,16 @@ def _scan_root_thread_ids(
return roots
+def _scan_execution_thread_ids(connection: sqlite3.Connection, scan: sqlite3.Row) -> list[str]:
+ # CLI recipes identify dedicated executions; Desktop continuations can be shared.
+ return _scan_root_thread_ids(
+ connection,
+ scan,
+ scan["continuation_thread_id"] if scan["recipe_json"] is not None else None,
+ include_owner_threads=False,
+ )
+
+
def _codex_state_database() -> Path | None:
configured_database = os.environ.get("CODEX_STATE_DB", "").strip()
if configured_database:
diff --git a/plugins/codex-security/tests/test_workbench_scan_history.py b/plugins/codex-security/tests/test_workbench_scan_history.py
index 4db806d97..d69d57c3d 100644
--- a/plugins/codex-security/tests/test_workbench_scan_history.py
+++ b/plugins/codex-security/tests/test_workbench_scan_history.py
@@ -12,6 +12,8 @@ from pathlib import Path
from typing import Any
from test_workbench_db import HEAD_CHANGED_WARNING
+from test_workbench_deep_scan import begin_target_scan
+from test_workbench_prompt_only_scan import start_headless_standard_scan, start_prompt_only_scan
from workbench_test_support import (
initialize_git_repository,
mark_deep_coordinator_succeeded,
@@ -281,6 +283,9 @@ def test_cli_scan_persists_its_continuation_thread(tmp_path: Path) -> None:
repository = tmp_path / "repository"
repository.mkdir()
scan = create_cli_scan(state_dir, tmp_path / "results", repository, complete=False)
+ initial = run_workbench(state_dir, "get-scan", "--scan-id", scan["scanId"])["scan"]
+ assert initial["threadIds"] == []
+ assert initial["executionThreadIds"] == []
result = run_workbench(
state_dir,
@@ -294,6 +299,104 @@ def test_cli_scan_persists_its_continuation_thread(tmp_path: Path) -> None:
assert result == {"scanId": scan["scanId"], "threadId": "thread-1"}
detail = run_workbench(state_dir, "get-scan", "--scan-id", scan["scanId"])
assert detail["scan"]["continuationThreadId"] == "thread-1"
+ assert detail["scan"]["threadIds"] == ["thread-1"]
+ assert detail["scan"]["executionThreadIds"] == ["thread-1"]
+
+
+def test_get_scan_keeps_desktop_standard_owners_out_of_execution_roots(tmp_path: Path) -> None:
+ state_dir = tmp_path / "state"
+ for start_scan in (start_prompt_only_scan, start_headless_standard_scan):
+ repository = tmp_path / start_scan.__name__
+ repository.mkdir()
+ started = start_scan(
+ state_dir, repository, tmp_path / "results", thread_id="desktop-owner"
+ )["scan"]
+ detail = run_workbench(state_dir, "get-scan", "--scan-id", started["scanId"])["scan"]
+ assert detail["threadIds"] == ["desktop-owner"]
+ assert detail["executionThreadIds"] == []
+ if start_scan is start_headless_standard_scan:
+ assert detail["continuationThreadId"] == "desktop-owner"
+
+
+def test_get_scan_includes_desktop_deep_worker_threads_without_continuation(tmp_path: Path) -> None:
+ state_dir, codex_home = tmp_path / "state", tmp_path / "codex-home"
+ repository, other_repository = tmp_path / "repository", tmp_path / "other-repository"
+ repository.mkdir()
+ other_repository.mkdir()
+ scan = begin_target_scan(
+ state_dir, codex_home, repository, tmp_path / "results", thread_id="desktop-owner"
+ )["deepScan"]
+ other = begin_target_scan(
+ state_dir, codex_home, other_repository, tmp_path / "results", thread_id="other-owner"
+ )["deepScan"]
+ workers = [
+ (scan["scanId"], "setup", "succeeded", "setup-worker"),
+ (scan["scanId"], "discovery", "failed", "failed-worker"),
+ (scan["scanId"], "discovery", "canceled", "canceled-worker"),
+ (scan["scanId"], "dedup", "running", "dedup-worker"),
+ (scan["scanId"], "discovery", "running", "shared-worker"),
+ (scan["scanId"], "discovery", "succeeded", "shared-worker"),
+ (scan["scanId"], "discovery", "running", "desktop-workspace"),
+ (scan["scanId"], "discovery", "queued", None),
+ (other["scanId"], "discovery", "failed", "other-worker"),
+ ]
+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
+ connection.execute(
+ "UPDATE workspaces SET thread_id = 'desktop-workspace' "
+ "WHERE id = (SELECT workspace_id FROM scans WHERE id = ?)",
+ (scan["scanId"],),
+ )
+ connection.executemany(
+ """
+ INSERT INTO deep_scan_workers (
+ id, scan_id, kind, status, sdk_thread_id, prompt_path, artifact_dir,
+ created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """,
+ [
+ (
+ str(uuid.uuid4()),
+ scan_id,
+ kind,
+ status,
+ thread_id,
+ str(tmp_path / "prompt.md"),
+ str(tmp_path / "artifacts"),
+ scan["createdAt"],
+ scan["createdAt"],
+ )
+ for scan_id, kind, status, thread_id in workers
+ ],
+ )
+
+ detail = run_workbench(state_dir, "get-scan", "--scan-id", scan["scanId"])["scan"]
+ assert detail["continuationThreadId"] is None
+ assert detail["threadIds"] == [
+ "desktop-owner",
+ "desktop-workspace",
+ "canceled-worker",
+ "dedup-worker",
+ "failed-worker",
+ "setup-worker",
+ "shared-worker",
+ ]
+ assert detail["executionThreadIds"] == [
+ "canceled-worker",
+ "dedup-worker",
+ "desktop-workspace",
+ "failed-worker",
+ "setup-worker",
+ "shared-worker",
+ ]
+
+ with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
+ connection.execute(
+ "UPDATE scans SET continuation_thread_id = 'desktop-headless' WHERE id = ?",
+ (scan["scanId"],),
+ )
+ continued = run_workbench(state_dir, "get-scan", "--scan-id", scan["scanId"])["scan"]
+ assert continued["threadIds"] == ["desktop-headless", *detail["threadIds"]]
+ assert continued["executionThreadIds"] == detail["executionThreadIds"]
def test_cli_scan_preserves_original_revision_when_head_moves(tmp_path: Path) -> None:
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index e3ab1b51c..6cd71dd83 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -1411,6 +1411,18 @@ and worker activity. These can contain source code, prompts, findings, tool
output, and other sensitive data. Only include logs you can share with OpenAI.
The command uses Codex's feedback service and respects `feedback.enabled = false`.
+For scans started through the Desktop plugin, run the command on the machine
+where the scan ran, using the same Codex home and Codex Security state directory.
+It searches active and archived sessions in both that Codex home and the CLI's
+managed home, and attaches available worker logs even if the parent log is missing.
+Earlier retries that started separate sessions may be missing when their session
+IDs are no longer recorded.
+
+Standard scans run inside an existing Codex conversation attach only the owner's
+saved session; they do not record which subagents belong to the scan. Deep Scans
+and scans launched by `codex-security` also attach their recorded execution
+threads and descendants, without following unrelated children of the owner.
+
### Scan history and reruns
Commands default to the current repository. Select scans by full ID or a
diff --git a/sdk/typescript/src/feedback.ts b/sdk/typescript/src/feedback.ts
index 8d5ad22e6..db0966e47 100644
--- a/sdk/typescript/src/feedback.ts
+++ b/sdk/typescript/src/feedback.ts
@@ -7,7 +7,7 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createInterface } from "node:readline";
-import { readCodexHomeConfig } from "./auth.js";
+import { configuredCodexHome, readCodexHomeConfig } from "./auth.js";
import { CodexSecurityError } from "./errors.js";
import {
codexSecurityCredentialHome,
@@ -56,13 +56,27 @@ export async function sendFeedback(
try {
const extraLogFiles: string[] = [];
if (includeLogs && scan !== undefined) {
- const logs = await readSavedScanLogs(scan, codexHome);
- directory = await mkdtemp(join(tmpdir(), "codex-security-feedback-"));
- const path = join(directory, "scan-logs.json");
- await writeFile(path, JSON.stringify(logs), { mode: 0o600 });
- extraLogFiles.push(path);
+ try {
+ const logs = await readSavedScanLogs(
+ scan,
+ [codexHome, configuredCodexHome(environment)],
+ { allowMissingRoot: true },
+ );
+ if (logs.sessions.length > 0) {
+ directory = await mkdtemp(join(tmpdir(), "codex-security-feedback-"));
+ const path = join(directory, "scan-logs.json");
+ await writeFile(path, JSON.stringify(logs), { mode: 0o600 });
+ extraLogFiles.push(path);
+ }
+ } catch {
+ options.signal?.throwIfAborted();
+ console.warn(
+ "Codex Security could not attach saved scan logs; sending feedback with available Codex logs.",
+ );
+ }
}
+ options.signal?.throwIfAborted();
const command = resolveCodexCommand(environment);
const child = startCodex(
executablePathForSpawn(command.command),
@@ -108,7 +122,15 @@ export async function sendFeedback(
params: {
classification: "bug",
reason: options.reason,
- threadId: scan?.continuationThreadId,
+ // Codex also collects this thread's descendants. Shared owners
+ // belong only in the explicit attachment, not in that subtree.
+ threadId:
+ !includeLogs ||
+ scan?.executionThreadIds?.includes(
+ scan.continuationThreadId ?? "",
+ )
+ ? scan?.continuationThreadId
+ : undefined,
includeLogs,
extraLogFiles,
tags: {
diff --git a/sdk/typescript/src/scan-logs.ts b/sdk/typescript/src/scan-logs.ts
index 4c793a10d..0d57cbc87 100644
--- a/sdk/typescript/src/scan-logs.ts
+++ b/sdk/typescript/src/scan-logs.ts
@@ -12,31 +12,43 @@ import {
interface ScanLogOptions {
scanId: string;
- threadId: string;
- codexHome: string;
+ threadId?: string;
+ threadIds?: readonly string[];
+ executionThreadIds?: readonly string[];
+ codexHome: string | readonly string[];
scanDirectory?: string;
completedAt?: string | null;
+ allowMissingRoot?: boolean;
}
export type ScanLogSource = JsonObject & {
scanId: string;
continuationThreadId?: string;
+ threadIds?: string[];
+ executionThreadIds?: string[];
mode?: string;
scanDir?: string;
progress?: { status?: string; updatedAt?: string };
};
-export function readSavedScanLogs(scan: ScanLogSource, codexHome: string) {
+export function readSavedScanLogs(
+ scan: ScanLogSource,
+ codexHome: string | readonly string[],
+ options: { allowMissingRoot?: boolean } = {},
+) {
const threadId = scan.continuationThreadId;
- if (!threadId) {
+ if (!threadId && !options.allowMissingRoot) {
throw new CodexSecurityError(
`No session is associated with scan ${scan.scanId}.`,
);
}
return readScanLogs({
scanId: scan.scanId,
- threadId,
+ threadId: threadId ?? scan.threadIds?.[0],
+ threadIds: scan.threadIds,
+ executionThreadIds: scan.executionThreadIds ?? [],
codexHome,
+ allowMissingRoot: options.allowMissingRoot,
scanDirectory: scan.mode === "deep" ? scan.scanDir : undefined,
completedAt:
scan.progress?.status === "running"
@@ -57,8 +69,11 @@ interface SessionLog {
path: string;
}
-async function* scanSessions(codexHome: string): AsyncGenerator<SessionLog> {
- for await (const path of sessionFiles(join(codexHome, "sessions"))) {
+async function* scanSessions(
+ codexHome: string,
+ directory = "sessions",
+): AsyncGenerator<SessionLog> {
+ for await (const path of sessionFiles(join(codexHome, directory))) {
for await (const first of sessionEvents(path)) {
if (first["type"] !== "session_meta" || !isRecord(first["payload"])) {
break;
@@ -91,33 +106,57 @@ export async function findScanSession(
export async function readScanLogs(options: ScanLogOptions) {
const logs = new Map<string, SessionLog>();
- for await (const session of scanSessions(options.codexHome)) {
- logs.set(session.threadId, session);
+ const homes = new Set(
+ typeof options.codexHome === "string"
+ ? [options.codexHome]
+ : options.codexHome,
+ );
+ for (const directory of ["sessions", "archived_sessions"]) {
+ for (const home of homes) {
+ for await (const session of scanSessions(home, directory)) {
+ if (!logs.has(session.threadId)) logs.set(session.threadId, session);
+ }
+ }
}
- const root = logs.get(options.threadId);
- if (root === undefined) {
+ const root = options.threadId ? logs.get(options.threadId) : undefined;
+ if (root === undefined && !options.allowMissingRoot) {
throw new CodexSecurityError(
`No saved session logs are available for scan ${options.scanId}.`,
);
}
- const sessions = [root];
- const included = new Set([root.threadId]);
- for (const parent of sessions) {
+ const included = new Set([
+ ...(options.threadId ? [options.threadId] : []),
+ ...(options.threadIds ?? []),
+ ...(options.executionThreadIds ?? []),
+ ]);
+ // A Desktop owner can contain other work. Include its log without treating
+ // the whole conversation tree as part of this scan.
+ const traversed = new Set(options.executionThreadIds ?? included);
+ const pending = [...traversed];
+ for (const parentId of pending) {
+ const parent = logs.get(parentId);
for (const session of logs.values()) {
if (
- !included.has(session.threadId) &&
- (session.parentThreadId === parent.threadId ||
- (parent === root &&
+ !traversed.has(session.threadId) &&
+ (session.parentThreadId === parentId ||
+ (root !== undefined &&
+ parent === root &&
session.parentThreadId === null &&
belongsToScan(session, root, options)))
) {
included.add(session.threadId);
- sessions.push(session);
+ traversed.add(session.threadId);
+ pending.push(session.threadId);
}
}
}
+ const sessions: SessionLog[] = [];
+ for (const threadId of included) {
+ const session = logs.get(threadId);
+ if (session !== undefined) sessions.push(session);
+ }
const events: Record<string, unknown>[] = [];
for (const session of sessions) {
let replaying = false;
@@ -145,7 +184,7 @@ export async function readScanLogs(options: ScanLogOptions) {
return {
scanId: options.scanId,
- threadId: root.threadId,
+ threadId: options.threadId ?? null,
sessions: sessions.map(({ threadId, parentThreadId, path }) => ({
threadId,
parentThreadId,
@@ -214,6 +253,8 @@ async function* sessionEvents(
continue;
}
}
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
} finally {
lines.close();
stream.destroy();
diff --git a/sdk/typescript/tests-ts/cli-workbench.test.ts b/sdk/typescript/tests-ts/cli-workbench.test.ts
index 68bb13cef..5bb35fada 100644
--- a/sdk/typescript/tests-ts/cli-workbench.test.ts
+++ b/sdk/typescript/tests-ts/cli-workbench.test.ts
@@ -336,6 +336,8 @@ describe("CLI workbench", () => {
scan: {
scanId: "scan-1",
continuationThreadId: "thread-1",
+ threadIds: ["thread-1"],
+ executionThreadIds: ["thread-1"],
mode: "deep",
progress: {
status: "complete",
diff --git a/sdk/typescript/tests-ts/feedback.test.ts b/sdk/typescript/tests-ts/feedback.test.ts
index b3246b44b..333d66a2e 100644
--- a/sdk/typescript/tests-ts/feedback.test.ts
+++ b/sdk/typescript/tests-ts/feedback.test.ts
@@ -70,7 +70,12 @@ async function setup() {
options: {
reason: "Scan stopped",
includeLogs: true,
- scan: { scanId: "scan-1", continuationThreadId: "thread-1" },
+ scan: {
+ scanId: "scan-1",
+ continuationThreadId: "thread-1",
+ threadIds: ["thread-1"],
+ executionThreadIds: ["thread-1"],
+ },
environment,
workingDirectory: directory,
},
@@ -113,6 +118,115 @@ test("uploads selected scan and worker logs through Codex and removes temporary
context.expectClosed();
});
+for (const missingParent of [false, true]) {
+ test(`uploads only the selected Desktop scan logs with parent ${missingParent ? "missing" : "available"}`, async () => {
+ const context = await setup();
+ const archived = join(context.environment.CODEX_HOME, "archived_sessions");
+ await mkdir(archived, { recursive: true });
+ const sessions: [string, string, string | null][] = [
+ [archived, "sdk-worker", null],
+ [join(context.home, "sessions"), "worker-child", "sdk-worker"],
+ ];
+ if (!missingParent) sessions.unshift([archived, "desktop-owner", null]);
+ for (const [directory, id, parent] of sessions) {
+ await writeFile(
+ join(directory, `rollout-${id}.jsonl`),
+ JSON.stringify({
+ type: "session_meta",
+ payload: { id, parent_thread_id: parent },
+ }),
+ );
+ }
+ for (const payload of [
+ {
+ id: "unrelated-before",
+ timestamp: "2026-09-10T09:00:00Z",
+ source: {
+ subagent: { thread_spawn: { parent_thread_id: "desktop-owner" } },
+ },
+ },
+ {
+ id: "unrelated-after",
+ timestamp: "2026-09-10T13:00:00Z",
+ parent_thread_id: "desktop-owner",
+ },
+ {
+ id: "unrelated-fork",
+ timestamp: "2026-09-10T11:30:00Z",
+ forked_from_id: "desktop-owner",
+ },
+ {
+ id: "unrelated-grandchild",
+ timestamp: "2026-09-10T11:45:00Z",
+ parent_thread_id: "unrelated-fork",
+ },
+ ]) {
+ await writeFile(
+ join(archived, `rollout-${payload.id}.jsonl`),
+ JSON.stringify({
+ type: "session_meta",
+ payload: { ...payload, cwd: join(context.directory, "other-repo") },
+ }),
+ );
+ }
+ await sendFeedback(
+ {
+ ...context.options,
+ scan: {
+ scanId: "desktop-scan",
+ mode: "deep",
+ scanDir: join(context.directory, "scan"),
+ progress: { status: "complete", updatedAt: "2026-09-10T12:00:00Z" },
+ threadIds: ["desktop-owner", "sdk-worker"],
+ executionThreadIds: ["sdk-worker"],
+ },
+ },
+ context.startCodex,
+ );
+ const { requests, attachments } = await context.transcript();
+ expect(requests[2].params.tags.codex_security_scan_id).toBe("desktop-scan");
+ expect(attachments).toHaveLength(1);
+ expect(
+ JSON.parse(attachments[0].content).sessions.map(
+ (session: { threadId: string }) => session.threadId,
+ ),
+ ).toEqual([
+ ...(!missingParent ? ["desktop-owner"] : []),
+ "sdk-worker",
+ "worker-child",
+ ]);
+ expect(existsSync(attachments[0].path)).toBe(false);
+ context.expectClosed();
+ });
+}
+
+for (const recordedExecutionRoots of [false, true]) {
+ test(`does not infer standard scan workers from a Desktop continuation (${recordedExecutionRoots})`, async () => {
+ const context = await setup();
+ await sendFeedback(
+ {
+ ...context.options,
+ scan: {
+ scanId: "desktop-standard",
+ mode: "standard",
+ continuationThreadId: "thread-1",
+ threadIds: ["thread-1"],
+ ...(recordedExecutionRoots ? { executionThreadIds: [] } : {}),
+ },
+ },
+ context.startCodex,
+ );
+ const { requests, attachments } = await context.transcript();
+ expect(requests[2].params.threadId).toBeUndefined();
+ expect(
+ JSON.parse(attachments[0].content).sessions.map(
+ (session: { threadId: string }) => session.threadId,
+ ),
+ ).toEqual(["thread-1"]);
+ context.expectClosed();
+ });
+}
+
test("without log opt-in, does not read or attach saved sessions", async () => {
const context = await setup();
await rm(join(context.home, "sessions"), { recursive: true });
@@ -162,14 +276,19 @@ test("respects disabled feedback without starting Codex", async () => {
).rejects.toThrow("disabled by configuration");
});
-test("reports missing session logs without sending an incomplete log report", async () => {
+test("sends feedback when saved session logs are unavailable", async () => {
const context = await setup();
await rm(join(context.home, "sessions"), { recursive: true });
- await expect(
- sendFeedback(context.options, () => {
- throw new Error("Must not start Codex");
- }),
- ).rejects.toThrow("No saved session logs");
+ expect(await sendFeedback(context.options, context.startCodex)).toEqual({
+ feedbackId: "feedback-1",
+ scanId: "scan-1",
+ includedLogs: true,
+ });
+ const { requests, attachments } = await context.transcript();
+ expect(requests[2].params.includeLogs).toBe(true);
+ expect(requests[2].params.extraLogFiles).toEqual([]);
+ expect(attachments).toEqual([]);
+ context.expectClosed();
});
test("reports failure to start Codex", async () => {
diff --git a/sdk/typescript/tests-ts/scan-logs.test.ts b/sdk/typescript/tests-ts/scan-logs.test.ts
index be57c441e..059e0e42f 100644
--- a/sdk/typescript/tests-ts/scan-logs.test.ts
+++ b/sdk/typescript/tests-ts/scan-logs.test.ts
@@ -3,13 +3,15 @@ import {
mkdtemp,
readFile,
realpath,
+ rename,
rm,
writeFile,
} from "node:fs/promises";
+import { unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, spyOn, test } from "bun:test";
-import { readScanLogs } from "../src/scan-logs.js";
+import { readSavedScanLogs, readScanLogs } from "../src/scan-logs.js";
const directories: string[] = [];
@@ -80,6 +82,160 @@ function commandEvent(command: string, id: string, timestamp?: string) {
}
describe("saved scan logs", () => {
+ test("collects known desktop and CLI threads across active and archived homes without duplicates", async () => {
+ const desktop = await temporaryHome();
+ const cli = await temporaryHome();
+ await writeSession(desktop, "desktop-owner", [
+ commandEvent("desktop scan", "owner-call"),
+ ]);
+ await writeSession(desktop, "worker", [
+ commandEvent("stale archived copy", "stale-call"),
+ ]);
+ await writeSession(
+ desktop,
+ "worker-child",
+ [commandEvent("archived child", "child-call")],
+ "worker",
+ );
+ await writeSession(desktop, "unrelated", [
+ commandEvent("unrelated archived scan", "unrelated-call"),
+ ]);
+ await rename(join(desktop, "sessions"), join(desktop, "archived_sessions"));
+ await writeSession(cli, "worker", [
+ commandEvent("active worker", "worker-call"),
+ ]);
+ await writeSession(cli, "owner-child", [], "desktop-owner");
+ await writeSession(cli, "other-scan", [
+ commandEvent("unrelated CLI scan", "other-call"),
+ ]);
+
+ const result = await readSavedScanLogs(
+ {
+ scanId: "scan-1",
+ threadIds: ["desktop-owner", "worker", "worker"],
+ executionThreadIds: ["worker"],
+ },
+ [desktop, cli, desktop],
+ { allowMissingRoot: true },
+ );
+
+ expect(result.threadId).toBe("desktop-owner");
+ expect(result.sessions.map(({ threadId }) => threadId).sort()).toEqual([
+ "desktop-owner",
+ "worker",
+ "worker-child",
+ ]);
+ expect(
+ result.events.filter(({ threadId }) => threadId === "worker"),
+ ).toHaveLength(2);
+ expect(JSON.stringify(result)).toContain("desktop scan");
+ expect(JSON.stringify(result)).toContain("active worker");
+ expect(JSON.stringify(result)).toContain("archived child");
+ expect(JSON.stringify(result)).not.toContain("stale archived copy");
+ expect(JSON.stringify(result)).not.toContain("unrelated");
+ });
+
+ test.each([undefined, "missing-owner"])(
+ "feedback collects known worker descendants without the owner log with continuation %s",
+ async (continuationThreadId) => {
+ const home = await temporaryHome();
+ await writeSession(home, "owner-child", [], "missing-owner");
+ await writeSession(home, "worker", [
+ commandEvent("independent worker", "worker-call"),
+ ]);
+ await writeSession(home, "worker-child", [], "worker");
+ await writeSession(home, "unrelated-child", [], "another-owner");
+ const scan = {
+ scanId: "scan-1",
+ ...(continuationThreadId === undefined ? {} : { continuationThreadId }),
+ threadIds: ["missing-owner", "worker"],
+ executionThreadIds: ["worker"],
+ };
+
+ const result = await readSavedScanLogs(scan, home, {
+ allowMissingRoot: true,
+ });
+ expect(result.threadId).toBe("missing-owner");
+ expect(result.sessions.map(({ threadId }) => threadId).sort()).toEqual([
+ "worker",
+ "worker-child",
+ ]);
+ if (continuationThreadId === undefined) {
+ expect(() => readSavedScanLogs(scan, home)).toThrow(
+ "No session is associated with scan scan-1.",
+ );
+ } else {
+ await expect(readSavedScanLogs(scan, home)).rejects.toThrow(
+ "No saved session logs are available for scan scan-1.",
+ );
+ }
+ },
+ );
+
+ test("feedback returns an empty log set when no scan threads are recorded", async () => {
+ const home = await temporaryHome();
+ await writeSession(home, "unrelated", []);
+ expect(
+ await readSavedScanLogs({ scanId: "scan-1" }, home, {
+ allowMissingRoot: true,
+ }),
+ ).toEqual({
+ scanId: "scan-1",
+ threadId: null,
+ sessions: [],
+ events: [],
+ });
+ });
+
+ test("keeps worker events when the parent rollout disappears after discovery", async () => {
+ const home = await temporaryHome();
+ await writeSession(home, "parent", []);
+ await writeSession(
+ home,
+ "worker",
+ [commandEvent("available worker", "worker-call")],
+ "parent",
+ );
+ const parentPath = join(
+ home,
+ "sessions",
+ "2026",
+ "08",
+ "11",
+ "rollout-parent.jsonl",
+ );
+ const originalParse = JSON.parse;
+ let removed = false;
+ const parseSpy = spyOn(JSON, "parse").mockImplementation(
+ (text, reviver) => {
+ const parsed = originalParse(text, reviver);
+ if (!removed && parsed?.payload?.id === "parent") {
+ unlinkSync(parentPath);
+ removed = true;
+ }
+ return parsed;
+ },
+ );
+ try {
+ const result = await readSavedScanLogs(
+ {
+ scanId: "scan-1",
+ continuationThreadId: "parent",
+ executionThreadIds: ["parent"],
+ },
+ home,
+ { allowMissingRoot: true },
+ );
+ expect(removed).toBe(true);
+ expect(result.events.map(({ threadId }) => threadId)).toEqual([
+ "worker",
+ "worker",
+ ]);
+ } finally {
+ parseSpy.mockRestore();
+ }
+ });
+
test("returns complete parent and worker events without unrelated sessions", async () => {
const home = await temporaryHome();
await writeSession(home, "parent", [