fix(progress): reconcile live and saved parent updates (#1596)

Reconcile live and saved parent command completions so scan progress stays in source order after reconnects. Preserve validation progress and recover missing counts from the parent inventory.
This commit is contained in:
Michael D'Angelo
2026-11-02 18:14:17 -08:00
committed by GitHub
parent 223dea6390
commit 5befcdfdd7
7 changed files with 16469 additions and 113 deletions
+80 -34
View File
@@ -100,6 +100,7 @@ import {
estimateScanCost,
ScanCostTracker,
type ScanCost,
type ParentProgressSource,
type ScanSessionEvent,
type ScanUsageObservation,
type ScanWorkerEvent,
@@ -1979,7 +1980,9 @@ export class CodexSecurity {
let scanProgressTracker: ScanProgressTracker | null = null;
let savedProviderProfile: ProviderProfile | undefined;
let artifactRestorationFailure: OutputDirectoryError | null = null;
let customValidationComplete = false;
const customValidation = {
status: "pending" as "pending" | "running" | "complete",
};
let completionCost: ScanCost | null = null;
let scanTurnStatus: "in_progress" | "completed" | "failed" | null = null;
let budgetRecovery: {
@@ -2317,31 +2320,63 @@ export class CodexSecurity {
let reviewedFileCount = 0;
let latestPhase: ScanProgress["phase"] = "preflight";
let reviewItems: ScanProgress["reviewItems"];
const reportProgress = (progress: ScanProgress): void => {
let lastProgress: string | null = null;
const progressKey = (progress: ScanProgress): string =>
`${progress.phase}:${progress.filesCompleted}:${progress.filesTotal}:${progress.reviewItems?.completed}:${progress.reviewItems?.total}`;
const reportProgress = (
progress: ScanProgress,
source?: ParentProgressSource,
): void => {
const liveEvent =
source?.reconciled === true ? undefined : source?.event;
if (
scopeFileCount === null ||
progress.filesTotal > scopeFileCount ||
progress.filesCompleted < reviewedFileCount
liveEvent !== undefined &&
!tracker.recordParentProgress(progress, liveEvent)
)
return;
const inventory =
source?.inventory === true ||
(progress.phase === "discovery" &&
reviewedFileCount === 0 &&
progress.filesCompleted === 0);
const filesTotal = inventory ? progress.filesTotal : scopeFileCount;
if (
filesTotal === null ||
progress.filesTotal > filesTotal ||
(source?.inventory !== true &&
progress.filesCompleted < reviewedFileCount)
) {
if (liveEvent !== undefined) tracker.deferParentInventory(liveEvent);
return;
}
if (inventory) {
scopeFileCount = filesTotal;
tracker.setExpectedFilesTotal(filesTotal);
}
reviewedFileCount = progress.filesCompleted;
if (liveEvent !== undefined)
tracker.acceptParentProgress(progress, liveEvent);
if (
source !== undefined ||
mode === "deep" ||
scanPhaseSchema.options.indexOf(progress.phase) >
scanPhaseSchema.options.indexOf(latestPhase)
) {
latestPhase = progress.phase;
}
notifyObserver(
options,
"onProgress",
)({
const update = {
...progress,
phase: latestPhase,
filesTotal: scopeFileCount,
phase:
customValidation.status === "running"
? ("validation" as const)
: latestPhase,
filesTotal,
...(reviewItems === undefined ? {} : { reviewItems }),
});
};
const key = progressKey(update);
if (lastProgress === key) return;
lastProgress = key;
notifyObserver(options, "onProgress")(update);
};
const reportWorkerStatus = (status: ScanWorkerStatus): void => {
if (mode !== "deep") {
@@ -2408,12 +2443,20 @@ export class CodexSecurity {
onProgress:
options.onProgress === undefined
? undefined
: (progress) =>
reportProgress({
...progress,
// Worker counts belong to the parent scan's current phase.
phase: mode === "deep" ? progress.phase : latestPhase,
}),
: (progress, source) =>
reportProgress(
{
...progress,
// Only worker counts use the last accepted parent phase.
phase:
mode === "deep" ||
(source !== undefined &&
(source.reconciled !== true || !source.worker))
? progress.phase
: latestPhase,
},
source,
),
onCost:
options.onCost === undefined && options.maxCostUsd === undefined
? undefined
@@ -3038,6 +3081,7 @@ export class CodexSecurity {
),
)}`;
}
tracker.beginParentTurn(resumeThreadId !== undefined);
const events = directDeepScan
? (this.#dependencies.runDeepScan ?? runDeepScan)({
codexOptions,
@@ -3125,6 +3169,7 @@ export class CodexSecurity {
// This turn follows the primary scan's reporting phase.
scanProgressTracker?.stop();
latestPhase = "validation";
customValidation.status = "running";
if (scopeFileCount !== null)
reportProgress({
phase: "validation",
@@ -3164,7 +3209,7 @@ export class CodexSecurity {
return turn.finalResponse;
},
});
customValidationComplete = true;
customValidation.status = "complete";
}
budgetAbortController.abort();
const snapshot = await tracker.stop(usage).catch((error: unknown) => {
@@ -3221,18 +3266,11 @@ export class CodexSecurity {
onTrustedAccessStatus: options.onTrustedAccessStatus,
onReconnect: options.onReconnect,
onActivity: options.onActivity,
onProgress: (progress) => {
if (
progress.phase === "discovery" &&
progress.filesCompleted === 0 &&
reviewedFileCount === 0 &&
progress.filesTotal !== scopeFileCount
) {
scopeFileCount = progress.filesTotal;
tracker.setExpectedFilesTotal(scopeFileCount);
}
reportProgress(progress);
},
onProgressItem:
options.onProgress === undefined
? undefined
: (event) => tracker.recordParentItem(event),
onProgress: reportProgress,
onWorkerStatus: reportWorkerStatus,
onWarning: options.onWarning,
onObserverError: options.onObserverError,
@@ -3599,7 +3637,7 @@ export class CodexSecurity {
if (activeScan !== null && options.resumeScanId === undefined) {
if (
options.validationPrompt !== undefined &&
!customValidationComplete
customValidation.status !== "complete"
) {
await writeCustomValidationStatus(scanDir, {
scanId: activeScan.id,
@@ -5068,7 +5106,8 @@ interface ScanEventRunOptions extends Pick<ScanOptions, "onReconnect"> {
onScanStarted?: () => void;
onTrustedAccessStatus?: (status: ScanTrustedAccessStatus) => void;
onActivity?: (activity: ScanActivity) => void;
onProgress?: (progress: ScanProgress) => void;
onProgressItem?: (event: Readonly<Record<string, unknown>>) => void;
onProgress?: (progress: ScanProgress, source: ParentProgressSource) => void;
onWorkerStatus?: (status: ScanWorkerStatus) => void;
onWarning?: (warning: string) => void;
onObserverError?: (observer: ScanObserverName, error: unknown) => void;
@@ -5112,8 +5151,15 @@ export async function runScanEvents(
)) {
notifyObserver(options, "onActivity")(activity);
}
options.onProgressItem?.(event);
for (const progress of scanProgressUpdatesFromEvent(event)) {
notifyObserver(options, "onProgress")(progress);
notifyObserver(
{
onProgress: (update) => options.onProgress?.(update, { event }),
onObserverError: options.onObserverError,
},
"onProgress",
)(progress);
}
const workerStatus = workerStatusFromEvent(event);
if (workerStatus !== null) {
+2741 -43
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -3,6 +3,7 @@ import { resolveCodexProfile } from "../src/config.js";
import { randomUUID } from "node:crypto";
import { mkdirSync, renameSync, writeFileSync } from "node:fs";
import {
appendFile,
chmod,
cp,
mkdir,
@@ -16,6 +17,8 @@ import { join, resolve } from "node:path";
import type { ScanReadFile } from "../../../plugins/codex-security/native/scan-read-binding.mjs";
import type { ThreadEvent } from "@openai/codex-sdk";
import type { ScanActivity } from "../src/scan-activity.js";
import type { ScanSessionEvent } from "../src/cost.js";
import { progressMarker, writeSession } from "./support/usage-rollout.js";
import Ajv2020 from "ajv/dist/2020.js";
import { afterEach, describe, expect, mock, spyOn, test } from "bun:test";
import {
@@ -722,6 +725,9 @@ describe("custom validation", () => {
"empty",
"incomplete",
"dismissed",
"late-progress",
"live-progress",
"late-progress-observer-error",
"unfinished-source",
];
test.each(completionScenarios)(
@@ -772,6 +778,33 @@ describe("custom validation", () => {
const workingDirectories: Array<string | undefined> = [];
const commands: string[] = [];
const activities: ScanActivity[] = [];
const progressScenario =
scenario !== "progress" && scenario.includes("progress");
const progressUpdates: Array<
ScanProgress & { validationStarted: boolean }
> = [];
const observerErrors: string[] = [];
let validationStarted = false;
let parentRollout = "";
const parentSeen = Promise.withResolvers<void>();
const parentMessage = (
id: string,
phase: ScanProgress["phase"],
filesCompleted: number,
) => ({
type: "response_item",
payload: {
type: "message",
id,
role: "assistant",
content: [
{
type: "output_text",
text: progressMarker(phase, filesCompleted, 1),
},
],
},
});
const progress: ScanProgress[] = [];
const validationActivity = "Synthetic validation activity.";
const profileDisabledTools =
@@ -889,6 +922,39 @@ describe("custom validation", () => {
);
expect(commands).not.toContain("prepare-scan-completion");
expect(commands).not.toContain("complete-scan");
if (progressScenario) {
parentRollout = await writeSession(
codexHome,
"thread-1",
{ input_tokens: 10, output_tokens: 3 },
);
const messages = [
parentMessage("inventory", "discovery", 0),
parentMessage("review", "discovery", 1),
];
if (scenario === "live-progress")
messages.push(
parentMessage("parent-final", "reporting", 1),
);
await appendFile(
parentRollout,
jsonLines(messages) + "\n",
);
async function* progressEvents(): AsyncGenerator<ThreadEvent> {
for (const message of messages)
yield {
type: "item.completed",
item: {
id: message.payload.id,
type: "agent_message",
text: message.payload.content[0]!.text,
},
};
}
return {
events: completedEvents("thread-1", progressEvents()),
};
}
if (scenario === "progress") {
return {
events:
@@ -999,6 +1065,26 @@ describe("custom validation", () => {
);
}
}
if (progressScenario) {
validationStarted = true;
if (scenario !== "live-progress") {
await appendFile(
parentRollout,
JSON.stringify(
parentMessage("parent-final", "reporting", 1),
) + "\n",
);
// The observer fires during the same synchronous batch that
// processes progress, so this awaits the actual saved receipt.
await parentSeen.promise;
}
expect(progressUpdates.at(-1)?.phase).toBe("validation");
expect(
progressUpdates
.filter((update) => update.validationStarted)
.every((update) => update.phase === "validation"),
).toBe(true);
}
return {
events: responseEvents(
output,
@@ -1023,6 +1109,10 @@ describe("custom validation", () => {
},
},
);
// Keep the synthetic validation turn alive while it awaits an unref'ed poll.
const keepAlive = progressScenario
? setInterval(() => {}, 1_000)
: undefined;
try {
const pending = client.run(repository, {
cyberAccessProgram: "daybreak_blue",
@@ -1031,6 +1121,27 @@ describe("custom validation", () => {
? { validationPromptFile: workflowFile }
: { validationPrompt: workflow }),
onActivity: (activity) => activities.push(activity),
...(progressScenario
? {
onProgress: (progress: ScanProgress) => {
progressUpdates.push({ ...progress, validationStarted });
if (
scenario === "late-progress-observer-error" &&
progress.phase === "validation"
)
throw new Error("Synthetic optional progress failure.");
},
onSessionEvent: ({ event }: ScanSessionEvent) => {
if (
(event["payload"] as { id?: string } | undefined)?.id ===
"parent-final"
)
parentSeen.resolve();
},
onObserverError: (observer: string) =>
observerErrors.push(observer),
}
: {}),
...(scenario === "progress"
? { onProgress: (update: ScanProgress) => progress.push(update) }
: {}),
@@ -1081,6 +1192,18 @@ describe("custom validation", () => {
return;
}
const completed = await pending;
if (progressScenario) {
expect(observerErrors).toEqual(
scenario === "late-progress-observer-error" ? ["onProgress"] : [],
);
if (scenario === "live-progress")
expect(
progressUpdates.some(
(update) =>
update.phase === "reporting" && !update.validationStarted,
),
).toBe(true);
}
if (scenario === "standard") {
const report = await readFile(join(scanDir, "report.md"), "utf8");
expect(report).toContain(
@@ -1128,6 +1251,7 @@ describe("custom validation", () => {
count === 0 || scenario === "dismissed" ? "No findings" : "Fixture 0",
);
} finally {
clearInterval(keepAlive);
await client.close();
}
},
@@ -1158,15 +1158,17 @@ describe("security policy preview", () => {
const f = await fixture();
const draft = await f.generate();
const source = new URL("../src/security-policy.ts", import.meta.url);
const built = await Bun.build({
entrypoints: [fileURLToPath(source)],
target: "node",
format: "esm",
define: { "import.meta.url": JSON.stringify(source.href) },
});
expect(built.success).toBe(true);
const module = join(f.root, "policy.mjs");
await writeFile(module, await built.outputs[0]!.text());
// Repeated in-process Bun builds can misread dependency files on macOS.
execFileSync(process.execPath, [
"build",
fileURLToPath(source),
"--target=node",
"--format=esm",
"--define",
`import.meta.url=${JSON.stringify(source.href)}`,
`--outfile=${module}`,
]);
const missingPython = join(f.root, "missing-python");
const result = JSON.parse(
execFileSync(
@@ -1,6 +1,7 @@
import { mkdir, writeFile } from "node:fs/promises";
import { runNodePython } from "./python-probe.js";
import { join } from "node:path";
import type { ThreadEvent } from "@openai/codex-sdk";
import assert from "node:assert/strict";
export const scanThreadId = "scan-thread";
@@ -25,6 +26,51 @@ export const ownedPythonUsage = {
totalTokens: 110,
};
export function progressMarker(
phase: string,
filesCompleted: number,
filesTotal: number,
): string {
return `CODEX_SECURITY_SCAN_PROGRESS ${JSON.stringify({ phase, filesCompleted, filesTotal })}`;
}
export function nativeCommand(
command: string | readonly string[],
output: string,
id?: string,
) {
return {
type: "event_msg",
payload: {
type: "item_completed",
item: {
type: "CommandExecution",
...(id === undefined ? {} : { id }),
command: typeof command === "string" ? [command] : command,
aggregated_output: output,
},
},
};
}
export function completedCommand(
command: string,
output: string,
id = command,
): ThreadEvent {
return {
type: "item.completed",
item: {
type: "command_execution",
id,
command,
aggregated_output: output,
status: "completed",
exit_code: 0,
},
};
}
function uuid7TaskStarted(turnId: string): Record<string, unknown> {
return {
type: "event_msg",