mirror of
https://github.com/openai/codex-security.git
synced 2026-12-04 00:40:12 +08:00
Share candidate fixtures across draft, recovery and validation tests
This commit is contained in:
@@ -7,11 +7,15 @@ const load = (file: string) =>
|
||||
fileURLToPath(new URL(`../src/deep-scan/${file}.ts`, import.meta.url)),
|
||||
);
|
||||
|
||||
const { createDeepScanArtifacts } = await load("artifacts");
|
||||
export const { createDeepScanArtifacts } = await load("artifacts");
|
||||
const validation = await load("artifact-validation");
|
||||
const { mergeBatch } = await load("iteration");
|
||||
export const { scanUnionToDraft, persistedScanUnion, parseScanUnion } =
|
||||
validation;
|
||||
export const {
|
||||
validateDiscoveryArtifacts,
|
||||
scanUnionToDraft,
|
||||
persistedScanUnion,
|
||||
parseScanUnion,
|
||||
} = validation;
|
||||
|
||||
// Admit worker output and merge it through the coordinator's normal entry points.
|
||||
export async function mergeWorkerFiles(
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,4 @@
|
||||
import { readJson, readSavedReviewState } from "./support/json.ts";
|
||||
import { readJson, readSavedReviewState, writeJson } from "./support/json.ts";
|
||||
import { recordCodexSecurityScanDraft } from "./scan-draft-recovery-fixture.ts";
|
||||
import {
|
||||
discoveryPluginRoot,
|
||||
@@ -514,20 +514,17 @@ for (const disposition of ["rejected", "not_applicable"]) {
|
||||
);
|
||||
// Replay a file-authored legacy exclusion alongside the accepted modern checkpoint.
|
||||
const manifestPath = path.join(scan.scanDir, "scan-manifest.json");
|
||||
const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
|
||||
const manifest = await readJson(manifestPath);
|
||||
delete manifest.scan.reviewState;
|
||||
manifest.scan.coverageRef = "coverage.json";
|
||||
const coveragePath = path.join(scan.scanDir, manifest.scan.coverageRef);
|
||||
await writeFile(
|
||||
coveragePath,
|
||||
JSON.stringify({
|
||||
...publication.reviewState,
|
||||
schemaVersion: "1.0",
|
||||
scanId: scan.scanId,
|
||||
explicitExclusions: [exclusion],
|
||||
}),
|
||||
);
|
||||
await writeFile(manifestPath, JSON.stringify(manifest));
|
||||
await writeJson(coveragePath, {
|
||||
...publication.reviewState,
|
||||
schemaVersion: "1.0",
|
||||
scanId: scan.scanId,
|
||||
explicitExclusions: [exclusion],
|
||||
});
|
||||
await writeJson(manifestPath, manifest);
|
||||
const checkpoints = path.join(scan.scanDir, "checkpoints");
|
||||
const before = new Map(
|
||||
await Promise.all(
|
||||
@@ -573,9 +570,7 @@ for (const disposition of ["rejected", "not_applicable"]) {
|
||||
saved.progress.candidates.unresolved,
|
||||
kind === "valid" ? 0 : 1,
|
||||
);
|
||||
const { scan: sealed } = JSON.parse(
|
||||
await readFile(manifestPath, "utf8"),
|
||||
);
|
||||
const { scan: sealed } = await readJson(manifestPath);
|
||||
const retained = (sealed.review?.unresolvedCandidates ?? []).filter(
|
||||
(row: { candidateId?: string }) =>
|
||||
row.candidateId === candidate.candidate_id,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { readJson, writeJson } from "./support/json.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdir, readFile, readdir, utimes, writeFile } from "node:fs/promises";
|
||||
@@ -27,6 +28,19 @@ const { preserveDiffCandidateDecisions } = await importSource(
|
||||
fileURLToPath(new URL("../src/artifact-diff-candidates.ts", import.meta.url)),
|
||||
);
|
||||
|
||||
async function captureCheckpoints(directory: string) {
|
||||
const originals = await Promise.all(
|
||||
(await readdir(directory)).map(async (name) => {
|
||||
const file = path.join(directory, name);
|
||||
return [file, await readFile(file, "utf8")] as const;
|
||||
}),
|
||||
);
|
||||
return async () => {
|
||||
for (const [file, contents] of originals)
|
||||
assert.equal(await readFile(file, "utf8"), contents);
|
||||
};
|
||||
}
|
||||
|
||||
for (const layout of ["standard", "diff", "deep"] as const) {
|
||||
test(`${layout}: a retained finding only suppresses late progress from the same owner`, async (t) => {
|
||||
const f = await fixture(t, layout);
|
||||
@@ -258,15 +272,7 @@ for (const layout of ["standard", "deep"] as const) {
|
||||
}),
|
||||
);
|
||||
const checkpointRoot = path.join(f.root, "checkpoints");
|
||||
const checkpoints = await Promise.all(
|
||||
(await readdir(checkpointRoot)).map(
|
||||
async (name) =>
|
||||
[
|
||||
name,
|
||||
await readFile(path.join(checkpointRoot, name), "utf8"),
|
||||
] as const,
|
||||
),
|
||||
);
|
||||
const assertPreserved = await captureCheckpoints(checkpointRoot);
|
||||
await f.write({
|
||||
...f.draft({}, layout !== "deep"),
|
||||
findings: [
|
||||
@@ -288,11 +294,7 @@ for (const layout of ["standard", "deep"] as const) {
|
||||
);
|
||||
await f.write(f.draft({}, layout !== "deep"));
|
||||
}
|
||||
for (const [name, contents] of checkpoints)
|
||||
assert.equal(
|
||||
await readFile(path.join(checkpointRoot, name), "utf8"),
|
||||
contents,
|
||||
);
|
||||
await assertPreserved();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -411,9 +413,7 @@ test("Diff ledger retains verified merged candidate resolutions on later saves",
|
||||
const coverage = await f.read();
|
||||
assert.deepEqual(coverage.deferred, []);
|
||||
assert.equal(coverage.completeness, undefined);
|
||||
const saved = JSON.parse(
|
||||
await readFile(path.join(f.root, "findings.json"), "utf8"),
|
||||
);
|
||||
const saved = await readJson(f.root, "findings.json");
|
||||
assert.equal(saved.findings.length, 1);
|
||||
assert.ok(
|
||||
saved.findings[0].provenance.previousFindings.some(
|
||||
@@ -482,9 +482,7 @@ for name,document in zip(['scan-manifest.json','findings.json','coverage.json'],
|
||||
row.provenance?.candidateId === "review" &&
|
||||
row.provenance.workerId === "worker";
|
||||
assert.ok(coverage.deferred.some(workerCandidate));
|
||||
const saved = JSON.parse(
|
||||
await readFile(path.join(f.root, "findings.json"), "utf8"),
|
||||
);
|
||||
const saved = await readJson(f.root, "findings.json");
|
||||
assert.equal(saved.findings.length, 1);
|
||||
assert.equal(saved.findings[0].provenance.candidateReopened, true);
|
||||
assert.equal(
|
||||
@@ -536,7 +534,7 @@ for (const mode of ["standard", "diff", "worker"] as const) {
|
||||
f.root,
|
||||
mode === "worker" ? "result.json" : "coverage.json",
|
||||
);
|
||||
const saved = JSON.parse(await readFile(file, "utf8"));
|
||||
const saved = await readJson(file);
|
||||
const coverage = mode === "worker" ? saved.reviewState : saved;
|
||||
coverage[field][0].sourceWorkerId = owner;
|
||||
const earlierFiles = [
|
||||
@@ -549,15 +547,7 @@ for (const mode of ["standard", "diff", "worker"] as const) {
|
||||
await writeFile(file, JSON.stringify(saved, null, 2) + "\n");
|
||||
}
|
||||
const checkpointRoot = path.join(f.root, "checkpoints");
|
||||
const checkpoints = await Promise.all(
|
||||
(await readdir(checkpointRoot)).map(
|
||||
async (name) =>
|
||||
[
|
||||
name,
|
||||
await readFile(path.join(checkpointRoot, name), "utf8"),
|
||||
] as const,
|
||||
),
|
||||
);
|
||||
const assertPreserved = await captureCheckpoints(checkpointRoot);
|
||||
await f.write(
|
||||
f.draft({
|
||||
deferred: [
|
||||
@@ -568,11 +558,7 @@ for (const mode of ["standard", "diff", "worker"] as const) {
|
||||
],
|
||||
}),
|
||||
);
|
||||
for (const [name, contents] of checkpoints)
|
||||
assert.equal(
|
||||
await readFile(path.join(checkpointRoot, name), "utf8"),
|
||||
contents,
|
||||
);
|
||||
await assertPreserved();
|
||||
const restored = await f.read();
|
||||
assert.ok(
|
||||
restored[field].some(
|
||||
@@ -620,7 +606,7 @@ for (const field of ["surfaces", "deferred"] as const) {
|
||||
complete: true,
|
||||
});
|
||||
const resultPath = path.join(f.root, "result.json");
|
||||
const saved = JSON.parse(await readFile(resultPath, "utf8"));
|
||||
const saved = await readJson(resultPath);
|
||||
saved.reviewState[field][0].sourceWorkerId = owner;
|
||||
const contents = JSON.stringify(saved, null, 2) + "\n";
|
||||
await writeFile(resultPath, contents);
|
||||
@@ -715,14 +701,9 @@ for (const candidateId of ["legacy-candidate", "review/auth"]) {
|
||||
),
|
||||
);
|
||||
if (sameOwner && outcome === "reported") {
|
||||
const saved = JSON.parse(
|
||||
await readFile(
|
||||
path.join(
|
||||
f.root,
|
||||
mode === "worker" ? "result.json" : "findings.json",
|
||||
),
|
||||
"utf8",
|
||||
),
|
||||
const saved = await readJson(
|
||||
f.root,
|
||||
mode === "worker" ? "result.json" : "findings.json",
|
||||
);
|
||||
assert.ok(
|
||||
JSON.stringify(saved.findings[0].provenance).includes(
|
||||
@@ -770,9 +751,7 @@ test("publishes colliding worker-local deferred IDs without changing their evide
|
||||
context,
|
||||
{ ...projected, handoffClaimToken: context.handoffClaimToken },
|
||||
async (args: string[]) => {
|
||||
const draft = JSON.parse(
|
||||
await readFile(args[args.indexOf("--draft-path") + 1]!, "utf8"),
|
||||
);
|
||||
const draft = await readJson(args[args.indexOf("--draft-path") + 1]!);
|
||||
const rows = draft.reviewState.deferred;
|
||||
assert.equal(new Set(rows.map((row: { id: string }) => row.id)).size, 3);
|
||||
assert.equal(rows[2].id, "candidate-review-2");
|
||||
@@ -829,9 +808,7 @@ for (const mode of ["standard", "diff"] as const) {
|
||||
...draft({}, true),
|
||||
findings: [current],
|
||||
});
|
||||
const saved = JSON.parse(
|
||||
await readFile(path.join(context.root, "findings.json"), "utf8"),
|
||||
);
|
||||
const saved = await readJson(context.root, "findings.json");
|
||||
assert.equal(saved.findings.length, 1, `replay=${replay}`);
|
||||
assert.equal(saved.findings[0].severity.level, "low");
|
||||
assert.equal(saved.findings[0].summary, current.summary);
|
||||
@@ -859,9 +836,7 @@ for (const mode of ["standard", "diff"] as const) {
|
||||
},
|
||||
],
|
||||
});
|
||||
const independent = JSON.parse(
|
||||
await readFile(path.join(independentRoot, "findings.json"), "utf8"),
|
||||
);
|
||||
const independent = await readJson(independentRoot, "findings.json");
|
||||
assert.equal(independent.findings.length, 2);
|
||||
});
|
||||
}
|
||||
@@ -903,9 +878,7 @@ for (const mode of ["standard", "diff"] as const) {
|
||||
...draft({}, true),
|
||||
findings: [current],
|
||||
});
|
||||
const saved = JSON.parse(
|
||||
await readFile(path.join(context.root, "findings.json"), "utf8"),
|
||||
);
|
||||
const saved = await readJson(context.root, "findings.json");
|
||||
assert.equal(saved.findings.length, 2, `replay=${replay}`);
|
||||
assert.deepEqual(
|
||||
saved.findings.map(
|
||||
@@ -1134,7 +1107,7 @@ for (const mode of ["standard", "diff"] as const) {
|
||||
);
|
||||
} else {
|
||||
const file = path.join(f.root, "coverage.json");
|
||||
const coverage = JSON.parse(await readFile(file, "utf8"));
|
||||
const coverage = await readJson(file);
|
||||
coverage.surfaces[0].candidateId = previous.candidateId;
|
||||
const earlierFiles = [
|
||||
path.join(f.root, "checkpoint-head.json"),
|
||||
@@ -1263,9 +1236,7 @@ for (const mode of ["standard", "diff"] as const) {
|
||||
coverage.deferred,
|
||||
independentPending ? [pending("worker-c")] : [],
|
||||
);
|
||||
const saved = JSON.parse(
|
||||
await readFile(path.join(f.root, "findings.json"), "utf8"),
|
||||
);
|
||||
const saved = await readJson(f.root, "findings.json");
|
||||
assert.equal(saved.findings.length, 1);
|
||||
assert.equal(saved.findings[0].provenance.sourceWorkerId, "worker-a");
|
||||
assert.ok(
|
||||
@@ -1359,9 +1330,7 @@ for (const reopened of [false, true]) {
|
||||
),
|
||||
dismissed,
|
||||
);
|
||||
const saved = JSON.parse(
|
||||
await readFile(path.join(f.root, "findings.json"), "utf8"),
|
||||
);
|
||||
const saved = await readJson(f.root, "findings.json");
|
||||
assert.equal(saved.findings.length, dismissed ? 0 : 1);
|
||||
if (!dismissed)
|
||||
assert.equal(
|
||||
@@ -1383,22 +1352,10 @@ for (const reopened of [false, true]) {
|
||||
};
|
||||
await assertCurrent();
|
||||
const checkpoints = path.join(f.root, "checkpoints");
|
||||
const originals = await Promise.all(
|
||||
(await readdir(checkpoints)).map(
|
||||
async (name) =>
|
||||
[
|
||||
name,
|
||||
await readFile(path.join(checkpoints, name), "utf8"),
|
||||
] as const,
|
||||
),
|
||||
);
|
||||
const assertPreserved = await captureCheckpoints(checkpoints);
|
||||
await f.write(f.draft());
|
||||
await assertCurrent();
|
||||
for (const [name, contents] of originals)
|
||||
assert.equal(
|
||||
await readFile(path.join(checkpoints, name), "utf8"),
|
||||
contents,
|
||||
);
|
||||
await assertPreserved();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1466,9 +1423,7 @@ for (const reopened of [false, true]) {
|
||||
handoffClaimToken,
|
||||
});
|
||||
const coverage = await f.read();
|
||||
const published = JSON.parse(
|
||||
await readFile(path.join(f.root, "findings.json"), "utf8"),
|
||||
);
|
||||
const published = await readJson(f.root, "findings.json");
|
||||
assert.equal(
|
||||
unresolvedCandidates(coverage, published.findings).length,
|
||||
expected.length,
|
||||
@@ -1526,7 +1481,7 @@ test("Deep Scan clears historical reopening after the same worker accepts the ca
|
||||
findings: [],
|
||||
});
|
||||
const previousPath = path.join(f.root, "saved-iteration.json");
|
||||
await writeFile(previousPath, JSON.stringify(persistedScanUnion(previous)));
|
||||
await writeJson(previousPath, persistedScanUnion(previous));
|
||||
const previousBytes = await readFile(previousPath, "utf8");
|
||||
assert.equal(previous.unresolvedCandidates.length, 1);
|
||||
await f.write({ ...scanUnionToDraft(previous), handoffClaimToken });
|
||||
@@ -1584,15 +1539,7 @@ for (const mode of ["standard", "diff"] as const) {
|
||||
findings: [previous],
|
||||
});
|
||||
const checkpointRoot = path.join(f.root, "checkpoints");
|
||||
const originals = await Promise.all(
|
||||
(await readdir(checkpointRoot)).map(
|
||||
async (name) =>
|
||||
[
|
||||
name,
|
||||
await readFile(path.join(checkpointRoot, name), "utf8"),
|
||||
] as const,
|
||||
),
|
||||
);
|
||||
const assertPreserved = await captureCheckpoints(checkpointRoot);
|
||||
const current = {
|
||||
...previous,
|
||||
provenance: {
|
||||
@@ -1603,13 +1550,11 @@ for (const mode of ["standard", "diff"] as const) {
|
||||
};
|
||||
for (const replay of [false, true]) {
|
||||
await f.write({ ...f.draft({}, true), findings: [current] });
|
||||
const savedFindings = JSON.parse(
|
||||
await readFile(path.join(f.root, "findings.json"), "utf8"),
|
||||
);
|
||||
const savedFindings = await readJson(f.root, "findings.json");
|
||||
const coverage = await f.read();
|
||||
const checkpoints = await Promise.all(
|
||||
(await readdir(checkpointRoot)).map(async (name) =>
|
||||
JSON.parse(await readFile(path.join(checkpointRoot, name), "utf8")),
|
||||
(await readdir(checkpointRoot)).map(
|
||||
async (name) => await readJson(checkpointRoot, name),
|
||||
),
|
||||
);
|
||||
const checkpoint = checkpoints.find(
|
||||
@@ -1665,11 +1610,7 @@ for (const mode of ["standard", "diff"] as const) {
|
||||
);
|
||||
}
|
||||
}
|
||||
for (const [name, contents] of originals)
|
||||
assert.equal(
|
||||
await readFile(path.join(checkpointRoot, name), "utf8"),
|
||||
contents,
|
||||
);
|
||||
await assertPreserved();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { createTestWorkbench } from "./support/discovery.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { test } from "node:test";
|
||||
import { test, type TestContext } from "node:test";
|
||||
import { importSource } from "./import-module.ts";
|
||||
import {
|
||||
draftApi,
|
||||
@@ -16,7 +17,29 @@ const { createScanArtifactContext } = await importSource(
|
||||
"../src/artifact-context.ts",
|
||||
{ absWorkingDir: import.meta.dirname },
|
||||
);
|
||||
import { mergeWorkerFiles, scanUnionToDraft } from "./scan-union-fixture.ts";
|
||||
import {
|
||||
mergeWorkerFiles,
|
||||
scanUnionToDraft,
|
||||
validateDiscoveryArtifacts,
|
||||
} from "./scan-union-fixture.ts";
|
||||
|
||||
async function reopeningFixture(
|
||||
t: TestContext,
|
||||
mode: "standard" | "worker" | "deep",
|
||||
) {
|
||||
const f = await fixture(t, mode);
|
||||
const directory = path.dirname(f.root);
|
||||
const target = path.join(directory, "target");
|
||||
const state = path.join(directory, "state");
|
||||
await mkdir(target);
|
||||
await writeFile(path.join(target, "app.py"), "synthetic source\n");
|
||||
const workbench = await createTestWorkbench(directory);
|
||||
const current = {
|
||||
...finding("review", "app.py"),
|
||||
provenance: { source: "local_plugin", candidateId: "candidate-one" },
|
||||
};
|
||||
return { f, directory, target, state, current, workbench };
|
||||
}
|
||||
|
||||
for (const mode of ["standard", "worker"] as const) {
|
||||
for (const scenario of [
|
||||
@@ -26,13 +49,8 @@ for (const mode of ["standard", "worker"] as const) {
|
||||
"other-candidate",
|
||||
] as const) {
|
||||
test(`publishes explicit candidate state through ${mode}: ${scenario}`, async (t) => {
|
||||
const f = await fixture(t, mode);
|
||||
const directory = path.dirname(f.root);
|
||||
const target = path.join(directory, "target");
|
||||
const state = path.join(directory, "state");
|
||||
await mkdir(target);
|
||||
await writeFile(path.join(target, "app.py"), "synthetic source\n");
|
||||
const workbench = await createTestWorkbench(directory);
|
||||
const { f, directory, target, state, current, workbench } =
|
||||
await reopeningFixture(t, mode);
|
||||
let context = { ...f.context, repoRoot: target };
|
||||
if (mode === "standard") {
|
||||
const { scan } = await workbench([
|
||||
@@ -58,10 +76,6 @@ for (const mode of ["standard", "worker"] as const) {
|
||||
await mkdir(context.root, { recursive: true });
|
||||
}
|
||||
assert.ok(context.scanId);
|
||||
const current = {
|
||||
...finding("review", "app.py"),
|
||||
provenance: { source: "local_plugin", candidateId: "candidate-one" },
|
||||
};
|
||||
const pending = {
|
||||
id: "gap",
|
||||
candidateId:
|
||||
@@ -175,3 +189,184 @@ for (const mode of ["standard", "worker"] as const) {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const outcome of ["reported", "rejected", "not_applicable"] as const) {
|
||||
for (const reopened of [false, true]) {
|
||||
for (const stop of ["fail-deep-scan", "cancel-scan"] as const) {
|
||||
test(`worker terminal publication survives ${stop}: ${outcome}, reopened=${reopened}`, async (t) => {
|
||||
const { directory, target, state, current, workbench } =
|
||||
await reopeningFixture(t, "deep");
|
||||
const home = path.join(directory, "home");
|
||||
await mkdir(path.join(home, "codex-security"), {
|
||||
recursive: true,
|
||||
mode: 0o700,
|
||||
});
|
||||
await writeFile(
|
||||
path.join(home, "codex-security/config.toml"),
|
||||
"[deep_scan]\nworkers = 1\nmax_discovery_runs = 1\n",
|
||||
);
|
||||
const { deepScan } = await workbench([
|
||||
"begin-deep-scan",
|
||||
"--thread-id",
|
||||
"synthetic-parent-thread",
|
||||
"--target-path",
|
||||
target,
|
||||
"--scope",
|
||||
".",
|
||||
"--scan-root",
|
||||
path.join(directory, "scans"),
|
||||
"--available-parallelism",
|
||||
"16",
|
||||
]);
|
||||
const scanId = deepScan.scanId;
|
||||
const workerId = randomUUID();
|
||||
const output = path.join(
|
||||
deepScan.scanDir,
|
||||
"artifacts/deep_discovery/worker",
|
||||
);
|
||||
await mkdir(output, { recursive: true });
|
||||
const prompt = path.join(output, "prompt.md");
|
||||
await writeFile(prompt, "Review the synthetic candidate.\n");
|
||||
const workerArgs = [
|
||||
"upsert-deep-scan-worker",
|
||||
"--scan-id",
|
||||
scanId,
|
||||
"--worker-id",
|
||||
workerId,
|
||||
"--kind",
|
||||
"discovery",
|
||||
"--prompt-path",
|
||||
prompt,
|
||||
"--artifact-dir",
|
||||
output,
|
||||
"--attempt",
|
||||
"1",
|
||||
];
|
||||
await workbench([...workerArgs, "--status", "running"]);
|
||||
const context = {
|
||||
root: output,
|
||||
repoRoot: target,
|
||||
scanId,
|
||||
layout: "worker",
|
||||
scope: ".",
|
||||
};
|
||||
const pending = {
|
||||
id: "gap",
|
||||
candidateId: "candidate-one",
|
||||
reason: "Earlier proof gap.",
|
||||
};
|
||||
const draft = {
|
||||
scanId,
|
||||
complete: true,
|
||||
findings: outcome === "reported" ? [current] : [],
|
||||
reviewState: {
|
||||
completeness: "partial",
|
||||
surfaces:
|
||||
outcome === "reported"
|
||||
? []
|
||||
: [
|
||||
{
|
||||
id: "review",
|
||||
label: "Candidate review",
|
||||
candidateId: "candidate-one",
|
||||
disposition: outcome,
|
||||
notes: "Current review resolved the candidate.",
|
||||
receiptRefs: [],
|
||||
},
|
||||
],
|
||||
explicitExclusions: [],
|
||||
deferred: [pending],
|
||||
},
|
||||
};
|
||||
await draftApi.recordCodexSecurityWorkerScanDraft(context, draft);
|
||||
if (reopened)
|
||||
await draftApi.recordCodexSecurityWorkerScanDraft(context, {
|
||||
...draft,
|
||||
findings: [],
|
||||
reviewState: {
|
||||
...draft.reviewState,
|
||||
surfaces: [],
|
||||
deferred: [
|
||||
{
|
||||
...pending,
|
||||
reason: "A later publication explicitly reopens the review.",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const resultPath = path.join(output, "result.json");
|
||||
await validateDiscoveryArtifacts(
|
||||
{ workersRoot: output },
|
||||
resultPath,
|
||||
scanId,
|
||||
);
|
||||
await workbench([
|
||||
...workerArgs,
|
||||
"--status",
|
||||
"succeeded",
|
||||
"--result-manifest-path",
|
||||
resultPath,
|
||||
]);
|
||||
const snapshots = await Promise.all(
|
||||
[
|
||||
"result.json",
|
||||
"checkpoint-head.json",
|
||||
...(await readdir(path.join(output, "checkpoints"))).map((name) =>
|
||||
path.join("checkpoints", name),
|
||||
),
|
||||
].map(
|
||||
async (name) =>
|
||||
[name, await readFile(path.join(output, name))] as const,
|
||||
),
|
||||
);
|
||||
await workbench([
|
||||
stop,
|
||||
"--scan-id",
|
||||
scanId,
|
||||
...(stop === "cancel-scan"
|
||||
? ["--thread-id", "synthetic-parent-thread"]
|
||||
: ["--message", "Synthetic interruption."]),
|
||||
]);
|
||||
const isWorkerCandidate = (row: {
|
||||
provenance?: Record<string, unknown>;
|
||||
}) =>
|
||||
row.provenance?.workerId === workerId &&
|
||||
row.provenance.attempt === 1 &&
|
||||
row.provenance.candidateId === pending.candidateId;
|
||||
for (let replay = 0; replay < 2; replay++) {
|
||||
const { scan } = await workbench(["get-scan", "--scan-id", scanId]);
|
||||
assert.equal(scan.progress.candidates.unresolved, reopened ? 1 : 0);
|
||||
const coverage = await readSavedReviewState(deepScan.scanDir, state);
|
||||
const findings = await readJson(deepScan.scanDir, "findings.json");
|
||||
const deferred = coverage.deferred.filter(isWorkerCandidate);
|
||||
assert.equal(deferred.length, reopened ? 1 : 0);
|
||||
if (reopened)
|
||||
assert.equal(
|
||||
deferred[0].reason,
|
||||
"A later publication explicitly reopens the review.",
|
||||
);
|
||||
if (outcome === "reported") {
|
||||
assert.equal(findings.findings.length, 1);
|
||||
assert.equal(
|
||||
findings.findings[0].provenance.candidateReopened === true,
|
||||
reopened,
|
||||
);
|
||||
} else {
|
||||
const decisions = coverage.surfaces.filter(isWorkerCandidate);
|
||||
assert.equal(decisions.length, reopened ? 0 : 1);
|
||||
if (!reopened) assert.equal(decisions[0].disposition, outcome);
|
||||
}
|
||||
for (const [name, bytes] of snapshots)
|
||||
assert.deepEqual(await readFile(path.join(output, name)), bytes);
|
||||
await workbench([
|
||||
"preserve-scan-results",
|
||||
"--scan-id",
|
||||
scanId,
|
||||
"--thread-id",
|
||||
"synthetic-parent-thread",
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,189 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { test } from "node:test";
|
||||
import { importSource } from "./import-module.ts";
|
||||
import { finding, scanId, workerDraft } from "./scan-draft-fixture.ts";
|
||||
import { readJson } from "./support/json.ts";
|
||||
import { temporaryDirectory } from "./support/temporary-directories.ts";
|
||||
|
||||
const { recordCodexSecurityWorkerScanDraft } = await importSource(
|
||||
"../src/artifact-scan-draft.ts",
|
||||
{ absWorkingDir: import.meta.dirname },
|
||||
);
|
||||
import {
|
||||
mergeWorkerFiles,
|
||||
persistedScanUnion,
|
||||
parseScanUnion,
|
||||
} from "./scan-union-fixture.ts";
|
||||
const { createDeepScanArtifacts } = await importSource(
|
||||
"../src/deep-scan/artifacts.ts",
|
||||
{ absWorkingDir: import.meta.dirname },
|
||||
);
|
||||
|
||||
const cases = [
|
||||
...["origin:a", "opaque-ref", "previous:0", "saved-worker:0"].flatMap(
|
||||
(reference) =>
|
||||
[false, true].map((reopened) => ({
|
||||
reference,
|
||||
reopened,
|
||||
owner: "saved-worker" as string | undefined,
|
||||
currentWorker: undefined as string | undefined,
|
||||
})),
|
||||
),
|
||||
...["origin", "previous"].flatMap((currentWorker) =>
|
||||
[
|
||||
{ owner: "saved-worker", reopened: false },
|
||||
{ owner: "saved-worker", reopened: true },
|
||||
{ owner: undefined, reopened: false },
|
||||
].map((state) => ({
|
||||
...state,
|
||||
reference: `${currentWorker}:a`,
|
||||
currentWorker,
|
||||
})),
|
||||
),
|
||||
];
|
||||
|
||||
for (const { reference, reopened, owner, currentWorker } of cases) {
|
||||
test(`resumed Deep Scan union preserves ${reference}, owner=${owner}, current=${currentWorker}, reopened=${reopened}`, async (t) => {
|
||||
const root = await temporaryDirectory("candidate-source-owner-", true);
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const artifacts = createDeepScanArtifacts(root);
|
||||
await mkdir(artifacts.dedupRoot, { recursive: true });
|
||||
const original = {
|
||||
...finding("candidate-one", "app.py"),
|
||||
provenance: {
|
||||
source: "local_plugin",
|
||||
candidateId: "candidate-one",
|
||||
...(owner === undefined ? {} : { sourceWorkerId: owner }),
|
||||
},
|
||||
};
|
||||
// Persisted references are opaque; older accepted aggregates retain them.
|
||||
let previousPath = path.join(artifacts.dedupRoot, "previous.json");
|
||||
await writeFile(
|
||||
previousPath,
|
||||
JSON.stringify({
|
||||
scanId,
|
||||
findings: [
|
||||
{
|
||||
...original,
|
||||
provenance: {
|
||||
...original.provenance,
|
||||
sourceFindingIds: [reference],
|
||||
sourceFindings: [{ id: reference, finding: original }],
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
const retained = new Map<string, Buffer>();
|
||||
retained.set(previousPath, await readFile(previousPath));
|
||||
for (let round = 0; round < 2; round++) {
|
||||
const workers =
|
||||
round === 0
|
||||
? [
|
||||
currentWorker ?? (reopened ? "saved-worker" : "next-worker"),
|
||||
...(currentWorker && reopened ? ["saved-worker"] : []),
|
||||
]
|
||||
: ["last-worker"];
|
||||
const claimedWorkers = [];
|
||||
for (const workerId of workers) {
|
||||
const workerRoot = path.join(artifacts.workersRoot, workerId, "output");
|
||||
await mkdir(workerRoot, { recursive: true });
|
||||
const pending = reopened && workerId === "saved-worker";
|
||||
await recordCodexSecurityWorkerScanDraft(
|
||||
{ root: workerRoot, repoRoot: root, scanId, layout: "worker" },
|
||||
workerDraft(
|
||||
workerId === currentWorker
|
||||
? [
|
||||
{
|
||||
...finding("candidate-two", "other.py"),
|
||||
provenance: {
|
||||
source: "local_plugin",
|
||||
candidateId: "candidate-two",
|
||||
sourceWorkerId: "imported-owner",
|
||||
},
|
||||
},
|
||||
]
|
||||
: [],
|
||||
{
|
||||
complete: true,
|
||||
reviewState: {
|
||||
completeness: pending ? "partial" : "complete",
|
||||
surfaces: [],
|
||||
explicitExclusions: [],
|
||||
deferred: pending
|
||||
? [
|
||||
{
|
||||
id: "proof-gap",
|
||||
candidateId: "candidate-one",
|
||||
reason: "Synthetic additional review required.",
|
||||
},
|
||||
]
|
||||
: [],
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
const resultPath = path.join(workerRoot, "result.json");
|
||||
retained.set(resultPath, await readFile(resultPath));
|
||||
claimedWorkers.push({ id: workerId, resultPath });
|
||||
}
|
||||
const aggregate = await mergeWorkerFiles(
|
||||
root,
|
||||
claimedWorkers,
|
||||
await readJson(previousPath),
|
||||
);
|
||||
const resultPath = path.join(artifacts.dedupRoot, `round-${round}.json`);
|
||||
await writeFile(
|
||||
resultPath,
|
||||
JSON.stringify(persistedScanUnion(aggregate)),
|
||||
);
|
||||
const saved = parseScanUnion(await readJson(resultPath));
|
||||
assert.equal(saved.findings.length, currentWorker ? 2 : 1);
|
||||
assert.equal(saved.findings[0].provenance.candidateId, "candidate-one");
|
||||
assert.equal(saved.findings[0].provenance.sourceWorkerId, owner);
|
||||
assert.equal(
|
||||
saved.findings[0].provenance.candidateReopened === true,
|
||||
reopened,
|
||||
);
|
||||
assert.deepEqual(saved.findings[0].provenance.sourceFindingIds, [
|
||||
reference,
|
||||
]);
|
||||
assert.deepEqual(saved.findings[0].provenance.sourceFindings, [
|
||||
{ id: reference, finding: original },
|
||||
]);
|
||||
if (currentWorker) {
|
||||
const current = saved.findings[1];
|
||||
assert.equal(current.provenance.candidateId, "candidate-two");
|
||||
assert.equal(current.provenance.sourceWorkerId, currentWorker);
|
||||
assert.equal(current.provenance.candidateReopened === true, false);
|
||||
assert.deepEqual(current.provenance.sourceFindingIds, [
|
||||
`${currentWorker}:0`,
|
||||
]);
|
||||
assert.equal(
|
||||
current.provenance.sourceFindings[0].finding.provenance
|
||||
.sourceWorkerId,
|
||||
currentWorker,
|
||||
);
|
||||
assert.equal(
|
||||
current.provenance.sourceFindings[0].finding.provenance.previousFindings.some(
|
||||
(row: { provenance: { sourceWorkerId?: string } }) =>
|
||||
row.provenance.sourceWorkerId === "imported-owner",
|
||||
),
|
||||
true,
|
||||
);
|
||||
}
|
||||
assert.equal((saved.unresolvedCandidates ?? []).length, Number(reopened));
|
||||
if (reopened)
|
||||
assert.equal(
|
||||
saved.unresolvedCandidates[0].sourceWorkerId,
|
||||
"saved-worker",
|
||||
);
|
||||
for (const [file, bytes] of retained)
|
||||
assert.deepEqual(await readFile(file), bytes);
|
||||
retained.set(resultPath, await readFile(resultPath));
|
||||
previousPath = resultPath;
|
||||
}
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,4 @@
|
||||
import { readJson } from "./support/json.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
@@ -107,7 +108,7 @@ for (const { label, candidateId, receipt, disposition } of cases) {
|
||||
findings: [],
|
||||
reviewState: { surfaces: [], explicitExclusions: [], deferred: [] },
|
||||
});
|
||||
const recovered = JSON.parse(await readFile(resultPath, "utf8"));
|
||||
const recovered = await readJson(resultPath);
|
||||
assert.equal(
|
||||
await readFile(path.join(archived, "result.json"), "utf8"),
|
||||
original,
|
||||
|
||||
@@ -1,223 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFile } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { test } from "node:test";
|
||||
import { promisify } from "node:util";
|
||||
import { importSource } from "./import-module.ts";
|
||||
import { draftApi, fixture } from "./scan-draft-recovery-fixture.ts";
|
||||
import { finding } from "./scan-draft-fixture.ts";
|
||||
import { readSavedReviewState, readJson } from "./support/json.ts";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const { validateDiscoveryArtifacts } = await importSource(
|
||||
"../src/deep-scan/artifact-validation.ts",
|
||||
{ absWorkingDir: import.meta.dirname },
|
||||
);
|
||||
|
||||
for (const outcome of ["reported", "rejected", "not_applicable"] as const) {
|
||||
for (const reopened of [false, true]) {
|
||||
for (const stop of ["fail-deep-scan", "cancel-scan"] as const) {
|
||||
test(`worker terminal publication survives ${stop}: ${outcome}, reopened=${reopened}`, async (t) => {
|
||||
const f = await fixture(t, "deep");
|
||||
const directory = path.dirname(f.root);
|
||||
const target = path.join(directory, "target");
|
||||
const home = path.join(directory, "home");
|
||||
const state = path.join(directory, "state");
|
||||
await mkdir(target);
|
||||
await writeFile(path.join(target, "app.py"), "synthetic source\n");
|
||||
await mkdir(path.join(home, "codex-security"), {
|
||||
recursive: true,
|
||||
mode: 0o700,
|
||||
});
|
||||
await writeFile(
|
||||
path.join(home, "codex-security/config.toml"),
|
||||
"[deep_scan]\nworkers = 1\nmax_discovery_runs = 1\n",
|
||||
);
|
||||
const workbench = async (...args: string[]) => {
|
||||
const { stdout } = await execFileAsync(
|
||||
process.env.PYTHON?.trim() || "python3",
|
||||
[
|
||||
path.join(import.meta.dirname, "../../scripts/workbench_db.py"),
|
||||
...args,
|
||||
],
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
CODEX_HOME: home,
|
||||
CODEX_SECURITY_STATE_DIR: state,
|
||||
},
|
||||
},
|
||||
);
|
||||
return JSON.parse(stdout);
|
||||
};
|
||||
const { deepScan } = await workbench(
|
||||
"begin-deep-scan",
|
||||
"--thread-id",
|
||||
"synthetic-parent-thread",
|
||||
"--target-path",
|
||||
target,
|
||||
"--scope",
|
||||
".",
|
||||
"--scan-root",
|
||||
path.join(directory, "scans"),
|
||||
"--available-parallelism",
|
||||
"16",
|
||||
);
|
||||
const scanId = deepScan.scanId;
|
||||
const workerId = randomUUID();
|
||||
const output = path.join(
|
||||
deepScan.scanDir,
|
||||
"artifacts/deep_discovery/worker",
|
||||
);
|
||||
await mkdir(output, { recursive: true });
|
||||
const prompt = path.join(output, "prompt.md");
|
||||
await writeFile(prompt, "Review the synthetic candidate.\n");
|
||||
const workerArgs = [
|
||||
"upsert-deep-scan-worker",
|
||||
"--scan-id",
|
||||
scanId,
|
||||
"--worker-id",
|
||||
workerId,
|
||||
"--kind",
|
||||
"discovery",
|
||||
"--prompt-path",
|
||||
prompt,
|
||||
"--artifact-dir",
|
||||
output,
|
||||
"--attempt",
|
||||
"1",
|
||||
];
|
||||
await workbench(...workerArgs, "--status", "running");
|
||||
const context = {
|
||||
root: output,
|
||||
repoRoot: target,
|
||||
scanId,
|
||||
layout: "worker",
|
||||
scope: ".",
|
||||
};
|
||||
const current = {
|
||||
...finding("review", "app.py"),
|
||||
provenance: { source: "local_plugin", candidateId: "candidate-one" },
|
||||
};
|
||||
const pending = {
|
||||
id: "gap",
|
||||
candidateId: "candidate-one",
|
||||
reason: "Earlier proof gap.",
|
||||
};
|
||||
const draft = {
|
||||
scanId,
|
||||
complete: true,
|
||||
findings: outcome === "reported" ? [current] : [],
|
||||
reviewState: {
|
||||
completeness: "partial",
|
||||
surfaces:
|
||||
outcome === "reported"
|
||||
? []
|
||||
: [
|
||||
{
|
||||
id: "review",
|
||||
label: "Candidate review",
|
||||
candidateId: "candidate-one",
|
||||
disposition: outcome,
|
||||
notes: "Current review resolved the candidate.",
|
||||
receiptRefs: [],
|
||||
},
|
||||
],
|
||||
explicitExclusions: [],
|
||||
deferred: [pending],
|
||||
},
|
||||
};
|
||||
await draftApi.recordCodexSecurityWorkerScanDraft(context, draft);
|
||||
if (reopened)
|
||||
await draftApi.recordCodexSecurityWorkerScanDraft(context, {
|
||||
...draft,
|
||||
findings: [],
|
||||
reviewState: {
|
||||
...draft.reviewState,
|
||||
surfaces: [],
|
||||
deferred: [
|
||||
{
|
||||
...pending,
|
||||
reason: "A later publication explicitly reopens the review.",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const resultPath = path.join(output, "result.json");
|
||||
await validateDiscoveryArtifacts(
|
||||
{ workersRoot: output },
|
||||
resultPath,
|
||||
scanId,
|
||||
);
|
||||
await workbench(
|
||||
...workerArgs,
|
||||
"--status",
|
||||
"succeeded",
|
||||
"--result-manifest-path",
|
||||
resultPath,
|
||||
);
|
||||
const snapshots = await Promise.all(
|
||||
[
|
||||
"result.json",
|
||||
"checkpoint-head.json",
|
||||
...(await readdir(path.join(output, "checkpoints"))).map((name) =>
|
||||
path.join("checkpoints", name),
|
||||
),
|
||||
].map(
|
||||
async (name) =>
|
||||
[name, await readFile(path.join(output, name))] as const,
|
||||
),
|
||||
);
|
||||
await workbench(
|
||||
stop,
|
||||
"--scan-id",
|
||||
scanId,
|
||||
...(stop === "cancel-scan"
|
||||
? ["--thread-id", "synthetic-parent-thread"]
|
||||
: ["--message", "Synthetic interruption."]),
|
||||
);
|
||||
const isWorkerCandidate = (row: {
|
||||
provenance?: Record<string, unknown>;
|
||||
}) =>
|
||||
row.provenance?.workerId === workerId &&
|
||||
row.provenance.attempt === 1 &&
|
||||
row.provenance.candidateId === pending.candidateId;
|
||||
for (let replay = 0; replay < 2; replay++) {
|
||||
const { scan } = await workbench("get-scan", "--scan-id", scanId);
|
||||
assert.equal(scan.progress.candidates.unresolved, reopened ? 1 : 0);
|
||||
const coverage = await readSavedReviewState(deepScan.scanDir, state);
|
||||
const findings = await readJson(deepScan.scanDir, "findings.json");
|
||||
const deferred = coverage.deferred.filter(isWorkerCandidate);
|
||||
assert.equal(deferred.length, reopened ? 1 : 0);
|
||||
if (reopened)
|
||||
assert.equal(
|
||||
deferred[0].reason,
|
||||
"A later publication explicitly reopens the review.",
|
||||
);
|
||||
if (outcome === "reported") {
|
||||
assert.equal(findings.findings.length, 1);
|
||||
assert.equal(
|
||||
findings.findings[0].provenance.candidateReopened === true,
|
||||
reopened,
|
||||
);
|
||||
} else {
|
||||
const decisions = coverage.surfaces.filter(isWorkerCandidate);
|
||||
assert.equal(decisions.length, reopened ? 0 : 1);
|
||||
if (!reopened) assert.equal(decisions[0].disposition, outcome);
|
||||
}
|
||||
for (const [name, bytes] of snapshots)
|
||||
assert.deepEqual(await readFile(path.join(output, name)), bytes);
|
||||
await workbench(
|
||||
"preserve-scan-results",
|
||||
"--scan-id",
|
||||
scanId,
|
||||
"--thread-id",
|
||||
"synthetic-parent-thread",
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import os
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
from collections.abc import Iterator
|
||||
from contextlib import closing, contextmanager
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -22,6 +24,73 @@ from workbench_test_support import (
|
||||
write_provisional_review_state,
|
||||
)
|
||||
|
||||
write_budget_contract = partial(
|
||||
write_completed_contract, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
|
||||
|
||||
def legacy_pending_review(ledger: Path):
|
||||
"""Reconstruct the surface and pending row emitted by the previous budget writer."""
|
||||
original = {**json.loads(ledger.read_text()), "validation": {"disposition": "deferred"}}
|
||||
surface = {
|
||||
"id": f"candidate-{original['candidate_id']}",
|
||||
"label": original["summary"],
|
||||
"disposition": "needs_follow_up",
|
||||
"notes": original["evidence"],
|
||||
"receiptRefs": [],
|
||||
}
|
||||
pending = {
|
||||
"id": original["candidate_id"],
|
||||
"candidateId": original["candidate_id"],
|
||||
"reason": f"Validation was deferred because the scan reached its cost limit: {original['summary']}. Evidence: {original['evidence']}",
|
||||
"paths": [row["path"] for row in original["locations"]],
|
||||
"surfaceIds": [surface["id"]],
|
||||
}
|
||||
return original, surface, pending
|
||||
|
||||
|
||||
def write_candidates(ledger: Path, *candidates: dict[str, Any]) -> None:
|
||||
ledger.write_text("".join(json.dumps(row) + "\n" for row in candidates))
|
||||
|
||||
|
||||
@contextmanager
|
||||
def edit_findings(scan_dir: Path) -> Iterator[list[dict[str, Any]]]:
|
||||
path = scan_dir / "findings.json"
|
||||
document = json.loads(path.read_text())
|
||||
yield document["findings"]
|
||||
path.write_text(json.dumps(document))
|
||||
|
||||
|
||||
def write_empty_budget_contract(scan_dir: Path, scan_id: str, target: Path) -> None:
|
||||
write_budget_contract(scan_dir, scan_id, target)
|
||||
with edit_findings(scan_dir) as findings:
|
||||
findings.clear()
|
||||
|
||||
|
||||
def persisted_scan(state_dir: Path, scan_id: str) -> sqlite3.Row:
|
||||
with closing(sqlite3.connect(state_dir / "workbench.sqlite3")) as connection:
|
||||
connection.row_factory = sqlite3.Row
|
||||
return connection.execute("SELECT * FROM scans WHERE id = ?", (scan_id,)).fetchone()
|
||||
|
||||
|
||||
def complete_with_coverage(
|
||||
state: Path,
|
||||
scan_id: str,
|
||||
scan_dir: Path,
|
||||
coverage: dict[str, Any],
|
||||
*,
|
||||
modern: bool = False,
|
||||
check: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
if modern:
|
||||
with sqlite3.connect(state / "workbench.sqlite3") as connection:
|
||||
connection.execute(
|
||||
"UPDATE deep_scan_runs SET manifest_path = ? WHERE scan_id = ?",
|
||||
(str(scan_dir / "scan-manifest.json"), scan_id),
|
||||
)
|
||||
return complete_budget_scan(state, scan_id, check=check)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def budget_draft():
|
||||
@@ -36,29 +105,21 @@ def test_budget_completion_retains_each_confirmed_candidate_identity(
|
||||
state_dir, target, scan_dir, scan_id, ledger = budget_scan_fixture(tmp_path)
|
||||
first_candidate = json.loads(ledger.read_text())
|
||||
second_candidate = {**first_candidate, "candidate_id": "candidate-two"}
|
||||
ledger.write_text(
|
||||
"\n".join(json.dumps(row) for row in [first_candidate, second_candidate]) + "\n"
|
||||
)
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
findings_path = scan_dir / "findings.json"
|
||||
findings = json.loads(findings_path.read_text())
|
||||
first = findings["findings"][0]
|
||||
first["provenance"]["candidateId"] = first_candidate["candidate_id"]
|
||||
second = json.loads(json.dumps(first))
|
||||
second["provenance"]["candidateId"] = second_candidate["candidate_id"]
|
||||
second["severity"]["level"] = "low"
|
||||
if variant == "distinct":
|
||||
second["identity"]["instance"] = "second-instance"
|
||||
elif variant == "invalid":
|
||||
second.pop("ruleId")
|
||||
findings["findings"] = [first, second]
|
||||
findings_path.write_text(json.dumps(findings))
|
||||
write_candidates(ledger, first_candidate, second_candidate)
|
||||
write_budget_contract(scan_dir, scan_id, target)
|
||||
with edit_findings(scan_dir) as findings:
|
||||
first = findings[0]
|
||||
first["provenance"]["candidateId"] = first_candidate["candidate_id"]
|
||||
second = json.loads(json.dumps(first))
|
||||
second["provenance"]["candidateId"] = second_candidate["candidate_id"]
|
||||
second["severity"]["level"] = "low"
|
||||
if variant == "distinct":
|
||||
second["identity"]["instance"] = "second-instance"
|
||||
elif variant == "invalid":
|
||||
second.pop("ruleId")
|
||||
findings[:] = [first, second]
|
||||
|
||||
with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
|
||||
connection.row_factory = sqlite3.Row
|
||||
scan = connection.execute("SELECT * FROM scans WHERE id = ?", (scan_id,)).fetchone()
|
||||
scan = persisted_scan(state_dir, scan_id)
|
||||
budget_draft(scan, scan_dir, [first_candidate, second_candidate], "Synthetic budget stop.")
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
assert {row["candidateId"] for row in coverage["deferred"] if row.get("candidateId")} == (
|
||||
@@ -81,16 +142,12 @@ def test_budget_completion_uses_current_candidate_state_after_finding_reopens(
|
||||
state_dir, target, scan_dir, scan_id, ledger = budget_scan_fixture(tmp_path)
|
||||
candidate = json.loads(ledger.read_text())
|
||||
candidate["validation"] = {"disposition": decision}
|
||||
ledger.write_text(json.dumps(candidate) + "\n")
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
findings_path = scan_dir / "findings.json"
|
||||
findings = json.loads(findings_path.read_text())
|
||||
findings["findings"][0]["provenance"].update(
|
||||
candidateId=candidate["candidate_id"], candidateReopened=reopened
|
||||
)
|
||||
findings_path.write_text(json.dumps(findings))
|
||||
write_candidates(ledger, candidate)
|
||||
write_budget_contract(scan_dir, scan_id, target)
|
||||
with edit_findings(scan_dir) as findings:
|
||||
findings[0]["provenance"].update(
|
||||
candidateId=candidate["candidate_id"], candidateReopened=reopened
|
||||
)
|
||||
surface = {
|
||||
"id": "candidate-review",
|
||||
"candidateId": candidate["candidate_id"],
|
||||
@@ -119,9 +176,7 @@ def test_budget_completion_uses_current_candidate_state_after_finding_reopens(
|
||||
surfaces=[surface, other_surface],
|
||||
deferred=[pending, other_pending],
|
||||
)
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
|
||||
completed = complete_budget_scan(state_dir, scan_id)["scan"]
|
||||
completed = complete_with_coverage(state_dir, scan_id, scan_dir, coverage)["scan"]
|
||||
|
||||
saved = read_review_state(state_dir, scan_dir)
|
||||
still_pending = expected_disposition == "needs_follow_up"
|
||||
@@ -160,17 +215,13 @@ def test_budget_exhaustion_reconciles_saved_candidate_rows_without_losing_other_
|
||||
if decision in {"reported", "other-owner", "existing-terminal"}
|
||||
else decision
|
||||
}
|
||||
ledger.write_text(json.dumps(candidate) + "\n")
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
write_candidates(ledger, candidate)
|
||||
write_budget_contract(scan_dir, scan_id, target)
|
||||
if decision in {"reported", "other-owner"}:
|
||||
findings_path = scan_dir / "findings.json"
|
||||
findings = json.loads(findings_path.read_text())
|
||||
findings["findings"][0]["provenance"]["candidateId"] = candidate["candidate_id"]
|
||||
if decision == "other-owner":
|
||||
findings["findings"][0]["provenance"]["sourceWorkerId"] = "worker-other"
|
||||
findings_path.write_text(json.dumps(findings))
|
||||
with edit_findings(scan_dir) as findings:
|
||||
findings[0]["provenance"]["candidateId"] = candidate["candidate_id"]
|
||||
if decision == "other-owner":
|
||||
findings[0]["provenance"]["sourceWorkerId"] = "worker-other"
|
||||
surface = {
|
||||
"id": "candidate-candidate-1",
|
||||
"candidateId": candidate["candidate_id"],
|
||||
@@ -214,9 +265,7 @@ def test_budget_exhaustion_reconciles_saved_candidate_rows_without_losing_other_
|
||||
generic,
|
||||
independent,
|
||||
]
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
|
||||
completed = complete_budget_scan(state_dir, scan_id)["scan"]
|
||||
completed = complete_with_coverage(state_dir, scan_id, scan_dir, coverage)["scan"]
|
||||
|
||||
preserved = read_review_state(state_dir, scan_dir)
|
||||
assert generic in preserved["deferred"]
|
||||
@@ -258,20 +307,16 @@ def test_budget_exhaustion_retains_original_deferred_finding_evidence(
|
||||
state_dir, target, scan_dir, scan_id, ledger = budget_scan_fixture(tmp_path)
|
||||
candidate = json.loads(ledger.read_text())
|
||||
candidate["validation"] = {"disposition": "reportable" if decision == "reported" else decision}
|
||||
ledger.write_text(json.dumps(candidate) + "\n")
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
findings_path = scan_dir / "findings.json"
|
||||
findings = json.loads(findings_path.read_text())
|
||||
original = dict(findings["findings"][0])
|
||||
original["summary"] = "Original detailed finding evidence from the deferred review."
|
||||
original["evidence"] = {"context": "Additional synthetic source review evidence."}
|
||||
if decision == "reported":
|
||||
findings["findings"][0]["provenance"]["candidateId"] = candidate["candidate_id"]
|
||||
else:
|
||||
findings["findings"] = []
|
||||
findings_path.write_text(json.dumps(findings))
|
||||
write_candidates(ledger, candidate)
|
||||
write_budget_contract(scan_dir, scan_id, target)
|
||||
with edit_findings(scan_dir) as findings:
|
||||
original = dict(findings[0])
|
||||
original["summary"] = "Original detailed finding evidence from the deferred review."
|
||||
original["evidence"] = {"context": "Additional synthetic source review evidence."}
|
||||
if decision == "reported":
|
||||
findings[0]["provenance"]["candidateId"] = candidate["candidate_id"]
|
||||
else:
|
||||
findings.clear()
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
coverage["deferred"] = [
|
||||
{
|
||||
@@ -286,7 +331,7 @@ def test_budget_exhaustion_retains_original_deferred_finding_evidence(
|
||||
|
||||
if newer_phase:
|
||||
candidate["validation"]["counterevidence_or_proof_gap"] = "Later review resolved the gap."
|
||||
ledger.write_text(json.dumps(candidate) + "\n")
|
||||
write_candidates(ledger, candidate)
|
||||
completed = complete_budget_scan(state_dir, scan_id)["scan"]
|
||||
|
||||
assert completed["progress"]["status"] == "complete"
|
||||
@@ -312,10 +357,8 @@ def test_budget_exhaustion_preserves_shared_reported_surface(tmp_path: Path, dec
|
||||
state_dir, target, scan_dir, scan_id, ledger = budget_scan_fixture(tmp_path)
|
||||
candidate = json.loads(ledger.read_text())
|
||||
candidate["validation"] = {"disposition": decision}
|
||||
ledger.write_text(json.dumps(candidate) + "\n")
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
write_candidates(ledger, candidate)
|
||||
write_budget_contract(scan_dir, scan_id, target)
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
shared = {
|
||||
"id": "shared-reported",
|
||||
@@ -326,9 +369,7 @@ def test_budget_exhaustion_preserves_shared_reported_surface(tmp_path: Path, dec
|
||||
"receiptRefs": [],
|
||||
}
|
||||
coverage.update(surfaces=[shared], deferred=[])
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
|
||||
completed = complete_budget_scan(state_dir, scan_id)["scan"]
|
||||
completed = complete_with_coverage(state_dir, scan_id, scan_dir, coverage)["scan"]
|
||||
|
||||
assert completed["findingCount"] == 1
|
||||
preserved = read_review_state(state_dir, scan_dir)
|
||||
@@ -350,15 +391,11 @@ def test_budget_exhaustion_keeps_failure_recovery_for_malformed_coverage(
|
||||
tmp_path: Path, malformed: dict[str, Any]
|
||||
) -> None:
|
||||
state_dir, target, scan_dir, scan_id, _ = budget_scan_fixture(tmp_path)
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
write_budget_contract(scan_dir, scan_id, target)
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
invalid = {"id": "malformed-review", "reason": "Unrelated saved review.", **malformed}
|
||||
coverage["deferred"] = [invalid]
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
|
||||
result = complete_budget_scan(state_dir, scan_id, check=False)
|
||||
result = complete_with_coverage(state_dir, scan_id, scan_dir, coverage, check=False)
|
||||
|
||||
assert result["returncode"] != 0
|
||||
scan = run_workbench(state_dir, "get-scan", "--scan-id", scan_id)["scan"]
|
||||
@@ -373,9 +410,7 @@ def test_budget_exhaustion_preserves_structured_exclusion_extensions(
|
||||
tmp_path: Path, disposition: Any
|
||||
) -> None:
|
||||
state_dir, target, scan_dir, scan_id, _ = budget_scan_fixture(tmp_path, candidates=[])
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
write_budget_contract(scan_dir, scan_id, target)
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
exclusion = {
|
||||
"pattern": "synthetic-exclusion/**",
|
||||
@@ -383,9 +418,7 @@ def test_budget_exhaustion_preserves_structured_exclusion_extensions(
|
||||
"disposition": disposition,
|
||||
}
|
||||
coverage["explicitExclusions"] = [exclusion]
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
|
||||
completed = complete_budget_scan(state_dir, scan_id)["scan"]
|
||||
completed = complete_with_coverage(state_dir, scan_id, scan_dir, coverage)["scan"]
|
||||
|
||||
assert completed["progress"]["status"] == "complete"
|
||||
assert completed["findingCount"] == 1
|
||||
@@ -398,9 +431,7 @@ def test_budget_exhaustion_retains_ledger_candidate_when_recovering_nonobject_su
|
||||
) -> None:
|
||||
state_dir, target, scan_dir, scan_id, ledger = budget_scan_fixture(tmp_path)
|
||||
candidate = json.loads(ledger.read_text())
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
write_budget_contract(scan_dir, scan_id, target)
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
coverage["surfaces"].append(None)
|
||||
generic = {
|
||||
@@ -409,9 +440,7 @@ def test_budget_exhaustion_retains_ledger_candidate_when_recovering_nonobject_su
|
||||
"surfaceIds": [coverage["surfaces"][0]["id"]],
|
||||
}
|
||||
coverage["deferred"] = [generic]
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
|
||||
result = complete_budget_scan(state_dir, scan_id, check=False)
|
||||
result = complete_with_coverage(state_dir, scan_id, scan_dir, coverage, check=False)
|
||||
|
||||
assert result["returncode"] != 0
|
||||
scan = run_workbench(state_dir, "get-scan", "--scan-id", scan_id)["scan"]
|
||||
@@ -432,14 +461,8 @@ def test_budget_completion_links_existing_pending_candidate_to_follow_up_surface
|
||||
) -> None:
|
||||
state_dir, target, scan_dir, scan_id, ledger = budget_scan_fixture(tmp_path)
|
||||
candidate = {**json.loads(ledger.read_text()), "validation": {"disposition": "deferred"}}
|
||||
ledger.write_text(json.dumps(candidate) + "\n")
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
findings_path = scan_dir / "findings.json"
|
||||
findings = json.loads(findings_path.read_text())
|
||||
findings["findings"] = []
|
||||
findings_path.write_text(json.dumps(findings))
|
||||
write_candidates(ledger, candidate)
|
||||
write_empty_budget_contract(scan_dir, scan_id, target)
|
||||
pending = {
|
||||
"id": "authored-proof-gap",
|
||||
"candidateId": candidate["candidate_id"],
|
||||
@@ -475,9 +498,7 @@ def test_budget_completion_links_existing_pending_candidate_to_follow_up_surface
|
||||
)
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
coverage.update(completeness="partial", surfaces=surfaces, deferred=[pending, generic])
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
|
||||
completed = complete_budget_scan(state_dir, scan_id)["scan"]
|
||||
completed = complete_with_coverage(state_dir, scan_id, scan_dir, coverage)["scan"]
|
||||
|
||||
saved = read_review_state(state_dir, scan_dir)
|
||||
assert completed["progress"]["status"] == "complete"
|
||||
@@ -558,9 +579,7 @@ def test_budget_exhaustion_retains_candidate_when_saved_surface_has_no_usable_id
|
||||
) -> None:
|
||||
state_dir, target, scan_dir, scan_id, ledger = budget_scan_fixture(tmp_path)
|
||||
candidate = json.loads(ledger.read_text())
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
write_budget_contract(scan_dir, scan_id, target)
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
coverage["surfaces"] = [
|
||||
{
|
||||
@@ -573,9 +592,7 @@ def test_budget_exhaustion_retains_candidate_when_saved_surface_has_no_usable_id
|
||||
}
|
||||
]
|
||||
coverage["deferred"] = []
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
|
||||
result = complete_budget_scan(state_dir, scan_id, check=False)
|
||||
result = complete_with_coverage(state_dir, scan_id, scan_dir, coverage, check=False)
|
||||
|
||||
assert result["returncode"] != 0
|
||||
scan = run_workbench(state_dir, "get-scan", "--scan-id", scan_id)["scan"]
|
||||
@@ -596,18 +613,14 @@ def test_budget_exhaustion_resolves_candidates_only_with_recoverable_findings(
|
||||
) -> None:
|
||||
state_dir, target, scan_dir, scan_id, ledger = budget_scan_fixture(tmp_path)
|
||||
candidate = json.loads(ledger.read_text())
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
findings_path = scan_dir / "findings.json"
|
||||
findings = json.loads(findings_path.read_text())
|
||||
finding = findings["findings"][0]
|
||||
finding["provenance"]["candidateId"] = candidate["candidate_id"]
|
||||
if missing_rule_id:
|
||||
finding.pop("ruleId")
|
||||
else:
|
||||
finding["ruleId"] = "Synthetic Candidate Review"
|
||||
findings_path.write_text(json.dumps(findings))
|
||||
write_budget_contract(scan_dir, scan_id, target)
|
||||
with edit_findings(scan_dir) as findings:
|
||||
finding = findings[0]
|
||||
finding["provenance"]["candidateId"] = candidate["candidate_id"]
|
||||
if missing_rule_id:
|
||||
finding.pop("ruleId")
|
||||
else:
|
||||
finding["ruleId"] = "Synthetic Candidate Review"
|
||||
pending = {
|
||||
"id": "saved-candidate-review",
|
||||
"candidateId": candidate["candidate_id"],
|
||||
@@ -616,9 +629,7 @@ def test_budget_exhaustion_resolves_candidates_only_with_recoverable_findings(
|
||||
}
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
coverage["deferred"] = [pending]
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
|
||||
result = complete_budget_scan(state_dir, scan_id, check=False)
|
||||
result = complete_with_coverage(state_dir, scan_id, scan_dir, coverage, check=False)
|
||||
|
||||
assert result["returncode"] != 0
|
||||
assert "invalid findings" in result["stderr"]
|
||||
@@ -652,7 +663,7 @@ def test_budget_exhaustion_resolves_candidates_only_with_recoverable_findings(
|
||||
row.get("candidateId") == candidate["candidate_id"] for row in recovered["deferred"]
|
||||
)
|
||||
assert (
|
||||
json.loads(findings_path.read_text())["findings"][0]["ruleId"]
|
||||
json.loads((scan_dir / "findings.json").read_text())["findings"][0]["ruleId"]
|
||||
== "synthetic-candidate-review"
|
||||
)
|
||||
assert json.loads((scan_dir / "scan-manifest.json").read_text())["scan"]["sealedAt"]
|
||||
@@ -675,15 +686,11 @@ def test_budget_exhaustion_preserves_authored_terminal_decisions(
|
||||
state_dir, target, scan_dir, scan_id, ledger = budget_scan_fixture(tmp_path)
|
||||
candidate = json.loads(ledger.read_text())
|
||||
candidate["validation"] = {"disposition": ledger_disposition}
|
||||
ledger.write_text(json.dumps(candidate) + "\n")
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
write_candidates(ledger, candidate)
|
||||
write_budget_contract(scan_dir, scan_id, target)
|
||||
if saved_kind == "finding":
|
||||
findings_path = scan_dir / "findings.json"
|
||||
findings = json.loads(findings_path.read_text())
|
||||
findings["findings"][0]["provenance"]["candidateId"] = candidate["candidate_id"]
|
||||
findings_path.write_text(json.dumps(findings))
|
||||
with edit_findings(scan_dir) as findings:
|
||||
findings[0]["provenance"]["candidateId"] = candidate["candidate_id"]
|
||||
pending_surface = {
|
||||
"id": "pending-review",
|
||||
"candidateId": candidate["candidate_id"],
|
||||
@@ -731,9 +738,7 @@ def test_budget_exhaustion_preserves_authored_terminal_decisions(
|
||||
"surfaceIds": [pending_surface["id"]],
|
||||
}
|
||||
]
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
|
||||
completed = complete_budget_scan(state_dir, scan_id)["scan"]
|
||||
completed = complete_with_coverage(state_dir, scan_id, scan_dir, coverage)["scan"]
|
||||
|
||||
assert completed["progress"]["status"] == "complete"
|
||||
assert completed["progress"]["candidates"]["unresolved"] == 0
|
||||
@@ -776,34 +781,32 @@ def test_budget_exhaustion_refreshes_generated_terminal_draft_after_resume(
|
||||
original["context"] = "Retained discovery context."
|
||||
run_workbench(state_dir, "set-scan-thread", "--scan-id", scan_id, "--thread-id", "sdk-thread")
|
||||
# Leave the real budget writer's output unsealed, as when completion is interrupted.
|
||||
with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
|
||||
connection.row_factory = sqlite3.Row
|
||||
scan = connection.execute("SELECT * FROM scans WHERE id = ?", (scan_id,)).fetchone()
|
||||
scan = persisted_scan(state_dir, scan_id)
|
||||
budget_draft(scan, scan_dir, [original], "Cost limit reached.")
|
||||
if started_pending:
|
||||
assert (
|
||||
run_workbench(state_dir, "get-scan", "--scan-id", scan_id)["scan"]["progress"][
|
||||
"candidates"
|
||||
]["unresolved"]
|
||||
== 1
|
||||
)
|
||||
assert (
|
||||
run_workbench(state_dir, "get-cli-scan-resume", "--scan-id", scan_id)["scanId"]
|
||||
== scan_id
|
||||
)
|
||||
original = {
|
||||
**original,
|
||||
"summary": "Updated terminal review",
|
||||
"evidence": "Updated terminal evidence.",
|
||||
"validation": {"disposition": "suppressed"},
|
||||
}
|
||||
budget_draft(scan, scan_dir, [original], "Cost limit reached.")
|
||||
if started_pending:
|
||||
assert (
|
||||
run_workbench(state_dir, "get-scan", "--scan-id", scan_id)["scan"]["progress"][
|
||||
"candidates"
|
||||
]["unresolved"]
|
||||
== 1
|
||||
)
|
||||
assert (
|
||||
run_workbench(state_dir, "get-cli-scan-resume", "--scan-id", scan_id)["scanId"]
|
||||
== scan_id
|
||||
)
|
||||
original = {
|
||||
**original,
|
||||
"summary": "Updated terminal review",
|
||||
"evidence": "Updated terminal evidence.",
|
||||
"validation": {"disposition": "suppressed"},
|
||||
}
|
||||
budget_draft(scan, scan_dir, [original], "Cost limit reached.")
|
||||
assert (
|
||||
run_workbench(state_dir, "get-scan", "--scan-id", scan_id)["scan"]["progress"][
|
||||
"candidates"
|
||||
]["unresolved"]
|
||||
== 0
|
||||
)
|
||||
assert (
|
||||
run_workbench(state_dir, "get-scan", "--scan-id", scan_id)["scan"]["progress"][
|
||||
"candidates"
|
||||
]["unresolved"]
|
||||
== 0
|
||||
)
|
||||
resumed = run_workbench(state_dir, "get-cli-scan-resume", "--scan-id", scan_id)
|
||||
assert resumed["scanId"] == scan_id
|
||||
assert "sealedProducerVersion" not in resumed
|
||||
@@ -817,7 +820,7 @@ def test_budget_exhaustion_refreshes_generated_terminal_draft_after_resume(
|
||||
candidate.pop("context")
|
||||
if decision == "reportable":
|
||||
candidate["attack_path"] = {"decision": "reportable"}
|
||||
ledger.write_text(json.dumps(candidate) + "\n")
|
||||
write_candidates(ledger, candidate)
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
surface = coverage["surfaces"][0]
|
||||
surface["reviewContext"] = "Keep this independent annotation."
|
||||
@@ -839,9 +842,7 @@ def test_budget_exhaustion_refreshes_generated_terminal_draft_after_resume(
|
||||
"surfaceIds": [surface["id"]],
|
||||
}
|
||||
)
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
|
||||
completed = complete_budget_scan(state_dir, scan_id)["scan"]
|
||||
completed = complete_with_coverage(state_dir, scan_id, scan_dir, coverage)["scan"]
|
||||
|
||||
assert completed["progress"]["status"] == "complete"
|
||||
assert completed["findingCount"] == 0
|
||||
@@ -879,10 +880,8 @@ def test_budget_exhaustion_refreshes_generated_pending_evidence_after_resume(
|
||||
"validation": {"disposition": "deferred"},
|
||||
}
|
||||
run_workbench(state_dir, "set-scan-thread", "--scan-id", scan_id, "--thread-id", "sdk-thread")
|
||||
with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
|
||||
connection.row_factory = sqlite3.Row
|
||||
scan = connection.execute("SELECT * FROM scans WHERE id = ?", (scan_id,)).fetchone()
|
||||
budget_draft(scan, scan_dir, [original], "Cost limit reached.")
|
||||
scan = persisted_scan(state_dir, scan_id)
|
||||
budget_draft(scan, scan_dir, [original], "Cost limit reached.")
|
||||
assert (
|
||||
run_workbench(state_dir, "get-cli-scan-resume", "--scan-id", scan_id)["scanId"] == scan_id
|
||||
)
|
||||
@@ -929,7 +928,7 @@ def test_budget_exhaustion_refreshes_generated_pending_evidence_after_resume(
|
||||
},
|
||||
}
|
||||
current.pop("context")
|
||||
ledger.write_text(json.dumps(current) + "\n")
|
||||
write_candidates(ledger, current)
|
||||
|
||||
completed = complete_budget_scan(state_dir, scan_id)["scan"]
|
||||
|
||||
@@ -1044,10 +1043,8 @@ def test_budget_completion_preserves_authored_partial_candidate_snapshot(
|
||||
) -> None:
|
||||
state_dir, _, scan_dir, scan_id, ledger = budget_scan_fixture(tmp_path)
|
||||
original = json.loads(ledger.read_text())
|
||||
with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
|
||||
connection.row_factory = sqlite3.Row
|
||||
scan = connection.execute("SELECT * FROM scans WHERE id = ?", (scan_id,)).fetchone()
|
||||
budget_draft(scan, scan_dir, [original], "Cost limit reached.")
|
||||
scan = persisted_scan(state_dir, scan_id)
|
||||
budget_draft(scan, scan_dir, [original], "Cost limit reached.")
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
partial = {field: original[field] for field in ("candidate_id", "summary", "evidence")}
|
||||
if snapshot == "authored-partial":
|
||||
@@ -1056,7 +1053,7 @@ def test_budget_completion_preserves_authored_partial_candidate_snapshot(
|
||||
coverage["deferred"][0]["reason"] = "Keep the authored proof gap."
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
current = {**original, "summary": "Updated review", "evidence": "Updated source evidence."}
|
||||
ledger.write_text(json.dumps(current) + "\n")
|
||||
write_candidates(ledger, current)
|
||||
|
||||
completed = complete_budget_scan(state_dir, scan_id)["scan"]
|
||||
|
||||
@@ -1090,10 +1087,8 @@ def test_budget_receipts_are_recovered_before_shared_surface_decisions(
|
||||
state, target, scan_dir, scan_id, ledger = budget_scan_fixture(tmp_path)
|
||||
candidate = json.loads(ledger.read_text())
|
||||
candidate["validation"] = {"disposition": "deferred"}
|
||||
ledger.write_text(json.dumps(candidate) + "\n")
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
write_candidates(ledger, candidate)
|
||||
write_budget_contract(scan_dir, scan_id, target)
|
||||
(scan_dir / "findings.json").write_text(json.dumps({"findings": []}))
|
||||
coverage = read_review_state(state, scan_dir)
|
||||
receipt_file = scan_dir / "artifacts/review/receipt.txt"
|
||||
@@ -1124,8 +1119,7 @@ def test_budget_receipts_are_recovered_before_shared_surface_decisions(
|
||||
"surfaceIds": [surface["id"]],
|
||||
}
|
||||
coverage.update(surfaces=[surface], deferred=[pending, generic])
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
completion = complete_budget_scan(state, scan_id, check=False)
|
||||
completion = complete_with_coverage(state, scan_id, scan_dir, coverage, check=False)
|
||||
if completion["returncode"]:
|
||||
run_workbench(
|
||||
state,
|
||||
@@ -1171,20 +1165,18 @@ def test_budget_generated_dedicated_surface_refresh_keeps_saved_reference_contex
|
||||
)
|
||||
original = {**json.loads(ledger.read_text()), "validation": {"disposition": "suppressed"}}
|
||||
run_workbench(state_dir, "set-scan-thread", "--scan-id", scan_id, "--thread-id", "sdk-thread")
|
||||
with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
|
||||
connection.row_factory = sqlite3.Row
|
||||
scan = connection.execute("SELECT * FROM scans WHERE id = ?", (scan_id,)).fetchone()
|
||||
budget_draft(scan, scan_dir, [original], "Cost limit reached.")
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
generic = {
|
||||
"id": "independent-review",
|
||||
"reason": "Keep independent unfinished work.",
|
||||
"surfaceIds": [coverage["surfaces"][0]["id"]],
|
||||
}
|
||||
coverage["deferred"].append(generic)
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
reopened = {**original, "validation": {"disposition": "deferred"}}
|
||||
budget_draft(scan, scan_dir, [reopened], "Cost limit reached.")
|
||||
scan = persisted_scan(state_dir, scan_id)
|
||||
budget_draft(scan, scan_dir, [original], "Cost limit reached.")
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
generic = {
|
||||
"id": "independent-review",
|
||||
"reason": "Keep independent unfinished work.",
|
||||
"surfaceIds": [coverage["surfaces"][0]["id"]],
|
||||
}
|
||||
coverage["deferred"].append(generic)
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
reopened = {**original, "validation": {"disposition": "deferred"}}
|
||||
budget_draft(scan, scan_dir, [reopened], "Cost limit reached.")
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
pending = next(
|
||||
row for row in coverage["deferred"] if row.get("candidateId") == original["candidate_id"]
|
||||
@@ -1219,7 +1211,7 @@ def test_budget_generated_dedicated_surface_refresh_keeps_saved_reference_contex
|
||||
"evidence": "Current reopened source evidence.",
|
||||
"locations": [{"path": "updated.py", "start_line": 1, "end_line": 1, "role": "sink"}],
|
||||
}
|
||||
ledger.write_text(json.dumps(current) + "\n")
|
||||
write_candidates(ledger, current)
|
||||
complete_budget_scan(state_dir, scan_id)
|
||||
published = read_review_state(state_dir, scan_dir)
|
||||
assert generic in published["deferred"]
|
||||
@@ -1240,41 +1232,20 @@ def test_budget_legacy_saved_pending_surface_refresh_uses_original_evidence(
|
||||
tmp_path: Path, edited_field: str | None, decision: str
|
||||
) -> None:
|
||||
state_dir, _, scan_dir, scan_id, ledger = budget_scan_fixture(tmp_path)
|
||||
original = {**json.loads(ledger.read_text()), "validation": {"disposition": "deferred"}}
|
||||
# This is the canonical row emitted by the previous budget writer.
|
||||
surface = {
|
||||
"id": f"candidate-{original['candidate_id']}",
|
||||
"label": original["summary"],
|
||||
"disposition": "needs_follow_up",
|
||||
"notes": original["evidence"],
|
||||
"receiptRefs": [],
|
||||
"annotation": "Keep this original annotation.",
|
||||
}
|
||||
original, surface, pending = legacy_pending_review(ledger)
|
||||
surface["annotation"] = "Keep this original annotation."
|
||||
if edited_field is not None:
|
||||
surface[edited_field] = "Authored review detail remains authoritative."
|
||||
saved_surface = dict(surface)
|
||||
pending = {
|
||||
"id": original["candidate_id"],
|
||||
"candidateId": original["candidate_id"],
|
||||
"reason": f"Validation was deferred because the scan reached its cost limit: {original['summary']}. Evidence: {original['evidence']}",
|
||||
"paths": [row["path"] for row in original["locations"]],
|
||||
"surfaceIds": [surface["id"]],
|
||||
}
|
||||
current = {
|
||||
**original,
|
||||
"summary": "Updated legacy review",
|
||||
"evidence": "Updated legacy source evidence.",
|
||||
"validation": {"disposition": decision},
|
||||
}
|
||||
ledger.write_text(json.dumps(current) + "\n")
|
||||
write_candidates(ledger, current)
|
||||
target = tmp_path / "target"
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
findings_path = scan_dir / "findings.json"
|
||||
findings = json.loads(findings_path.read_text())
|
||||
findings["findings"] = []
|
||||
findings_path.write_text(json.dumps(findings))
|
||||
write_empty_budget_contract(scan_dir, scan_id, target)
|
||||
manifest_path = scan_dir / "scan-manifest.json"
|
||||
manifest = json.loads(manifest_path.read_text())
|
||||
manifest["scan"].pop("sealedAt", None)
|
||||
@@ -1282,8 +1253,7 @@ def test_budget_legacy_saved_pending_surface_refresh_uses_original_evidence(
|
||||
manifest_path.write_text(json.dumps(manifest))
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
coverage.update(completeness="partial", surfaces=[surface], deferred=[pending])
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
complete_budget_scan(state_dir, scan_id)
|
||||
complete_with_coverage(state_dir, scan_id, scan_dir, coverage)
|
||||
published = read_review_state(state_dir, scan_dir)
|
||||
retained = next(row for row in published["surfaces"] if row["id"] == surface["id"])
|
||||
if edited_field is not None:
|
||||
@@ -1308,10 +1278,8 @@ def test_budget_terminal_refresh_archives_previous_candidate_snapshot(
|
||||
)
|
||||
original = {**json.loads(ledger.read_text()), "validation": {"disposition": "suppressed"}}
|
||||
run_workbench(state_dir, "set-scan-thread", "--scan-id", scan_id, "--thread-id", "sdk-thread")
|
||||
with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
|
||||
connection.row_factory = sqlite3.Row
|
||||
scan = connection.execute("SELECT * FROM scans WHERE id = ?", (scan_id,)).fetchone()
|
||||
budget_draft(scan, scan_dir, [original], "Cost limit reached.")
|
||||
scan = persisted_scan(state_dir, scan_id)
|
||||
budget_draft(scan, scan_dir, [original], "Cost limit reached.")
|
||||
current = {
|
||||
**original,
|
||||
"summary": "Current review",
|
||||
@@ -1335,7 +1303,7 @@ def test_budget_terminal_refresh_archives_previous_candidate_snapshot(
|
||||
}[authored]
|
||||
surface["candidate"] = original
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
ledger.write_text(json.dumps(current) + "\n")
|
||||
write_candidates(ledger, current)
|
||||
complete_budget_scan(state_dir, scan_id)
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
surface = next(
|
||||
@@ -1352,21 +1320,7 @@ def test_legacy_budget_pending_refresh_keeps_authored_fields(
|
||||
state_dir, target, scan_dir, scan_id, ledger = budget_scan_fixture(
|
||||
tmp_path, extra_files={"updated.py": "# updated source\n"}
|
||||
)
|
||||
original = {**json.loads(ledger.read_text()), "validation": {"disposition": "deferred"}}
|
||||
surface = {
|
||||
"id": f"candidate-{original['candidate_id']}",
|
||||
"label": original["summary"],
|
||||
"disposition": "needs_follow_up",
|
||||
"notes": original["evidence"],
|
||||
"receiptRefs": [],
|
||||
}
|
||||
pending = {
|
||||
"id": original["candidate_id"],
|
||||
"candidateId": original["candidate_id"],
|
||||
"reason": f"Validation was deferred because the scan reached its cost limit: {original['summary']}. Evidence: {original['evidence']}",
|
||||
"paths": [row["path"] for row in original["locations"]],
|
||||
"surfaceIds": [surface["id"]],
|
||||
}
|
||||
original, surface, pending = legacy_pending_review(ledger)
|
||||
if edited_field == "malformed_paths":
|
||||
pending["paths"] = [{}]
|
||||
elif edited_field is not None:
|
||||
@@ -1374,13 +1328,7 @@ def test_legacy_budget_pending_refresh_keeps_authored_fields(
|
||||
"Authored reason." if edited_field == "reason" else ["app.py", "authored.py"]
|
||||
)
|
||||
saved_pending = copy.deepcopy(pending)
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
findings_path = scan_dir / "findings.json"
|
||||
findings = json.loads(findings_path.read_text())
|
||||
findings["findings"] = []
|
||||
findings_path.write_text(json.dumps(findings))
|
||||
write_empty_budget_contract(scan_dir, scan_id, target)
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
coverage.update(completeness="partial", surfaces=[surface], deferred=[pending])
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
@@ -1390,7 +1338,7 @@ def test_legacy_budget_pending_refresh_keeps_authored_fields(
|
||||
"evidence": "Current unresolved evidence.",
|
||||
"locations": [{"path": "updated.py", "start_line": 1, "end_line": 1, "role": "sink"}],
|
||||
}
|
||||
ledger.write_text(json.dumps(current) + "\n")
|
||||
write_candidates(ledger, current)
|
||||
if edited_field == "malformed_paths":
|
||||
result = complete_budget_scan(state_dir, scan_id, check=False)
|
||||
assert result["returncode"] != 0
|
||||
@@ -1420,21 +1368,14 @@ def test_budget_candidate_allocation_preserves_generic_closure(
|
||||
) -> None:
|
||||
state_dir, target, scan_dir, scan_id, ledger = budget_scan_fixture(tmp_path)
|
||||
candidate = json.loads(ledger.read_text())
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
findings_path = scan_dir / "findings.json"
|
||||
findings = json.loads(findings_path.read_text())
|
||||
findings["findings"] = []
|
||||
findings_path.write_text(json.dumps(findings))
|
||||
write_empty_budget_contract(scan_dir, scan_id, target)
|
||||
coverage = read_review_state(state_dir, scan_dir)
|
||||
closure = {
|
||||
"id": candidate["candidate_id"] if collision else "general-review",
|
||||
"reason": "Independent generic review finished.",
|
||||
}
|
||||
coverage.update(surfaces=[], explicitExclusions=[], deferred=[], resolvedDeferred=[closure])
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
complete_budget_scan(state_dir, scan_id)
|
||||
complete_with_coverage(state_dir, scan_id, scan_dir, coverage)
|
||||
saved = read_review_state(state_dir, scan_dir)
|
||||
assert saved["resolvedDeferred"] == [closure]
|
||||
pending = [
|
||||
@@ -1456,18 +1397,14 @@ def test_public_budget_completion_keeps_receipt_reopened_work(
|
||||
"disposition": decision,
|
||||
"counterevidence_or_proof_gap": "Saved terminal decision.",
|
||||
}
|
||||
ledger.write_text(json.dumps(candidate) + "\n")
|
||||
write_candidates(ledger, candidate)
|
||||
original_ledger = ledger.read_bytes()
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
findings_path = scan_dir / "findings.json"
|
||||
findings = json.loads(findings_path.read_text())
|
||||
if receipt == "reported":
|
||||
findings["findings"][0]["provenance"]["candidateId"] = candidate["candidate_id"]
|
||||
else:
|
||||
findings["findings"] = []
|
||||
findings_path.write_text(json.dumps(findings))
|
||||
write_budget_contract(scan_dir, scan_id, target)
|
||||
with edit_findings(scan_dir) as findings:
|
||||
if receipt == "reported":
|
||||
findings[0]["provenance"]["candidateId"] = candidate["candidate_id"]
|
||||
else:
|
||||
findings.clear()
|
||||
path = scan_dir / "artifacts/proof/decision.txt"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("Synthetic original decision evidence.\n")
|
||||
@@ -1492,16 +1429,9 @@ def test_public_budget_completion_keeps_receipt_reopened_work(
|
||||
],
|
||||
deferred=[],
|
||||
)
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
if modern:
|
||||
with sqlite3.connect(state / "workbench.sqlite3") as connection:
|
||||
connection.execute(
|
||||
"UPDATE deep_scan_runs SET manifest_path = ? WHERE scan_id = ?",
|
||||
(str(scan_dir / "scan-manifest.json"), scan_id),
|
||||
)
|
||||
completed = complete_budget_scan(state, scan_id)["scan"]
|
||||
completed = complete_with_coverage(state, scan_id, scan_dir, coverage, modern=modern)["scan"]
|
||||
saved = read_review_state(state, scan_dir)
|
||||
active = json.loads(findings_path.read_text())["findings"]
|
||||
active = json.loads((scan_dir / "findings.json").read_text())["findings"]
|
||||
assert len(active) == int(receipt == "reported")
|
||||
assert completed["progress"]["candidates"]["unresolved"] == int(receipt == "missing")
|
||||
if receipt == "missing":
|
||||
@@ -1534,16 +1464,12 @@ def test_public_budget_dismissal_archives_reopened_findings(
|
||||
candidate["validation"]["counterevidence_or_proof_gap"] = (
|
||||
"New independent terminal evidence."
|
||||
)
|
||||
ledger.write_text(json.dumps(candidate) + "\n")
|
||||
write_candidates(ledger, candidate)
|
||||
original_ledger = ledger.read_bytes()
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
findings_path = scan_dir / "findings.json"
|
||||
findings = json.loads(findings_path.read_text())
|
||||
old = findings["findings"][0]
|
||||
old["provenance"].update(candidateId=candidate["candidate_id"], candidateReopened=True)
|
||||
findings_path.write_text(json.dumps(findings))
|
||||
write_budget_contract(scan_dir, scan_id, target)
|
||||
with edit_findings(scan_dir) as findings:
|
||||
old = findings[0]
|
||||
old["provenance"].update(candidateId=candidate["candidate_id"], candidateReopened=True)
|
||||
coverage = read_review_state(state, scan_dir)
|
||||
coverage.update(
|
||||
completeness="partial",
|
||||
@@ -1566,16 +1492,9 @@ def test_public_budget_dismissal_archives_reopened_findings(
|
||||
}
|
||||
],
|
||||
)
|
||||
write_provisional_review_state(scan_dir, coverage)
|
||||
if modern:
|
||||
with sqlite3.connect(state / "workbench.sqlite3") as connection:
|
||||
connection.execute(
|
||||
"UPDATE deep_scan_runs SET manifest_path = ? WHERE scan_id = ?",
|
||||
(str(scan_dir / "scan-manifest.json"), scan_id),
|
||||
)
|
||||
completed = complete_budget_scan(state, scan_id)["scan"]
|
||||
completed = complete_with_coverage(state, scan_id, scan_dir, coverage, modern=modern)["scan"]
|
||||
saved = read_review_state(state, scan_dir)
|
||||
active = json.loads(findings_path.read_text())["findings"]
|
||||
active = json.loads((scan_dir / "findings.json").read_text())["findings"]
|
||||
assert len(active) == int(modern)
|
||||
assert completed["progress"]["candidates"]["unresolved"] == int(modern)
|
||||
if modern:
|
||||
@@ -1608,10 +1527,8 @@ def test_public_budget_retry_retains_receipt_reopening(
|
||||
"disposition": decision,
|
||||
"counterevidence_or_proof_gap": "Saved terminal decision.",
|
||||
}
|
||||
ledger.write_text(json.dumps(candidate) + "\n")
|
||||
write_completed_contract(
|
||||
scan_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
|
||||
)
|
||||
write_candidates(ledger, candidate)
|
||||
write_budget_contract(scan_dir, scan_id, target)
|
||||
findings_path = scan_dir / "findings.json"
|
||||
findings = json.loads(findings_path.read_text())
|
||||
finding = findings["findings"][0]
|
||||
@@ -1671,7 +1588,7 @@ def test_public_budget_retry_retains_receipt_reopening(
|
||||
)
|
||||
if retry_evidence == "new-phase":
|
||||
candidate["validation"]["counterevidence_or_proof_gap"] = "New terminal evidence."
|
||||
ledger.write_text(json.dumps(candidate) + "\n")
|
||||
write_candidates(ledger, candidate)
|
||||
elif retry_evidence == "receipt":
|
||||
path = scan_dir / "artifacts/proof/replacement.txt"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -220,6 +220,45 @@ async function fixture(count = 1) {
|
||||
};
|
||||
}
|
||||
|
||||
async function candidateFixture(candidateId: string, sourceWorkerId?: string) {
|
||||
const f = await fixture();
|
||||
const { provenance } = f.findings.findings[0]!;
|
||||
provenance["candidateId"] = candidateId;
|
||||
if (sourceWorkerId !== undefined)
|
||||
provenance["sourceWorkerId"] = sourceWorkerId;
|
||||
await save(join(f.scanDir, "findings.json"), f.findings);
|
||||
const coverage = await json<CoverageDocument>(
|
||||
join(f.scanDir, "coverage.json"),
|
||||
);
|
||||
return { f, coverage };
|
||||
}
|
||||
|
||||
async function validateCoverage(
|
||||
f: Awaited<ReturnType<typeof fixture>>,
|
||||
coverage: CoverageDocument,
|
||||
validation: CustomValidationResult,
|
||||
) {
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(validation),
|
||||
});
|
||||
return loadResult(f.scanDir);
|
||||
}
|
||||
|
||||
const dispositions = [
|
||||
"reportable",
|
||||
"deferred",
|
||||
"suppressed",
|
||||
"not_applicable",
|
||||
] as const;
|
||||
const surfaceDisposition = {
|
||||
reportable: "reported",
|
||||
deferred: "needs_follow_up",
|
||||
suppressed: "rejected",
|
||||
not_applicable: "not_applicable",
|
||||
} as const;
|
||||
|
||||
async function* responseEvents(
|
||||
value: unknown,
|
||||
activity?: string,
|
||||
@@ -242,13 +281,9 @@ for (const section of ["surfaces", "explicitExclusions"] as const) {
|
||||
test.each(["sourceWorkerId", "workerId"])(
|
||||
`current custom validation replaces ${section}/${disposition}/${sameOwner ? "same" : "other"} owner decisions (%s)`,
|
||||
async (ownerField) => {
|
||||
const f = await fixture();
|
||||
const finding = f.findings.findings[0]!;
|
||||
finding.provenance["candidateId"] = "validated-candidate";
|
||||
finding.provenance["sourceWorkerId"] = "worker-current";
|
||||
await save(join(f.scanDir, "findings.json"), f.findings);
|
||||
const coverage = await json<CoverageDocument>(
|
||||
join(f.scanDir, "coverage.json"),
|
||||
const { f, coverage } = await candidateFixture(
|
||||
"validated-candidate",
|
||||
"worker-current",
|
||||
);
|
||||
const previous = {
|
||||
id: "older-decision",
|
||||
@@ -262,12 +297,7 @@ for (const section of ["surfaces", "explicitExclusions"] as const) {
|
||||
receiptRefs: [],
|
||||
};
|
||||
coverage[section].push(previous);
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result("deferred")),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(f, coverage, result("deferred"));
|
||||
expect(saved.unresolvedCandidates).toHaveLength(1);
|
||||
expect(saved.unresolvedCandidates[0]!.candidateId).toBe(
|
||||
"validated-candidate",
|
||||
@@ -286,20 +316,9 @@ for (const section of ["surfaces", "explicitExclusions"] as const) {
|
||||
}
|
||||
}
|
||||
|
||||
for (const disposition of [
|
||||
"reportable",
|
||||
"deferred",
|
||||
"suppressed",
|
||||
"not_applicable",
|
||||
] as const) {
|
||||
for (const disposition of dispositions) {
|
||||
test(`independent shared surface candidate survives custom ${disposition}`, async () => {
|
||||
const f = await fixture();
|
||||
f.findings.findings[0]!.provenance["candidateId"] = "validated-b";
|
||||
f.findings.findings[0]!.provenance["sourceWorkerId"] = "worker-b";
|
||||
await save(join(f.scanDir, "findings.json"), f.findings);
|
||||
const coverage = await json<CoverageDocument>(
|
||||
join(f.scanDir, "coverage.json"),
|
||||
);
|
||||
const { f, coverage } = await candidateFixture("validated-b", "worker-b");
|
||||
coverage.surfaces[0]!.candidateId = "independent-a";
|
||||
coverage.surfaces[0]!["sourceWorkerId"] = "worker-a";
|
||||
const independent = {
|
||||
@@ -311,23 +330,12 @@ for (const disposition of [
|
||||
};
|
||||
coverage["completeness"] = "partial";
|
||||
coverage.deferred = [independent];
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result(disposition)),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(f, coverage, result(disposition));
|
||||
expect(saved.unresolvedCandidates).toContainEqual(independent);
|
||||
});
|
||||
|
||||
test(`saved custom validation evidence survives ${disposition}`, async () => {
|
||||
const f = await fixture();
|
||||
const finding = f.findings.findings[0]!;
|
||||
finding.provenance["candidateId"] = "saved-candidate";
|
||||
await save(join(f.scanDir, "findings.json"), f.findings);
|
||||
const coverage = await json<CoverageDocument>(
|
||||
join(f.scanDir, "coverage.json"),
|
||||
);
|
||||
const { f, coverage } = await candidateFixture("saved-candidate");
|
||||
const previous = [1, 2].map((index) => ({
|
||||
id: `saved-review-${index}`,
|
||||
candidateId: "saved-candidate",
|
||||
@@ -338,18 +346,13 @@ for (const disposition of [
|
||||
evidence: `Original source evidence ${index}.`,
|
||||
},
|
||||
finding: {
|
||||
...structuredClone(finding),
|
||||
...structuredClone(f.findings.findings[0]!),
|
||||
title: `Earlier finding ${index}`,
|
||||
},
|
||||
}));
|
||||
coverage["completeness"] = "partial";
|
||||
coverage.deferred = previous;
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result(disposition)),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(f, coverage, result(disposition));
|
||||
const current =
|
||||
disposition === "reportable"
|
||||
? saved.findings.findings[0]
|
||||
@@ -440,12 +443,7 @@ describe("custom validation", () => {
|
||||
{ ...old, id: "duplicate-checkpoint" },
|
||||
...unrelated,
|
||||
];
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result("deferred")),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(f, coverage, result("deferred"));
|
||||
expect(saved.unresolvedCandidateCount).toBe(2);
|
||||
expect(saved.reviewState.deferred).toEqual([
|
||||
...unrelated,
|
||||
@@ -510,15 +508,11 @@ describe("custom validation", () => {
|
||||
};
|
||||
coverage["completeness"] = "partial";
|
||||
coverage.deferred = [previous, unrelated];
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () =>
|
||||
JSON.stringify(
|
||||
shared ? result(disposition, "reportable") : result(disposition),
|
||||
),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(
|
||||
f,
|
||||
coverage,
|
||||
shared ? result(disposition, "reportable") : result(disposition),
|
||||
);
|
||||
expect(saved.findings.findings).toHaveLength(shared ? 1 : 0);
|
||||
expect(saved.reviewState.deferred).toEqual([unrelated]);
|
||||
expect(saved.unresolvedCandidateCount).toBe(1);
|
||||
@@ -621,12 +615,7 @@ describe("custom validation", () => {
|
||||
disposition: "needs_follow_up",
|
||||
receiptRefs: [],
|
||||
});
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result(disposition)),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(f, coverage, result(disposition));
|
||||
expect(saved.unresolvedCandidateCount).toBe(0);
|
||||
expect(saved.reviewState["completeness"]).toBe(undefined);
|
||||
expect(saved.reviewState["completenessBeforeCandidates"]).toBe(
|
||||
@@ -647,12 +636,11 @@ describe("custom validation", () => {
|
||||
join(f.scanDir, "coverage.json"),
|
||||
);
|
||||
coverage.surfaces = [{ ...coverage.surfaces[0]!, candidateId: "source-0" }];
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result("deferred", "reportable")),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(
|
||||
f,
|
||||
coverage,
|
||||
result("deferred", "reportable"),
|
||||
);
|
||||
expect(saved.findings.findings).toHaveLength(1);
|
||||
expect(saved.reviewState.surfaces[0]!.disposition).toBe("reported");
|
||||
expect(saved.unresolvedCandidateCount).toBe(1);
|
||||
@@ -688,15 +676,11 @@ describe("custom validation", () => {
|
||||
candidateId: `reviewer-attempt-1-candidate-${new Bun.CryptoHasher("sha256").update(priorId).digest("hex")}`,
|
||||
provenance: { workerId: "reviewer", attempt: 1, candidateId: priorId },
|
||||
});
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () =>
|
||||
JSON.stringify(
|
||||
result("reportable", "reportable", "reportable", "deferred"),
|
||||
),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(
|
||||
f,
|
||||
coverage,
|
||||
result("reportable", "reportable", "reportable", "deferred"),
|
||||
);
|
||||
expect(saved.unresolvedCandidateCount).toBe(1);
|
||||
expect(saved.unresolvedCandidates[0]).toMatchObject({
|
||||
id: "custom-validation-candidate-4-6",
|
||||
@@ -2182,21 +2166,12 @@ describe("custom validation", () => {
|
||||
const unexpectedValidation = rejecting("unexpected validation");
|
||||
|
||||
for (const prior of ["rejected", "not_applicable"] as const) {
|
||||
for (const disposition of [
|
||||
"reportable",
|
||||
"deferred",
|
||||
"suppressed",
|
||||
"not_applicable",
|
||||
] as const) {
|
||||
for (const disposition of dispositions) {
|
||||
for (const gap of ["generic", "other-worker", "none"] as const) {
|
||||
test(`unmapped terminal surface retains referenced evidence: ${prior}/${disposition}/${gap}`, async () => {
|
||||
const f = await fixture();
|
||||
const finding = f.findings.findings[0]!;
|
||||
finding.provenance["candidateId"] = "validated-candidate";
|
||||
finding.provenance["sourceWorkerId"] = "worker-current";
|
||||
await save(join(f.scanDir, "findings.json"), f.findings);
|
||||
const coverage = await json<CoverageDocument>(
|
||||
join(f.scanDir, "coverage.json"),
|
||||
const { f, coverage } = await candidateFixture(
|
||||
"validated-candidate",
|
||||
"worker-current",
|
||||
);
|
||||
const previous = {
|
||||
id: "saved-terminal-review",
|
||||
@@ -2222,12 +2197,7 @@ for (const prior of ["rejected", "not_applicable"] as const) {
|
||||
surfaceIds: [previous.id],
|
||||
};
|
||||
coverage.deferred = gap === "none" ? [] : [independent];
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result(disposition)),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(f, coverage, result(disposition));
|
||||
const reopened = saved.unresolvedCandidates.filter(
|
||||
(row) =>
|
||||
row.candidateId === "validated-candidate" &&
|
||||
@@ -2258,13 +2228,7 @@ for (const prior of ["rejected", "not_applicable"] as const) {
|
||||
["synthetic-worker"],
|
||||
]) {
|
||||
test(`structured exclusion owner remains independent: ${prior}/${disposition}/${Array.isArray(owner) ? "array" : "object"}`, async () => {
|
||||
const f = await fixture();
|
||||
f.findings.findings[0]!.provenance["candidateId"] =
|
||||
"validated-candidate";
|
||||
await save(join(f.scanDir, "findings.json"), f.findings);
|
||||
const coverage = await json<CoverageDocument>(
|
||||
join(f.scanDir, "coverage.json"),
|
||||
);
|
||||
const { f, coverage } = await candidateFixture("validated-candidate");
|
||||
const previous = {
|
||||
id: "independent-exclusion",
|
||||
candidateId: "validated-candidate",
|
||||
@@ -2275,34 +2239,20 @@ for (const prior of ["rejected", "not_applicable"] as const) {
|
||||
annotation: "Retain this authored annotation.",
|
||||
};
|
||||
coverage.explicitExclusions.push(previous);
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result(disposition)),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(f, coverage, result(disposition));
|
||||
expect(saved.reviewState.explicitExclusions).toContainEqual(previous);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const disposition of [
|
||||
"reportable",
|
||||
"deferred",
|
||||
"suppressed",
|
||||
"not_applicable",
|
||||
] as const) {
|
||||
for (const disposition of dispositions) {
|
||||
for (const sameOwner of [false, true]) {
|
||||
for (const shared of [false, true]) {
|
||||
test(`saved unmapped follow-up reconciles custom ${disposition}, sameOwner=${sameOwner}, shared=${shared}`, async () => {
|
||||
const f = await fixture();
|
||||
const finding = f.findings.findings[0]!;
|
||||
finding.provenance["candidateId"] = "validated-candidate";
|
||||
finding.provenance["sourceWorkerId"] = "worker-current";
|
||||
await save(join(f.scanDir, "findings.json"), f.findings);
|
||||
const coverage = await json<CoverageDocument>(
|
||||
join(f.scanDir, "coverage.json"),
|
||||
const { f, coverage } = await candidateFixture(
|
||||
"validated-candidate",
|
||||
"worker-current",
|
||||
);
|
||||
const previous = {
|
||||
id: "saved-follow-up",
|
||||
@@ -2331,12 +2281,7 @@ for (const disposition of [
|
||||
reason: "Independent work still needs this surface.",
|
||||
surfaceIds: [previous.id],
|
||||
});
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result(disposition)),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(f, coverage, result(disposition));
|
||||
const retained = saved.reviewState.surfaces.find(
|
||||
(row) => row.id === previous.id,
|
||||
)!;
|
||||
@@ -2345,13 +2290,7 @@ for (const disposition of [
|
||||
expect(retained.notes).toBe(previous.notes);
|
||||
const resolved = sameOwner && !shared && disposition !== "deferred";
|
||||
expect(retained.disposition).toBe(
|
||||
resolved
|
||||
? disposition === "reportable"
|
||||
? "reported"
|
||||
: disposition === "suppressed"
|
||||
? "rejected"
|
||||
: "not_applicable"
|
||||
: "needs_follow_up",
|
||||
resolved ? surfaceDisposition[disposition] : "needs_follow_up",
|
||||
);
|
||||
if (shared)
|
||||
expect(saved.reviewState.deferred).toContainEqual({
|
||||
@@ -2365,21 +2304,10 @@ for (const disposition of [
|
||||
}
|
||||
|
||||
for (const prior of ["rejected", "not_applicable"] as const) {
|
||||
for (const disposition of [
|
||||
"reportable",
|
||||
"deferred",
|
||||
"suppressed",
|
||||
"not_applicable",
|
||||
] as const) {
|
||||
for (const disposition of dispositions) {
|
||||
for (const sameCandidate of [true, false]) {
|
||||
test(`custom validation preserves shared terminal ${prior} after ${disposition}, sameCandidate=${sameCandidate}`, async () => {
|
||||
const f = await fixture();
|
||||
f.findings.findings[0]!.provenance["candidateId"] =
|
||||
"validated-candidate";
|
||||
await save(join(f.scanDir, "findings.json"), f.findings);
|
||||
const coverage = await json<CoverageDocument>(
|
||||
join(f.scanDir, "coverage.json"),
|
||||
);
|
||||
const { f, coverage } = await candidateFixture("validated-candidate");
|
||||
coverage.surfaces[0]!.candidateId = sameCandidate
|
||||
? "validated-candidate"
|
||||
: "independent-candidate";
|
||||
@@ -2394,12 +2322,7 @@ for (const prior of ["rejected", "not_applicable"] as const) {
|
||||
surfaceIds: [coverage.surfaces[0]!.id],
|
||||
},
|
||||
];
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result(disposition)),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(f, coverage, result(disposition));
|
||||
if (!sameCandidate) {
|
||||
const retained = saved.reviewState.surfaces.find(
|
||||
(row) =>
|
||||
@@ -2410,13 +2333,7 @@ for (const prior of ["rejected", "not_applicable"] as const) {
|
||||
expect(retained!["annotation"]).toBe("Saved terminal annotation.");
|
||||
} else {
|
||||
expect(saved.reviewState.surfaces[0]!.disposition).toBe(
|
||||
disposition === "reportable"
|
||||
? "reported"
|
||||
: disposition === "deferred"
|
||||
? "needs_follow_up"
|
||||
: disposition === "suppressed"
|
||||
? "rejected"
|
||||
: "not_applicable",
|
||||
surfaceDisposition[disposition],
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -2426,13 +2343,9 @@ for (const prior of ["rejected", "not_applicable"] as const) {
|
||||
|
||||
for (const mapped of [false, true]) {
|
||||
test(`repeated custom validation retains legacy-owned follow-up links, mapped=${mapped}`, async () => {
|
||||
const f = await fixture();
|
||||
const finding = f.findings.findings[0]!;
|
||||
finding.provenance["candidateId"] = "validated-candidate";
|
||||
finding.provenance["sourceWorkerId"] = "worker-current";
|
||||
await save(join(f.scanDir, "findings.json"), f.findings);
|
||||
const coverage = await json<CoverageDocument>(
|
||||
join(f.scanDir, "coverage.json"),
|
||||
const { f, coverage } = await candidateFixture(
|
||||
"validated-candidate",
|
||||
"worker-current",
|
||||
);
|
||||
const previous = {
|
||||
id: "saved-follow-up",
|
||||
@@ -2455,12 +2368,7 @@ for (const mapped of [false, true]) {
|
||||
surfaceIds: [previous.id],
|
||||
},
|
||||
];
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result("deferred")),
|
||||
});
|
||||
const pending = await loadResult(f.scanDir);
|
||||
const pending = await validateCoverage(f, coverage, result("deferred"));
|
||||
if (!mapped)
|
||||
expect(pending.reviewState.deferred[0]!.surfaceIds).toContain(
|
||||
previous.id,
|
||||
@@ -2489,19 +2397,11 @@ for (const mapped of [false, true]) {
|
||||
}
|
||||
|
||||
for (const owner of [{ worker: "historical-worker" }, ["historical-worker"]]) {
|
||||
for (const disposition of [
|
||||
"reportable",
|
||||
"deferred",
|
||||
"suppressed",
|
||||
"not_applicable",
|
||||
] as const) {
|
||||
for (const disposition of dispositions) {
|
||||
test(`historical structured deferred remains independent: ${Array.isArray(owner) ? "array" : "object"}/${disposition}`, async () => {
|
||||
const f = await fixture();
|
||||
f.findings.findings[0]!.provenance["candidateId"] = "validated-candidate";
|
||||
f.findings.findings[0]!.provenance["sourceWorkerId"] = "worker-current";
|
||||
await save(join(f.scanDir, "findings.json"), f.findings);
|
||||
const coverage = await json<CoverageDocument>(
|
||||
join(f.scanDir, "coverage.json"),
|
||||
const { f, coverage } = await candidateFixture(
|
||||
"validated-candidate",
|
||||
"worker-current",
|
||||
);
|
||||
const historical = {
|
||||
id: "historical-deferred",
|
||||
@@ -2513,12 +2413,7 @@ for (const owner of [{ worker: "historical-worker" }, ["historical-worker"]]) {
|
||||
};
|
||||
coverage.deferred = [historical];
|
||||
coverage["completeness"] = "partial";
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result(disposition)),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(f, coverage, result(disposition));
|
||||
expect(saved.reviewState.deferred).toContainEqual(historical);
|
||||
expect(saved.unresolvedCandidates).toHaveLength(
|
||||
disposition === "deferred" ? 1 : 0,
|
||||
@@ -2578,12 +2473,7 @@ for (const outcomes of [
|
||||
};
|
||||
if (independent) coverage.deferred.push(shared);
|
||||
coverage["completeness"] = "partial";
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result(...outcomes)),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(f, coverage, result(...outcomes));
|
||||
const historicalSurface = saved.reviewState.surfaces.find(
|
||||
(row) => row.id === historical.id,
|
||||
)!;
|
||||
@@ -2616,12 +2506,7 @@ for (const owner of [
|
||||
["historical-worker"],
|
||||
]) {
|
||||
for (const mapped of [false, true]) {
|
||||
for (const disposition of [
|
||||
"reportable",
|
||||
"deferred",
|
||||
"suppressed",
|
||||
"not_applicable",
|
||||
] as const) {
|
||||
for (const disposition of dispositions) {
|
||||
test(`historical follow-up owner remains independent: ${JSON.stringify(owner)}/${mapped}/${disposition}`, async () => {
|
||||
const f = await fixture();
|
||||
const finding = f.findings.findings[0]!;
|
||||
@@ -2647,12 +2532,7 @@ for (const owner of [
|
||||
};
|
||||
coverage.surfaces.push(historical);
|
||||
coverage["completeness"] = "partial";
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result(disposition)),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(f, coverage, result(disposition));
|
||||
const independent = !mapped && owner !== undefined;
|
||||
const retained = saved.reviewState.surfaces.find(
|
||||
(row) => row.id === historical.id,
|
||||
@@ -2679,20 +2559,9 @@ for (const owner of [
|
||||
}
|
||||
|
||||
for (const owner of [undefined, "", " ", "other-worker"]) {
|
||||
for (const disposition of [
|
||||
"reportable",
|
||||
"deferred",
|
||||
"suppressed",
|
||||
"not_applicable",
|
||||
] as const) {
|
||||
for (const disposition of dispositions) {
|
||||
test(`legacy linked follow-up uses effective owner: ${JSON.stringify(owner)}/${disposition}`, async () => {
|
||||
const f = await fixture();
|
||||
const finding = f.findings.findings[0]!;
|
||||
finding.provenance["candidateId"] = "validated-candidate";
|
||||
await save(join(f.scanDir, "findings.json"), f.findings);
|
||||
const coverage = await json<CoverageDocument>(
|
||||
join(f.scanDir, "coverage.json"),
|
||||
);
|
||||
const { f, coverage } = await candidateFixture("validated-candidate");
|
||||
const historical = {
|
||||
id: "legacy-linked-proof",
|
||||
...(owner === undefined ? {} : { sourceWorkerId: owner }),
|
||||
@@ -2712,12 +2581,7 @@ for (const owner of [undefined, "", " ", "other-worker"]) {
|
||||
surfaceIds: [historical.id],
|
||||
},
|
||||
];
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result(disposition)),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(f, coverage, result(disposition));
|
||||
const row = saved.reviewState.surfaces.find(
|
||||
(item) => item.id === historical.id,
|
||||
)!;
|
||||
@@ -2727,15 +2591,7 @@ for (const owner of [undefined, "", " ", "other-worker"]) {
|
||||
saved.reviewState.deferred.some((item) => item.id === "legacy-gap"),
|
||||
).toBe(true);
|
||||
} else {
|
||||
expect(row.disposition).toBe(
|
||||
disposition === "reportable"
|
||||
? "reported"
|
||||
: disposition === "deferred"
|
||||
? "needs_follow_up"
|
||||
: disposition === "suppressed"
|
||||
? "rejected"
|
||||
: "not_applicable",
|
||||
);
|
||||
expect(row.disposition).toBe(surfaceDisposition[disposition]);
|
||||
expect(
|
||||
saved.reviewState.deferred.some((item) => item.id === "legacy-gap"),
|
||||
).toBe(disposition === "deferred");
|
||||
@@ -2750,13 +2606,9 @@ for (const disposition of ["reportable", "suppressed"] as const) {
|
||||
for (const independent of [false, true]) {
|
||||
for (const linked of [false, true]) {
|
||||
test(`unique cross-owner historical follow-up ${disposition}/${independent}/${linked}`, async () => {
|
||||
const f = await fixture();
|
||||
const finding = f.findings.findings[0]!;
|
||||
finding.provenance["candidateId"] = "current-candidate";
|
||||
finding.provenance["sourceWorkerId"] = "worker-current";
|
||||
await save(join(f.scanDir, "findings.json"), f.findings);
|
||||
const coverage = await json<CoverageDocument>(
|
||||
join(f.scanDir, "coverage.json"),
|
||||
const { f, coverage } = await candidateFixture(
|
||||
"current-candidate",
|
||||
"worker-current",
|
||||
);
|
||||
const historical = {
|
||||
id: "historical-proof",
|
||||
@@ -2783,12 +2635,7 @@ for (const disposition of ["reportable", "suppressed"] as const) {
|
||||
surfaceIds: [historical.id],
|
||||
};
|
||||
if (independent) coverage.deferred.push(generic);
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result(disposition)),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(f, coverage, result(disposition));
|
||||
const surface = saved.reviewState.surfaces.find(
|
||||
(row) => row.id === historical.id,
|
||||
)!;
|
||||
@@ -2836,17 +2683,11 @@ for (const reassessed of [false, true]) {
|
||||
notes: "Original candidate B rejection evidence.",
|
||||
};
|
||||
coverage.surfaces[0] = previous;
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () =>
|
||||
JSON.stringify(
|
||||
reassessed
|
||||
? result("reportable", "deferred")
|
||||
: result("reportable"),
|
||||
),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(
|
||||
f,
|
||||
coverage,
|
||||
reassessed ? result("reportable", "deferred") : result("reportable"),
|
||||
);
|
||||
const old = saved.reviewState.surfaces.filter(
|
||||
(row) =>
|
||||
row.candidateId === "candidate-b" && row.disposition === "rejected",
|
||||
@@ -2887,12 +2728,11 @@ for (const section of ["surfaces", "explicitExclusions"] as const) {
|
||||
receiptRefs: [],
|
||||
};
|
||||
coverage[section].push(previous);
|
||||
await save(join(f.scanDir, "coverage.json"), coverage);
|
||||
await runCustomValidation({
|
||||
...f,
|
||||
run: async () => JSON.stringify(result("reportable", "suppressed")),
|
||||
});
|
||||
const saved = await loadResult(f.scanDir);
|
||||
const saved = await validateCoverage(
|
||||
f,
|
||||
coverage,
|
||||
result("reportable", "suppressed"),
|
||||
);
|
||||
expect(saved.findings.findings).toHaveLength(1);
|
||||
expect(saved.reviewState[section]).not.toContainEqual(previous);
|
||||
expect(
|
||||
|
||||
Reference in New Issue
Block a user