mirror of
https://github.com/openai/codex-security.git
synced 2026-11-26 10:35:38 +08:00
fix(scans): retain the reported phase when a Standard scan stops
This commit is contained in:
@@ -23,6 +23,7 @@
|
||||
"hostedScopeInventory": 1,
|
||||
"scopedInventoryReceipt": 1,
|
||||
"standardScanHandoff": 1,
|
||||
"stoppedScanPhaseObservation": 1,
|
||||
"workerProviderSnapshot": 4
|
||||
},
|
||||
"interface": {
|
||||
|
||||
@@ -14,10 +14,10 @@ export interface Migration {
|
||||
statements: readonly string[];
|
||||
}
|
||||
|
||||
// Python owns the repository-dependent migrations 67–71. Migration 72 only uses
|
||||
// the external source tables that both workbench runtimes already maintain.
|
||||
// Python owns the repository-dependent migrations 67–71. Migrations 72 and 74
|
||||
// only use tables that both workbench runtimes already maintain.
|
||||
export const migrations: readonly Migration[] = history.filter(
|
||||
(item) => item.version <= 66 || item.version === 72,
|
||||
(item) => item.version <= 66 || item.version === 72 || item.version === 74,
|
||||
);
|
||||
const migration = (version: number) =>
|
||||
migrations.find((item) => item.version === version)!;
|
||||
|
||||
@@ -79,7 +79,7 @@ function assertMigrationNames(database: DatabaseSync, ...versions: number[]) {
|
||||
database
|
||||
.prepare("SELECT name FROM schema_migrations WHERE version = ?")
|
||||
.get(version)?.name,
|
||||
workbenchMigrations[version - 1].name,
|
||||
workbenchMigrations.find((item) => item.version === version)!.name,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -352,6 +352,9 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
|
||||
fail_scan.add_argument("--model-thread-id")
|
||||
fail_scan.add_argument("--claim-token")
|
||||
fail_scan.add_argument("--cost-json")
|
||||
for stop in (fail_scan, cancel_scan):
|
||||
stop.add_argument("--observed-phase", choices=PHASES)
|
||||
stop.add_argument("--phase-observed-at")
|
||||
|
||||
preserve_scan = add_command("preserve-scan-results", "--scan-id")
|
||||
preserve_scan.add_argument("--thread-id")
|
||||
|
||||
@@ -90,6 +90,11 @@ def scan_progress_result(
|
||||
"worklistRows": scan["review_items_total"],
|
||||
},
|
||||
"phase": scan["phase"],
|
||||
**(
|
||||
{"lastObservedPhase": json.loads(scan["last_observed_phase_json"])}
|
||||
if scan["last_observed_phase_json"] is not None
|
||||
else {}
|
||||
),
|
||||
"phaseProgress": {
|
||||
"completed": scan["phase_items_completed"],
|
||||
"total": scan["phase_items_total"],
|
||||
|
||||
@@ -75,6 +75,7 @@ from workbench_constants import PHASES
|
||||
from workbench_coverage_receipts import (
|
||||
_generic_surface_updates as _generic_surface_updates,
|
||||
)
|
||||
from workbench_scan_usage import _timestamp as parse_observation_time
|
||||
|
||||
_PUBLICATION_FOLLOW_UP_WARNING = (
|
||||
"Saved scan evidence remains on disk; result publication needs follow-up:"
|
||||
@@ -1252,16 +1253,25 @@ def mark_running_scan_failed(
|
||||
return updated.rowcount == 1
|
||||
|
||||
|
||||
def stopped_phase_observation(scan: sqlite3.Row, args: argparse.Namespace) -> str | None:
|
||||
phase = getattr(args, "observed_phase", None)
|
||||
observed_at = getattr(args, "phase_observed_at", None)
|
||||
if scan["mode"] == "standard" and phase and parse_observation_time(observed_at) is not None:
|
||||
return json.dumps({"phase": phase, "observedAt": observed_at})
|
||||
return None
|
||||
|
||||
|
||||
def touch_scan_progress(
|
||||
connection: sqlite3.Connection,
|
||||
scan_id: str,
|
||||
timestamp: str,
|
||||
scope_file_count: int | None = None,
|
||||
last_observed_phase: str | None = None,
|
||||
) -> bool:
|
||||
updated = connection.execute(
|
||||
"UPDATE scan_progress SET updated_at = ?, scope_file_count = COALESCE(?, scope_file_count) "
|
||||
"WHERE scan_id = ?",
|
||||
(timestamp, scope_file_count, scan_id),
|
||||
"UPDATE scan_progress SET updated_at = ?, scope_file_count = COALESCE(?, scope_file_count), "
|
||||
"last_observed_phase_json = ? WHERE scan_id = ?",
|
||||
(timestamp, scope_file_count, last_observed_phase, scan_id),
|
||||
)
|
||||
return updated.rowcount == 1
|
||||
|
||||
@@ -1313,6 +1323,7 @@ def fail_scan_locked(db: Any, connection: Any, args: Any) -> dict[str, Any]:
|
||||
scan_id,
|
||||
timestamp,
|
||||
scope_file_count if scan["scan_dir"] == observed["scan_dir"] else None,
|
||||
stopped_phase_observation(scan, args),
|
||||
):
|
||||
raise SystemExit("Codex Security scan progress not found.")
|
||||
record_stopped_scan_usage(db, connection, scan_id, cost_json)
|
||||
@@ -1377,6 +1388,7 @@ def cancel_scan_locked(db: Any, connection: Any, args: Any) -> dict[str, Any]:
|
||||
scan_id,
|
||||
timestamp,
|
||||
scope_file_count if scan["scan_dir"] == observed["scan_dir"] else None,
|
||||
stopped_phase_observation(scan, args),
|
||||
):
|
||||
raise SystemExit("Codex Security scan progress not found.")
|
||||
record_stopped_scan_usage(db, connection, scan_id, cost_json)
|
||||
|
||||
@@ -372,6 +372,7 @@ SCAN_SUMMARY_COLUMNS = """
|
||||
progress.scope_file_count,
|
||||
progress.review_items_completed,
|
||||
progress.review_items_total,
|
||||
progress.last_observed_phase_json,
|
||||
progress.updated_at AS progress_updated_at,
|
||||
(
|
||||
SELECT COUNT(*)
|
||||
@@ -395,7 +396,7 @@ def scan_with_progress(connection: sqlite3.Connection, scan_id: str) -> sqlite3.
|
||||
progress.review_items_total, progress.review_items_completed, progress.deep_review_pass,
|
||||
progress.phase_items_total, progress.phase_items_completed, progress.phase_progress_unit,
|
||||
progress.preflight_checks_total, progress.preflight_checks_completed,
|
||||
progress.preflight_issues_json
|
||||
progress.preflight_issues_json, progress.last_observed_phase_json
|
||||
FROM scans
|
||||
JOIN scan_progress AS progress ON progress.scan_id = scans.id
|
||||
JOIN scan_lifecycles AS lifecycle ON lifecycle.scan_id = scans.id
|
||||
@@ -426,6 +427,11 @@ def scan_summary(row: sqlite3.Row) -> dict[str, Any]:
|
||||
"worklistRows": row["review_items_total"],
|
||||
},
|
||||
"phase": row["phase"],
|
||||
**(
|
||||
{"lastObservedPhase": json.loads(row["last_observed_phase_json"])}
|
||||
if row["last_observed_phase_json"] is not None
|
||||
else {}
|
||||
),
|
||||
"status": "canceled" if row["canceled_at"] else row["status"],
|
||||
"updatedAt": row["progress_updated_at"],
|
||||
},
|
||||
|
||||
@@ -588,5 +588,12 @@
|
||||
"CREATE INDEX external_finding_members_by_version\nON external_finding_import_members (finding_id, version);",
|
||||
"CREATE TABLE external_finding_publications (\n finding_id TEXT NOT NULL REFERENCES external_source_reports(id),\n version INTEGER NOT NULL,\n cloud_api_url TEXT NOT NULL,\n account_id TEXT NOT NULL,\n destination_id TEXT NOT NULL,\n receipt_id TEXT NOT NULL,\n outcome TEXT NOT NULL,\n cloud_finding_id TEXT,\n created_at TEXT NOT NULL,\n PRIMARY KEY (finding_id, version, cloud_api_url, account_id, destination_id, receipt_id)\n) WITHOUT ROWID;"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": 74,
|
||||
"name": "retain the last observed phase of stopped Standard scans",
|
||||
"statements": [
|
||||
"ALTER TABLE scan_progress ADD COLUMN last_observed_phase_json TEXT;"
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
@@ -13,10 +13,12 @@ from workbench_test_support import (
|
||||
cancel_scan,
|
||||
create_saved_workspace,
|
||||
empty_target_paths,
|
||||
empty_target_scan,
|
||||
fail_scan,
|
||||
get_scan,
|
||||
load_script,
|
||||
mark_handoff_delivered,
|
||||
run_workbench,
|
||||
scan_claim_command,
|
||||
scan_command,
|
||||
start_delivered_scan,
|
||||
@@ -121,6 +123,46 @@ def test_cancellation_identifies_committed_scan_when_workspace_has_replacement(
|
||||
assert response["results"]["progress"]["status"] == ("running" if app else "canceled")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stop", ["fail-scan", "cancel-scan"])
|
||||
def test_stop_retains_observation_separately_from_committed_progress(tmp_path: Path, stop: str):
|
||||
state_dir, _, scan_id, _ = empty_target_scan(tmp_path)
|
||||
before = get_scan(state_dir, scan_id)["scan"]["progress"]
|
||||
assert "lastObservedPhase" not in before
|
||||
extra = ["--message", "Fixture interruption"] if stop == "fail-scan" else []
|
||||
observed_at = before["updatedAt"]
|
||||
scan_command(
|
||||
state_dir,
|
||||
stop,
|
||||
scan_id,
|
||||
*extra,
|
||||
"--observed-phase",
|
||||
"discovery",
|
||||
"--phase-observed-at",
|
||||
observed_at,
|
||||
)
|
||||
scan_command(
|
||||
state_dir,
|
||||
stop,
|
||||
scan_id,
|
||||
*extra,
|
||||
"--observed-phase",
|
||||
"reporting",
|
||||
"--phase-observed-at",
|
||||
observed_at,
|
||||
)
|
||||
detail = get_scan(state_dir, scan_id)["scan"]
|
||||
summary = run_workbench(state_dir, "list-scans")["scans"][0]
|
||||
compact = get_scan(state_dir, scan_id, "--progress-only")["scan"]
|
||||
for entry in (detail, summary, compact):
|
||||
progress = entry["progress"]
|
||||
assert progress["lastObservedPhase"] == {"phase": "discovery", "observedAt": observed_at}
|
||||
assert progress["phase"] == before["phase"]
|
||||
assert progress["coverage"] == before["coverage"]
|
||||
assert progress["updatedAt"] == detail["lifecycle"]["finishedAt"]
|
||||
if stop == "fail-scan":
|
||||
assert detail["failureMessage"] == "Fixture interruption"
|
||||
|
||||
|
||||
def test_workbench_records_scan_failure(tmp_path: Path) -> None:
|
||||
state_dir, target = empty_target_paths(tmp_path)
|
||||
saved = create_saved_workspace(state_dir, target)
|
||||
|
||||
@@ -120,6 +120,7 @@ EXPECTED_MIGRATIONS = [
|
||||
(70, "retain checkout roots for Git discovery"),
|
||||
(71, "retain rejected workspace checkout boundaries"),
|
||||
(72, "retain external finding import selections and provenance"),
|
||||
(74, "retain the last observed phase of stopped Standard scans"),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -2213,8 +2213,14 @@ summaries include the same navigation when the current run was registered, plus
|
||||
the last observed phase when available. A failure before registration has no
|
||||
scan ID. The handoff uses that run's registration receipt without querying scan
|
||||
history. Inspect its saved status before choosing resume or rerun, and supply
|
||||
the original custom prompt files for reruns. Structured history and log output
|
||||
and command selection defaults are unchanged.
|
||||
the original custom prompt files for reruns.
|
||||
|
||||
For a failed or canceled local Standard scan using the default validation
|
||||
workflow, `scans show SCAN_ID` also shows the last phase the primary model
|
||||
reported directly, when available. In JSON,
|
||||
`progress.lastObservedPhase` contains the reported `phase` and the time the
|
||||
SDK received it (`observedAt`). The workbench checkpoint supplies
|
||||
`progress.phase` and the saved review counts.
|
||||
|
||||
Without an ID, rerun selects the latest completed scan in the current worktree.
|
||||
If only a related checkout has a completed scan, rerun shows its ID, path, and
|
||||
|
||||
@@ -722,6 +722,11 @@ export interface ScanPreflight extends DeepScanOptions, ScanModelConfiguration {
|
||||
deepScanSources?: DeepScanSources;
|
||||
}
|
||||
|
||||
interface ObservedScanPhase {
|
||||
phase: ScanProgress["phase"];
|
||||
observedAt: string;
|
||||
}
|
||||
|
||||
interface LocalScanInputs extends Omit<
|
||||
ScanPreflight,
|
||||
"model" | "reasoningEffort" | "authentication"
|
||||
@@ -2273,6 +2278,7 @@ export class CodexSecurity {
|
||||
let preparedTargetWarnings: string[] = [];
|
||||
let runPostScan: (() => ReturnType<CodexThreadLike["runStreamed"]>) | null =
|
||||
null;
|
||||
let observedPhase: ObservedScanPhase | undefined;
|
||||
let activeScan: {
|
||||
id: string;
|
||||
options: WorkbenchCommandOptions;
|
||||
@@ -2615,6 +2621,11 @@ export class CodexSecurity {
|
||||
? await pluginCapabilities(shellPluginRoot)
|
||||
: undefined;
|
||||
const standard = standardCapabilities?.["standardScanHandoff"] === 1;
|
||||
const trackStoppedPhase =
|
||||
standard &&
|
||||
!hosted &&
|
||||
options.validationPrompt === undefined &&
|
||||
standardCapabilities?.["stoppedScanPhaseObservation"] === 1;
|
||||
const discoveryPrompt =
|
||||
options.validationPrompt === undefined
|
||||
? undefined
|
||||
@@ -2701,8 +2712,24 @@ export class CodexSecurity {
|
||||
tracker.setExpectedFilesTotal(filesTotal);
|
||||
}
|
||||
reviewedFileCount = progress.filesCompleted;
|
||||
if (liveEvent !== undefined)
|
||||
if (liveEvent !== undefined) {
|
||||
tracker.acceptParentProgress(progress, liveEvent);
|
||||
// Command output may quote a progress marker from source. Only save
|
||||
// a phase that the coordinator itself reported during this turn.
|
||||
const item = liveEvent["item"];
|
||||
if (
|
||||
trackStoppedPhase &&
|
||||
isRecord(item) &&
|
||||
item["type"] === "agent_message"
|
||||
) {
|
||||
observedPhase = {
|
||||
phase: progress.phase,
|
||||
observedAt: new Date(
|
||||
(this.#dependencies.now ?? Date.now)(),
|
||||
).toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
if (
|
||||
source !== undefined ||
|
||||
mode === "deep" ||
|
||||
@@ -4351,6 +4378,7 @@ export class CodexSecurity {
|
||||
(failure instanceof ScanCostLimitExceededError
|
||||
? failure.cost
|
||||
: snapshot?.cost),
|
||||
observedPhase,
|
||||
);
|
||||
activeScan = null;
|
||||
} catch {}
|
||||
@@ -7056,9 +7084,18 @@ async function stopRegisteredScan(
|
||||
canceled: boolean,
|
||||
error: unknown,
|
||||
cost?: Readonly<ScanCost> | ReturnType<typeof measuredScanCost>,
|
||||
observedPhase?: ObservedScanPhase,
|
||||
): Promise<void> {
|
||||
const cleanupOptions = { ...activeScan.options, signal: undefined };
|
||||
const costArgs = cost ? ["--cost-json", JSON.stringify(cost)] : [];
|
||||
const phaseArgs = observedPhase
|
||||
? [
|
||||
"--observed-phase",
|
||||
observedPhase.phase,
|
||||
"--phase-observed-at",
|
||||
observedPhase.observedAt,
|
||||
]
|
||||
: [];
|
||||
if (canceled) {
|
||||
try {
|
||||
const stopped = await workbench(cleanupOptions, [
|
||||
@@ -7066,6 +7103,7 @@ async function stopRegisteredScan(
|
||||
"--scan-id",
|
||||
activeScan.id,
|
||||
...costArgs,
|
||||
...phaseArgs,
|
||||
]);
|
||||
// A workspace can already display a replacement when cancellation returns.
|
||||
const results = stopped["results"];
|
||||
@@ -7088,6 +7126,7 @@ async function stopRegisteredScan(
|
||||
activeScan.id,
|
||||
`--message=${errorMessage(error)}`,
|
||||
...costArgs,
|
||||
...phaseArgs,
|
||||
]);
|
||||
notifyScanLifecycle(options, failed["scan"], true);
|
||||
}
|
||||
|
||||
@@ -294,7 +294,8 @@ export function renderScanHistory(
|
||||
);
|
||||
}
|
||||
} else if (command === "show") {
|
||||
const status = clean((result["progress"] as JsonObject)["status"]);
|
||||
const progress = result["progress"] as JsonObject;
|
||||
const status = clean(progress["status"]);
|
||||
const statusColor =
|
||||
status === "complete" ? 32 : status === "running" ? 36 : 31;
|
||||
lines.push(
|
||||
@@ -373,8 +374,13 @@ export function renderScanHistory(
|
||||
.join(` ${accent("·")} `)}`,
|
||||
);
|
||||
}
|
||||
const coverage = (result["progress"] as JsonObject)["coverage"] as
|
||||
JsonObject | undefined;
|
||||
const observation = progress["lastObservedPhase"] as JsonObject | undefined;
|
||||
if (observation) {
|
||||
lines.push(
|
||||
` ${strong("LAST REPORTED PHASE")} ${clean(observation["phase"])} ${accent("·")} ${clean(observation["observedAt"])}`,
|
||||
);
|
||||
}
|
||||
const coverage = progress["coverage"] as JsonObject | undefined;
|
||||
if (coverage) {
|
||||
const parts = [
|
||||
...(coverage["worklistRows"] == null
|
||||
|
||||
@@ -4488,6 +4488,85 @@ if __name__ == "__main__":
|
||||
},
|
||||
);
|
||||
|
||||
test.each(["failure", "cancellation", "tool output only", "legacy plugin"])(
|
||||
"saves only an accepted coordinator phase at its observation time on stop (%s)",
|
||||
async (scenario) => {
|
||||
const { root, repository, codexHome, scanDir } = await scanDirectories();
|
||||
const pluginRoot = await copyCredentialTestPlugin(root);
|
||||
if (scenario === "legacy plugin") {
|
||||
const path = join(pluginRoot, ".codex-plugin", "plugin.json");
|
||||
const manifest = JSON.parse(await readFile(path, "utf8"));
|
||||
delete manifest.codexSecurity.stoppedScanPhaseObservation;
|
||||
await writeFile(path, JSON.stringify(manifest));
|
||||
}
|
||||
const controller = new AbortController();
|
||||
const observedAt = "2026-01-02T12:00:00.000Z";
|
||||
let now = Date.parse(observedAt);
|
||||
async function* events(): AsyncGenerator<ThreadEvent> {
|
||||
if (scenario !== "tool output only") {
|
||||
yield {
|
||||
type: "item.completed",
|
||||
item: {
|
||||
type: "agent_message",
|
||||
id: "phase",
|
||||
text: progressMarker("discovery", 1, 8),
|
||||
},
|
||||
};
|
||||
}
|
||||
now += 60_000;
|
||||
// A source read can quote a valid marker. A coordinator claim beyond
|
||||
// the registered inventory also fails the existing eligibility check.
|
||||
yield completedCommand(
|
||||
"cat example.txt",
|
||||
progressMarker("validation", 2, 8),
|
||||
);
|
||||
yield {
|
||||
type: "item.completed",
|
||||
item: {
|
||||
type: "agent_message",
|
||||
id: "too-large",
|
||||
text: progressMarker("reporting", 3, 9),
|
||||
},
|
||||
};
|
||||
if (scenario === "cancellation") controller.abort();
|
||||
throw new Error("Synthetic scan interruption");
|
||||
}
|
||||
let stopped: readonly string[] | undefined;
|
||||
await using client = TestClient.withDependencies({
|
||||
...scanRuntimeDependencies(codexHome, scanDir),
|
||||
now: () => now,
|
||||
prepareRuntime: async () => {
|
||||
const runtime = preparedRuntime(codexHome);
|
||||
runtime.plugin.pluginRoot = runtime.plugin.installedRoot = pluginRoot;
|
||||
return runtime;
|
||||
},
|
||||
createCodex: codexFactory(async () => ({ events: events() })),
|
||||
runWorkbench: async (options, args, input) => {
|
||||
if (args[0] === "fail-scan" || args[0] === "cancel-scan")
|
||||
stopped = args;
|
||||
return registerEightFileScan(options, args, input);
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
client.run(repository, { signal: controller.signal }),
|
||||
).rejects.toThrow();
|
||||
expect(stopped?.[0]).toBe(
|
||||
scenario === "cancellation" ? "cancel-scan" : "fail-scan",
|
||||
);
|
||||
if (scenario === "legacy plugin" || scenario === "tool output only") {
|
||||
expect(stopped).not.toContain("--observed-phase");
|
||||
expect(stopped).not.toContain("--phase-observed-at");
|
||||
} else {
|
||||
expect(stopped?.slice(-4)).toEqual([
|
||||
"--observed-phase",
|
||||
"discovery",
|
||||
"--phase-observed-at",
|
||||
observedAt,
|
||||
]);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("reports a Deep Scan terminal failure instead of a completion-state error", async () => {
|
||||
const { root, repository, codexHome, scanDir } = await scanDirectories();
|
||||
const commands: string[] = [];
|
||||
|
||||
@@ -34,6 +34,30 @@ describe("scan history renderer", () => {
|
||||
expect(historical).not.toContain("scoped paths:");
|
||||
});
|
||||
|
||||
test("shows the coordinator's reported phase and receipt time in stopped scan details", () => {
|
||||
const text = renderScanHistory(
|
||||
{
|
||||
scanId: "synthetic-scan",
|
||||
targetPath: "/synthetic/repository",
|
||||
mode: "standard",
|
||||
findings: [],
|
||||
progress: {
|
||||
status: "canceled",
|
||||
phase: "threat_model",
|
||||
lastObservedPhase: {
|
||||
phase: "discovery",
|
||||
observedAt: "2026-01-02T12:01:00Z",
|
||||
},
|
||||
},
|
||||
},
|
||||
"show",
|
||||
{ color: false },
|
||||
);
|
||||
expect(text).toMatch(
|
||||
/LAST REPORTED PHASE.*discovery.*2026-01-02T12:01:00Z/u,
|
||||
);
|
||||
});
|
||||
|
||||
test("counts singleton sides when the other side is grouped", () => {
|
||||
const text = renderScanHistory(
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user