Merge main and retain validation for committed receipt metadata

This commit is contained in:
mldangelo-oai
2026-11-04 21:29:06 +00:00
34 changed files with 1208 additions and 376 deletions
@@ -2,7 +2,7 @@ name: Audit pnpm lockfiles
description: Check selected dependency trees locally against the vulnerability database.
inputs:
targets:
description: Space-separated workspaces to audit (mcp and/or evals).
description: Space-separated inventories to audit (mcp, evals, tokenizer).
required: true
runs:
using: composite
@@ -18,14 +18,17 @@ runs:
run: |
read -ra targets <<< "$TARGETS"
for target in "${targets[@]}"; do
echo "Auditing $target dependencies"
sbom="$RUNNER_TEMP/$target.cdx.json"
case "$target" in
mcp) scope=(--dir plugins/codex-security/mcp-app sbom --prod) ;;
evals) scope=(--dir evals/triage-finding sbom) ;;
mcp) pnpm --dir plugins/codex-security/mcp-app sbom --prod --lockfile-only --sbom-format cyclonedx > "$sbom" ;;
evals) pnpm --dir evals/triage-finding sbom --lockfile-only --sbom-format cyclonedx > "$sbom" ;;
tokenizer)
pnpm --dir sdk/typescript exec node scripts/build-embedding-tokenizer.mjs
sbom="sdk/typescript/dist/server/embedding-tokenizer.cdx.json"
;;
*) echo "Unknown audit target: $target" >&2; exit 1 ;;
esac
echo "Auditing $target lockfile"
sbom="$RUNNER_TEMP/$target.cdx.json"
pnpm "${scope[@]}" --lockfile-only --sbom-format cyclonedx > "$sbom"
trivy sbom --offline-scan --disable-telemetry --skip-version-check \
--exit-code 1 --severity HIGH,CRITICAL "$sbom"
done
+8 -2
View File
@@ -51,12 +51,18 @@ export function selectLockfileAudits(paths, { event, baseChanged }) {
baseChanged ||
paths.includes(".github/actions/audit-pnpm-lockfiles/action.yml")
)
return "mcp evals";
return "mcp evals tokenizer";
return [
["mcp", "plugins/codex-security/mcp-app/pnpm-lock.yaml"],
["evals", "evals/triage-finding/pnpm-lock.yaml"],
[
"tokenizer",
"sdk/typescript/pnpm-lock.yaml",
"sdk/typescript/src/server/embedding-tokenizer.ts",
"sdk/typescript/scripts/build-embedding-tokenizer.mjs",
],
]
.filter(([, lockfile]) => paths.includes(lockfile))
.filter(([, ...inputs]) => inputs.some((input) => paths.includes(input)))
.map(([target]) => target)
.join(" ");
}
+11 -5
View File
@@ -558,25 +558,31 @@ test("only an authenticated, successful classifier can propagate a source result
}
});
test("audits the changed lockfiles and checks both trees on full event runs", () => {
test("audits changed dependency inputs and checks every inventory on full event runs", () => {
const pr = { event: "pull_request" };
const mcp = "plugins/codex-security/mcp-app/pnpm-lock.yaml";
const evals = "evals/triage-finding/pnpm-lock.yaml";
assert.equal(selectLockfileAudits([mcp], pr), "mcp");
assert.equal(selectLockfileAudits([evals], pr), "evals");
assert.equal(selectLockfileAudits([mcp, evals], pr), "mcp evals");
assert.equal(selectLockfileAudits(["sdk/typescript/pnpm-lock.yaml"], pr), "");
for (const input of [
"sdk/typescript/pnpm-lock.yaml",
"sdk/typescript/scripts/build-embedding-tokenizer.mjs",
"sdk/typescript/src/server/embedding-tokenizer.ts",
])
assert.equal(selectLockfileAudits([input], pr), "tokenizer");
assert.equal(selectLockfileAudits(["README.md"], pr), "");
for (const event of ["schedule", "workflow_dispatch", "push"])
assert.equal(selectLockfileAudits([], { event }), "mcp evals");
assert.equal(selectLockfileAudits([], { event }), "mcp evals tokenizer");
assert.equal(
selectLockfileAudits([], { ...pr, baseChanged: true }),
"mcp evals",
"mcp evals tokenizer",
);
assert.equal(
selectLockfileAudits(
[".github/actions/audit-pnpm-lockfiles/action.yml"],
pr,
),
"mcp evals",
"mcp evals tokenizer",
);
});
+1 -1
View File
@@ -123,7 +123,7 @@ jobs:
run: pnpm --dir sdk/typescript run format
- name: Check MCP formatting
run: pnpm --dir plugins/codex-security/mcp-app exec prettier --check "**/*.{cjs,cts,js,jsx,mjs,mts,ts,tsx}"
- name: Audit changed MCP and eval lockfiles
- name: Audit changed dependency inventories
if: needs.classify-changes.outputs.audit-lockfiles != ''
uses: ./.github/actions/audit-pnpm-lockfiles
with:
+2 -2
View File
@@ -159,10 +159,10 @@ jobs:
name: Install ripgrep
run: .github/scripts/install-ripgrep.sh
- name: Audit bundled MCP production dependencies
- name: Audit bundled MCP and tokenizer dependencies
uses: ./.github/actions/audit-pnpm-lockfiles
with:
targets: mcp
targets: mcp tokenizer
- name: Audit production dependencies
run: sfw pnpm --dir sdk/typescript run audit:prod
+23 -17
View File
@@ -30,8 +30,10 @@ env:
jobs:
native:
if: inputs.compare-layouts && !inputs.native-artifacts-ready
if: ${{ !inputs.native-artifacts-ready }}
uses: ./.github/workflows/native-artifacts.yml
with:
reuse-verified: ${{ !inputs.compare-layouts }}
runner:
needs: native
@@ -97,9 +99,11 @@ jobs:
uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: "3.12"
- name: Prepare native runtime
- &download-native
name: Prepare native runtime
uses: ./.github/actions/download-native
- name: Set up TypeScript tools
- &set-up-plugin-tools
name: Set up TypeScript tools
uses: ./.github/actions/setup-tools
with:
cache-dependency-path: |
@@ -109,7 +113,8 @@ jobs:
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
with:
bun-version: "1.3.14"
- name: Install dependencies
- &install-plugin-dependencies
name: Install dependencies
shell: bash
run: |
pnpm --dir sdk/typescript install --frozen-lockfile
@@ -120,7 +125,8 @@ jobs:
id: windows-temp
shell: pwsh
run: ./sdk/typescript/scripts/prepare-windows-test-root.ps1
- name: Build bundled plugin
- &build-plugin
name: Build bundled plugin
run: pnpm --dir sdk/typescript run build:plugin
- name: Install ripgrep
if: runner.os == 'Linux'
@@ -144,8 +150,9 @@ jobs:
retention-days: 14
properties:
needs: native
if: ${{ !cancelled() && !inputs.compare-layouts && (inputs.native-artifacts-ready || needs.native.result == 'success') }}
name: ${{ matrix.os }} / rotating properties
if: ${{ !inputs.compare-layouts }}
runs-on: ${{ matrix.os }}
timeout-minutes: 20
env:
@@ -158,13 +165,11 @@ jobs:
os: [ubuntu-latest, macos-latest, windows-latest]
steps:
- *actions-checkout
- &set-up-sdk-tools
name: Set up TypeScript tools
uses: ./.github/actions/setup-tools
- *download-native
- *set-up-plugin-tools
- *set-up-bun
- &install-sdk-dependencies
name: Install dependencies
run: pnpm --dir sdk/typescript install --frozen-lockfile
- *install-plugin-dependencies
- *build-plugin
- *prepare-windows-test-root
- name: Test rotating properties
working-directory: sdk/typescript
@@ -172,9 +177,7 @@ jobs:
env: *test-temp
run: |
git grep -lzF 'support/property' -- 'tests-ts/*.test.ts' > "$RUNNER_TEMP/property-tests"
mkdir -p reports _bundled_plugin/examples
cp -R ../../plugins/codex-security/examples/completed-scan _bundled_plugin/examples/
cp -R ../../plugins/codex-security/schemas _bundled_plugin/
mkdir -p reports
xargs -0 bun test --timeout="$CODEX_SECURITY_TEST_TIMEOUT_MS" --seed="$CODEX_SECURITY_PROPERTY_SEED" --reporter=junit --reporter-outfile=reports/properties.xml < "$RUNNER_TEMP/property-tests"
- *upload-runner-report
@@ -185,8 +188,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- *actions-checkout
- *set-up-sdk-tools
- *install-sdk-dependencies
- name: Set up TypeScript tools
uses: ./.github/actions/setup-tools
- &install-sdk-dependencies
name: Install dependencies
run: pnpm --dir sdk/typescript install --frozen-lockfile
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: runner-*
+2
View File
@@ -63,6 +63,8 @@ jobs:
with:
node-version: "24.15.0"
package-manager-cache: false
- name: Test Wolfi dependency inventories
run: python3 -m unittest discover -s docker/wolfi/tests
- name: Exercise release staging on a known published scanner
id: known
shell: bash
+9
View File
@@ -38,6 +38,15 @@ def enrich(sbom, components):
"referenceLocator": purl}],
})
for i, item in enumerate(components.get("bundled_tokenizer", [])):
add(npm_ids[PurePosixPath("node_modules/@openai/codex-security")], {
"SPDXID": f"SPDXRef-tokenizer-{i}", "name": item["name"], "versionInfo": item["version"],
"downloadLocation": "NOASSERTION", "licenseDeclared": item["licenses"][0]["license"]["id"],
"filesAnalyzed": False, "sourceInfo": "Bundled in the SDK embedding tokenizer.",
"externalRefs": [{"referenceCategory": "PACKAGE-MANAGER", "referenceType": "purl",
"referenceLocator": item["purl"]}],
})
for i, item in enumerate(components["bundled_native"]):
path = PurePosixPath(item["path"])
owner = next(npm_ids[p] for p in path.parents if p in npm_ids)
@@ -0,0 +1,50 @@
import json
import runpy
import unittest
from pathlib import Path
verifier = runpy.run_path(str(Path(__file__).resolve().parents[1] / "verify-public.py"))
inventory = verifier["inventory_tokenizer"]
SCANNER = verifier["SCANNER"]
def component(name, version):
return {"name": name, "version": version, "type": "library", "purl": f"pkg:npm/{name}@{version}",
"licenses": [{"license": {"id": "MIT"}}]}
def bom(items):
return json.dumps({"bomFormat": "CycloneDX", "components": items})
class TokenizerInventoryTest(unittest.TestCase):
def setUp(self):
self.scanner = {"dependencies": {}, "devDependencies": {"js-tiktoken": "1.2.3"}}
self.manifests = {SCANNER: self.scanner}
self.items = [component("js-tiktoken", "1.2.3"), component("base64-js", "4.5.6")]
def test_bundled_components(self):
self.assertEqual(inventory(self.manifests, bom(self.items)), self.items)
for payload in (None, bom([]), bom(self.items[:1]), bom(self.items[:1] * 2)):
with self.subTest(payload=payload), self.assertRaises(SystemExit):
inventory(self.manifests, payload)
def test_invalid_identity(self):
for change in ({"version": ""}, {"purl": "pkg:npm/base64-js@9.0.0"}, {"licenses": []},
{"type": "application"}, component("js-tiktoken", "9.0.0")):
with self.subTest(change=change), self.assertRaises(SystemExit):
inventory(self.manifests, bom([self.items[0] | change, self.items[1]]))
def test_only_the_direct_installed_dependency_supports_legacy_releases(self):
self.manifests["node_modules/js-tiktoken"] = {"name": "js-tiktoken", "version": "1.2.3"}
with self.assertRaises(SystemExit):
inventory(self.manifests, None)
self.scanner["dependencies"]["js-tiktoken"] = "1.2.3"
self.assertEqual(inventory(self.manifests, None), [])
self.manifests[SCANNER + "/node_modules/js-tiktoken"] = {"name": "js-tiktoken", "version": "0.9.0"}
with self.assertRaises(SystemExit):
inventory(self.manifests, None)
del self.manifests[SCANNER + "/node_modules/js-tiktoken"], self.manifests["node_modules/js-tiktoken"]
with self.assertRaises(SystemExit):
inventory(self.manifests, None)
+33 -1
View File
@@ -7,11 +7,14 @@ import json
import re
import tarfile
from pathlib import Path
from urllib.parse import quote
WOLFI = "https://packages.wolfi.dev/os"
REGISTRY = "https://registry.npmjs.org/"
APP = "usr/lib/codex-security/"
ENTRYPOINT = "/usr/local/bin/codex-security-entrypoint"
SCANNER = "node_modules/@openai/codex-security"
TOKENIZER_BOM = APP + SCANNER + "/dist/server/embedding-tokenizer.cdx.json"
SOURCES = "usr/share/licenses/codex-security/SOURCES.json"
APK_DATABASES = {"lib/apk/db/installed", "usr/lib/apk/db/installed"}
# A package can contain other package.json files (for example, in examples/).
@@ -66,7 +69,7 @@ def inspect_layer(fs):
check(ent.isfile(), f"Unexpected public key format: {path}")
keys[path.removeprefix("etc/apk/keys/")] = fs.extractfile(ent).read()
elif ent.isfile():
if path in APK_DATABASES or path in {"etc/apk/repositories", APP + "package-lock.json", SOURCES}:
if path in APK_DATABASES or path in {"etc/apk/repositories", APP + "package-lock.json", SOURCES, TOKENIZER_BOM}:
raw[path] = fs.extractfile(ent).read()
elif path.startswith(APP) and NPM_MANIFEST.fullmatch(path[len(APP):]):
manifests[path[len(APP):-len("/package.json")]] = json.load(fs.extractfile(ent))
@@ -121,6 +124,32 @@ def inventory_npm(manifests, packages, sources):
return npm
def inventory_tokenizer(manifests, bom):
scanner = manifests[SCANNER]
if bom is None:
# Older releases installed the pinned tokenizer as an ordinary npm dependency.
pin = scanner["dependencies"].get("js-tiktoken")
installed = next((manifests[p] for p in (SCANNER + "/node_modules/js-tiktoken", "node_modules/js-tiktoken")
if p in manifests), {})
check(pin and installed.get("name") == "js-tiktoken" and installed.get("version") == pin,
"Missing tokenizer BOM or verified legacy SDK dependency")
return []
document = json.loads(bom)
items = document["components"]
check(document.get("bomFormat") == "CycloneDX" and len(items) == 2 and
{item["name"] for item in items} == {"js-tiktoken", "base64-js"}, "Incomplete tokenizer BOM")
for item in items:
name, version = item["name"], item["version"]
check(item.get("type") == "library" and isinstance(version, str) and
re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?", version) and
item.get("purl") == f"pkg:npm/{name}@{quote(version, safe='')}" and
item.get("licenses") == [{"license": {"id": "MIT"}}], f"Invalid tokenizer BOM component: {name}")
if name == "js-tiktoken":
check(version == scanner["devDependencies"]["js-tiktoken"], "Tokenizer BOM differs from SDK build pin")
return items
def verify(archive, lock):
with tarfile.open(archive) as tar:
manifest, = json.load(tar.extractfile("manifest.json"))
@@ -173,6 +202,9 @@ def verify(archive, lock):
"public_upstream_packages":len(apks)-local, "local_scanner_packages":local,
"keyring_sha256":{k:"sha256:"+v for k,v in key_hashes.items()},
"signed_build_manifest":"SHA256SUMS", "manifest_signature":"SHA256SUMS.sig"}
tokenizer = inventory_tokenizer(manifests, raw.get(TOKENIZER_BOM))
if tokenizer:
components["bundled_tokenizer"] = tokenizer
return {"verification.json": verification, "public-components.json": components}
+4 -4
View File
@@ -13,7 +13,7 @@
"@actions/io": "3.0.2"
},
"devDependencies": {
"@types/node": "26.6.5",
"@types/node": "26.6.6",
"esbuild": "0.28.2",
"prettier": "3.9.10",
"tsx": "4.23.15",
@@ -986,9 +986,9 @@
}
},
"node_modules/@types/node": {
"version": "26.6.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz",
"integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==",
"version": "26.6.6",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
"integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
"dev": true,
"license": "MIT",
"dependencies": {
+1 -1
View File
@@ -25,7 +25,7 @@
"@actions/io": "3.0.2"
},
"devDependencies": {
"@types/node": "26.6.5",
"@types/node": "26.6.6",
"esbuild": "0.28.2",
"prettier": "3.9.10",
"tsx": "4.23.15",
+1 -1
View File
@@ -18,7 +18,7 @@
"yaml": "2.9.1"
},
"devDependencies": {
"@types/node": "^26.6.5",
"@types/node": "^26.6.6",
"esbuild": "^0.28.2",
"prettier": "3.9.10",
"typescript": "^7.0.2"
+5 -5
View File
@@ -28,8 +28,8 @@ importers:
version: 4.6.7
devDependencies:
'@types/node':
specifier: ^26.6.5
version: 26.6.5
specifier: ^26.6.6
version: 26.6.6
esbuild:
specifier: ^0.28.2
version: 0.28.2
@@ -259,8 +259,8 @@ packages:
cpu: [x64]
os: [win32]
'@types/node@26.6.5':
resolution: {integrity: sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==}
'@types/node@26.6.6':
resolution: {integrity: sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==}
'@typescript/typescript-aix-ppc64@7.0.2':
resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==}
@@ -900,7 +900,7 @@ snapshots:
'@openai/codex@0.166.0-win32-x64':
optional: true
'@types/node@26.6.5':
'@types/node@26.6.6':
dependencies:
undici-types: 8.9.0
+5 -15
View File
@@ -36,7 +36,10 @@ import {
} from "./src/deep-scan/parent-sandbox.js";
import { WorkbenchDeepScanStore } from "./src/deep-scan/store.js";
import { readDeepScanProjectConfig } from "./src/deep-scan/project-config.js";
import type { DeepScanRunState } from "./src/deep-scan/types.js";
import type {
DeepScanLogEvent,
DeepScanRunState,
} from "./src/deep-scan/types.js";
import { PLUGIN_ROOT, runWorkbench, scanRoot } from "./src/workbench-client.js";
const USER_INPUT_WAIT_TIMEOUT_MS = 14 * 60 * 1000;
@@ -2364,20 +2367,7 @@ function deepScanTerminalResult(
return undefined;
}
function logDeepScanEvent(event: {
event: string;
scanId: string;
workerId?: string;
kind?: string;
attempt?: number;
count?: number;
completed?: number;
newFindings?: number;
pass?: number;
reason?: string;
threadId?: string;
total?: number;
}): void {
function logDeepScanEvent(event: DeepScanLogEvent): void {
console.error(
JSON.stringify({ component: "codex_security_deep_scan", ...event }),
);
@@ -729,6 +729,9 @@ export class DeepScanCoordinator {
this.artifacts.dedupRoot,
"dedup",
);
let pass = persisted.filter(
(w) => w.kind === "dedup" && w.status === "succeeded",
).length;
let dispatched = this.state.dispatchedCount;
let streak = this.state.noNewStreak;
let errors = this.state.consecutiveErrors;
@@ -756,7 +759,8 @@ export class DeepScanCoordinator {
signal.throwIfAborted();
if (batch.length) {
// Newly dispatched scans arrive in launch order. Recovery uses the same labels.
for (const count of await this.mergeAcceptedBatch(result, batch)) {
const newCounts = await this.mergeAcceptedBatch(result, batch);
for (const count of newCounts) {
streak = count ? 0 : streak + 1;
}
resultPath = join(
@@ -768,8 +772,9 @@ export class DeepScanCoordinator {
"result.json",
);
await writeJsonAtomic(resultPath, persistedScanUnion(result));
const iterationId = randomUUID();
const saved = await this.options.store.recordIteration({
id: randomUUID(),
id: iterationId,
scanId,
workerIds: batch.map((w) => w.id),
resultPath,
@@ -778,6 +783,15 @@ export class DeepScanCoordinator {
});
signal.throwIfAborted();
this.state = saved;
this.log({
event: "dedup_committed",
scanId,
workerId: iterationId,
pass: ++pass,
count: batch.length,
newFindings: newCounts.reduce((sum, count) => sum + count, 0),
retainedFindings: result.findings.length,
});
this.logProgress(acceptedCount);
}
if (errors >= config.stopAfterConsecutiveErrors && failure) {
@@ -2,6 +2,7 @@ import {
scanDraftInputSchema,
type ScanDraftInput,
} from "../artifact-scan-draft.js";
import { z } from "zod";
import { asRecord } from "../record.js";
import { addScanCoverage, type ScanUnion } from "./artifact-validation.js";
import type { AcceptedDiscovery } from "./worker-runner.js";
@@ -201,6 +202,10 @@ function hasAdditionalControl(a: Finding, b: Finding) {
);
}
function separateControls(a: Finding, b: Finding) {
return hasAdditionalControl(a, b) || hasAdditionalControl(b, a);
}
function sourcesNeedSeparateReports(a: Finding, b: Finding) {
return a.provenance.sourceFindings?.some((left, i) => {
const worker = left.id.slice(0, left.id.lastIndexOf(":") + 1);
@@ -210,8 +215,7 @@ function sourcesNeedSeparateReports(a: Finding, b: Finding) {
if (right.id.startsWith(worker) && differentWorkerSites(source, other))
return true;
return (
hasAdditionalControl(source, other) ||
hasAdditionalControl(other, source) ||
separateControls(source, other) ||
((i > 0 || j > 0) && separateSinks(source, other))
);
});
@@ -245,7 +249,7 @@ function distinctIdentity(
);
}
function addLocations(finding: Finding, source: Finding) {
function addLocations(finding: Finding, source: Pick<Finding, "locations">) {
for (const location of source.locations) {
if (
!finding.locations.some(
@@ -262,31 +266,114 @@ function addLocations(finding: Finding, source: Finding) {
// Keep the original repair groups as comparison inputs even after two reports
// are published as one. A later batch must see the same reports after a resume.
type RepairGroup = { order: number; sources: string[] };
const repairGroupSchema = z.strictObject({
order: z.number().int().nonnegative(),
sources: z.array(z.string()),
});
const repairGroupsSchema = z.array(repairGroupSchema).min(1);
type RepairGroup = z.infer<typeof repairGroupSchema>;
function sourceIds(finding: Finding) {
return (
finding.provenance.sourceFindingIds ??
finding.provenance.sourceFindings?.map(({ id }) => id) ??
[]
);
}
// The persisted schema accepts partial original records from older reducers.
// Only groups with all their original reports can enter semantic comparisons.
function hasCompleteSources(finding: Finding) {
const ids = sourceIds(finding);
const sources = finding.provenance.sourceFindings ?? [];
const known = new Set(sources.map(({ id }) => id));
return (
ids.length > 0 &&
ids.length === sources.length &&
known.size === ids.length &&
ids.every((id) => known.has(id)) &&
sources.every(
({ finding }) =>
scanDraftInputSchema.shape.findings.element.safeParse(finding).success,
)
);
}
function restoreRepairGroups(findings: Finding[]) {
const groups: { finding: Finding; target: number }[] = [];
for (const [id, visible] of findings.entries()) {
const parts = visible.provenance.deepScanRepairGroups as
RepairGroup[] | undefined;
if (!parts) {
groups[id] = { finding: visible, target: id };
function visibleGroups() {
// Pre-rewrite reducers could write arbitrary fields in provenance.
return findings.map((finding, target) => {
delete finding.provenance.deepScanRepairGroups;
return { finding, target };
});
}
if (findings[0]?.provenance.deepScanRepairGroups === undefined)
return visibleGroups();
const groups = new Map<number, { finding: Finding; target: number }>();
let previousTarget = -1;
for (const visible of findings) {
const parts = repairGroupsSchema.safeParse(
visible.provenance.deepScanRepairGroups,
).data;
if (!parts || parts[0]!.order <= previousTarget) return visibleGroups();
const target = parts[0]!.order;
previousTarget = target;
if (parts.length === 1) {
// Singletons already carry the visible report, even if a legacy source
// has only a title or a reference with no archived finding.
const ids = sourceIds(visible);
const sources = parts[0]!.sources;
if (
groups.has(target) ||
ids.length !== sources.length ||
!ids.every((id, i) => id === sources[i])
)
return visibleGroups();
delete visible.provenance.deepScanRepairGroups;
groups.set(target, { finding: visible, target });
continue;
}
const originals = new Map(
visible.provenance.sourceFindings!.map((source) => [source.id, source]),
visible.provenance.sourceFindings?.map((source) => [source.id, source]),
);
for (const { order, sources } of parts) {
const members = sources.map((id) => originals.get(id)!);
const finding = structuredClone(members[0]!.finding) as Finding;
if (!sources.length || order < target || groups.has(order))
return visibleGroups();
const members = [];
for (const id of sources) {
const source = originals.get(id);
if (!source) return visibleGroups();
originals.delete(id);
members.push(source);
}
const finding = scanDraftInputSchema.shape.findings.element.safeParse(
members[0]!.finding,
).data;
if (!finding) return visibleGroups();
delete finding.provenance.deepScanRepairGroups;
finding.provenance.sourceFindingIds = sources;
finding.provenance.sourceFindings = members;
for (const member of members.slice(1))
addLocations(finding, member.finding as Finding);
groups[order] = { finding, target: parts[0]!.order };
for (const member of members.slice(1)) {
const locations =
scanDraftInputSchema.shape.findings.element.shape.locations.safeParse(
member.finding.locations,
).data;
if (!locations) return visibleGroups();
addLocations(finding, { locations });
}
groups.set(order, { finding, target });
}
if (originals.size) return visibleGroups();
}
return groups;
// Validate the dense sequence before assigning any array indexes.
const ordered = [];
for (let order = 0; order < groups.size; order++) {
const group = groups.get(order);
if (!group) return visibleGroups();
ordered.push(group);
}
return ordered;
}
export async function mergeBatch(
@@ -311,8 +398,15 @@ export async function mergeBatch(
JSON.stringify({ ...finding, provenance: undefined });
const exact = originals.map(content);
const copies = new Map<string, (typeof retained)[number]>();
const incomplete = new Set<number>();
for (const group of retained) {
copies.set(exact[group.id]!, group);
if (!hasCompleteSources(group.finding)) {
incomplete.add(group.target);
continue;
}
// A legacy checkpoint can include all originals without the separate ID array.
group.finding.provenance.sourceFindingIds ??= sourceIds(group.finding);
for (const source of group.finding.provenance.sourceFindings ?? [])
copies.set(content(source.finding), group);
}
@@ -352,6 +446,7 @@ export async function mergeBatch(
retained.find((prior) => {
const other = repairs?.get(prior.id);
if (
incomplete.has(prior.target) ||
!key ||
!other ||
key.length !== other.length ||
@@ -375,7 +470,7 @@ export async function mergeBatch(
source,
finding,
id.startsWith(worker.id + ":"),
),
) || separateControls(source, finding as Finding),
)
);
});
@@ -394,7 +489,9 @@ export async function mergeBatch(
const sourceId = `${worker.id}:${index}`;
copies.set(exact[id]!, group);
const { finding } = group;
(finding.provenance.sourceFindingIds ??= []).push(sourceId);
(finding.provenance.sourceFindingIds ??= sourceIds(finding)).push(
sourceId,
);
(finding.provenance.sourceFindings ??= []).push({
id: sourceId,
finding: structuredClone(source),
@@ -423,43 +520,40 @@ export async function mergeBatch(
group.target = group.id;
group.worker = worker;
}
if (
repairs &&
retained.some((group) => group.worker >= 0) &&
retained.every(
({ finding }) =>
finding.provenance.sourceFindings?.length &&
finding.provenance.sourceFindingIds?.length,
)
) {
let matches: Map<number, Set<number>> | undefined;
try {
const sources = new Map<number, Record<string, unknown>[]>();
for (const group of retained) {
const members = sources.get(group.target) ?? [];
members.push(
...group.finding.provenance.sourceFindings!.map((s) => s.finding),
);
sources.set(group.target, members);
}
matches = await checkSameFix(
retained.filter((group) => group.target === group.id),
priorTargets,
records,
repairs,
sources,
compare,
if (repairs && retained.some((group) => group.worker >= 0)) {
const sources = new Map<number, Record<string, unknown>[]>();
for (const group of retained) {
if (incomplete.has(group.target)) continue;
const members = sources.get(group.target) ?? [];
members.push(
...group.finding.provenance.sourceFindings!.map((s) => s.finding),
);
} catch (error) {
onError(error);
sources.set(group.target, members);
}
const reviewFailures = new Set<string>();
const matches = await checkSameFix(
retained.filter(
(group) => group.target === group.id && !incomplete.has(group.target),
),
priorTargets,
records,
repairs,
sources,
compare,
(error) => {
onError(error);
reviewFailures.add(errorMessage(error));
},
);
if (reviewFailures.size) {
limitation = [
limitation,
`Deep Scan could not check disputed duplicates: ${errorMessage(error)}`,
`Deep Scan could not check disputed duplicates: ${[...reviewFailures].join(" / ")}`,
]
.filter(Boolean)
.join(" ");
}
if (matches?.size) {
if (matches.size) {
const kept = new Map<number, typeof retained>();
for (const group of retained) {
const earlier = matches.get(group.id);
@@ -505,7 +599,7 @@ export async function mergeBatch(
}
(target.provenance.deepScanRepairGroups as RepairGroup[]).push({
order,
sources: group.finding.provenance.sourceFindingIds!,
sources: sourceIds(group.finding),
});
}
aggregate.findings = [...visible.values()];
@@ -59,6 +59,8 @@ const sourceInstructions = `Judge each pair of original reports independently as
Identify the faulty operation or missing check and the smallest change that fixes A. Do the same for B. Read the summary, root cause and code. A missing check that a report explicitly describes as a cause counts even if it has the same impact as the primary bug. Suggested hardening and different ways of implementing the correction do not count as additional bugs.
Apply each fix alone. If a claimed defect in the other report survives, quote the phrase that claims it and name a concrete input or operation that still fails. Put these counterexamples in survivingPaths. Different examples, callers, or consequences of one faulty operation are compatible when correcting that operation resolves both. Do not infer an additional requirement from a hypothetical attack that neither report claims. Return same only when the two complete corrections are equivalent and the evidence supports the decision. Keep uncertain pairs separate.`;
// Each pair needs its own model verdict and two evidence references.
const PAIRS_PER_REVIEW = 16;
type Pair = { id: number; left: number; right: number };
function claim({
title,
@@ -71,27 +73,22 @@ function claim({
return { title, summary, rootCause, remediation, locations, codeEvidence };
}
// Structured output constrains each row, but can still return the same ID twice.
function unambiguous<T>(rows: T[], id: (row: T) => number): T[] {
return [...Map.groupBy(rows, id).values()].flatMap((group) =>
group.length === 1 ? group : [],
);
}
async function confirmSources(
pairs: Pair[],
originals: Map<number, Record<string, unknown>[]>,
claimsFor: (id: number) => ReturnType<typeof claim>[],
compare: CompareReports,
) {
const cases = pairs.flatMap((pair) =>
originals
.get(pair.right)!
.flatMap((a) =>
originals
.get(pair.left)!
.map((b) => ({ pair, A: claim(a), B: claim(b) })),
),
);
const rejected = new Set<number>();
// Grade small independent pairs. A grouped report can carry many original claims.
for (let start = 0; start < cases.length; start += 4) {
const batch = cases
.slice(start, start + 4)
.filter(({ pair }) => !rejected.has(pair.id));
if (!batch.length) continue;
type Claim = ReturnType<typeof claim>;
const batch: { pair: Pair; A: Claim; B: Claim }[] = [];
async function gradeBatch() {
const rows = batch.map(({ A, B }, id) => ({ id, A, B }));
const { sources } = JSON.parse(
await compare(
@@ -100,16 +97,31 @@ async function confirmSources(
),
);
const same = new Set(
sources
.filter(
(s: { same: boolean; survivingPaths: string[] }) =>
s.same && !s.survivingPaths.length,
)
.map((s: { id: number }) => s.id),
unambiguous(
sources as { id: number; same: boolean; survivingPaths: string[] }[],
(s) => s.id,
)
.filter((s) => s.same && !s.survivingPaths.length)
.map((s) => s.id),
);
for (const [id, { pair }] of batch.entries())
if (!same.has(id)) rejected.add(pair.id);
batch.length = 0;
}
// A single surviving path rejects the pair. Generate only the cases we still need.
nextPair: for (const pair of pairs) {
const left = claimsFor(pair.left);
for (const A of claimsFor(pair.right)) {
for (const B of left) {
batch.push({ pair, A, B });
if (batch.length === 4) {
await gradeBatch();
if (rejected.has(pair.id)) continue nextPair;
}
}
}
}
if (batch.length) await gradeBatch();
return pairs.filter(({ id }) => !rejected.has(id));
}
@@ -138,80 +150,128 @@ export async function checkSameFix(
repairs: Map<number, number[] | undefined>,
originals: Map<number, Record<string, unknown>[]>,
compare: CompareReports,
onReviewError: (error: unknown) => void,
) {
const evidence = records.map((record) =>
record.evidence.flatMap(([path, code]) => (path ? [{ path, code }] : [])),
);
const batches = new Map<number, Pair[]>();
for (const [i, { id: right, worker }] of groups.entries()) {
if (worker < 0) continue;
const b = repairs.get(right);
for (const { id: left } of groups.slice(0, i)) {
const a = repairs.get(left);
const prior = priorTargets[right];
if (prior !== undefined && priorTargets[left] !== prior) continue;
if (
prior === undefined &&
!(a && b
? a.some((key) => b.includes(key))
: sharesSource(records[left]!, records[right]!))
)
continue;
if (
!evidence[left]!.some((x) =>
evidence[right]!.some((y) => x.path === y.path),
const pending = groups
.map(({ id, worker }, index) => ({ id, worker, index }))
.filter(({ worker }) => worker >= 0);
const workers = Map.groupBy(pending, ({ worker }) => worker);
function* candidatePairs(workerGroups: typeof pending): Generator<Pair> {
let pairId = 0;
for (const { id: right, index } of workerGroups) {
const b = repairs.get(right);
for (let i = 0; i < index; i++) {
const left = groups[i]!.id;
const a = repairs.get(left);
const prior = priorTargets[right];
if (prior !== undefined && priorTargets[left] !== prior) continue;
if (
prior === undefined &&
!(a && b
? a.some((key) => b.includes(key))
: sharesSource(records[left]!, records[right]!))
)
)
continue;
const pairs = batches.get(worker) ?? [];
pairs.push({ id: pairs.length, left, right });
batches.set(worker, pairs);
continue;
if (
!evidence[left]!.some((x) =>
evidence[right]!.some((y) => x.path === y.path),
)
)
continue;
yield { id: pairId++, left, right };
}
}
}
const claims = new Map<number, ReturnType<typeof claim>[]>();
function claimsFor(id: number) {
let rows = claims.get(id);
if (rows === undefined) {
// Keep every observation in the artifact. Send identical evidence to the model once.
const distinct = new Map<string, ReturnType<typeof claim>>();
for (const source of originals.get(id)!) {
const row = claim(source);
distinct.set(JSON.stringify(row), row);
}
rows = [...distinct.values()];
claims.set(id, rows);
}
return rows;
}
const matches = new Map<number, Set<number>>();
async function reviewPairs(pairs: Pair[]) {
const reports = [
...new Set(pairs.flatMap(({ left, right }) => [left, right])),
].map((id) => {
const [first, ...rest] = claimsFor(id);
const { title, summary, rootCause, remediation } = first!;
return {
id,
primary: {
title,
summary,
rootCause,
remediation,
locations: records[id]!.locations,
evidence: evidence[id]!.map((excerpt, id) => ({ id, ...excerpt })),
},
attached: rest,
};
});
const { reviews } = JSON.parse(
await compare(
instructions + "\n" + JSON.stringify({ pairs, reports }),
schema,
),
);
const proposed: Pair[] = [];
const decisions = unambiguous(
reviews as {
pair: number;
decision: string;
leftEvidence: number;
rightEvidence: number;
}[],
(review) => review.pair,
);
for (const { pair, decision, leftEvidence, rightEvidence } of decisions) {
const candidate = pairs.find(({ id }) => id === pair);
if (decision !== "same" || !candidate) continue;
const { left, right } = candidate;
const path = evidence[left]![leftEvidence]?.path;
if (!path || path !== evidence[right]![rightEvidence]?.path) continue;
proposed.push(candidate);
}
for (const { left, right } of await confirmSources(
proposed,
claimsFor,
compare,
)) {
const earlier = matches.get(right) ?? new Set<number>();
earlier.add(left);
matches.set(right, earlier);
}
}
async function reviewBatch(pairs: Pair[]) {
try {
await reviewPairs(pairs);
} catch (error) {
onReviewError(error);
}
}
const results = await Promise.allSettled(
[...batches.values()].map(async (pairs) => {
const reports = [
...new Set(pairs.flatMap(({ left, right }) => [left, right])),
].map((id) => {
const [first, ...rest] = originals.get(id)!;
const { title, summary, rootCause, remediation } = first!;
return {
id,
primary: {
title,
summary,
rootCause,
remediation,
locations: records[id]!.locations,
evidence: evidence[id]!.map((excerpt, id) => ({ id, ...excerpt })),
},
attached: rest.map(claim),
};
});
const { reviews } = JSON.parse(
await compare(
instructions + "\n" + JSON.stringify({ pairs, reports }),
schema,
),
);
const proposed: Pair[] = [];
for (const { pair, decision, leftEvidence, rightEvidence } of reviews) {
if (decision !== "same" || !pairs[pair]) continue;
const { left, right } = pairs[pair]!;
const path = evidence[left]![leftEvidence]?.path;
if (!path || path !== evidence[right]![rightEvidence]?.path) continue;
proposed.push(pairs[pair]!);
}
for (const { left, right } of await confirmSources(
proposed,
originals,
compare,
)) {
const earlier = matches.get(right) ?? new Set<number>();
earlier.add(left);
matches.set(right, earlier);
[...workers.values()].map(async (workerGroups) => {
const batch: Pair[] = [];
for (const pair of candidatePairs(workerGroups)) {
batch.push(pair);
if (batch.length === PAIRS_PER_REVIEW) {
await reviewBatch(batch);
batch.length = 0;
}
}
if (batch.length) await reviewBatch(batch);
}),
);
for (const result of results)
@@ -115,6 +115,7 @@ export interface DeepScanLogEvent {
count?: number;
completed?: number;
newFindings?: number;
retainedFindings?: number;
pass?: number;
reason?: string;
total?: number;
@@ -719,16 +719,19 @@ test("fixing login cannot hide a separately cited permissive action policy", asy
{ path: "policy.py", startLine: 2, role: "control" },
],
};
const { draft } = await scanLoop([[login, policy]], {
maxDiscoveryRuns: 1,
stopAfterNoNew: 1,
comparisons: [[[0, 1], [1]]],
sameFix: approvePairs,
});
assert.deepEqual(
draft.findings.map((f) => f.title),
[login.title, policy.title],
);
// The primary comparison can agree on a single repair or send the pair to confirmation.
for (const assignments of [[[0, 1]], [[0, 1], [1]]]) {
const { draft } = await scanLoop([[login, policy]], {
maxDiscoveryRuns: 1,
stopAfterNoNew: 1,
comparisons: [assignments],
sameFix: approvePairs,
});
assert.deepEqual(
draft.findings.map((f) => f.title),
[login.title, policy.title],
);
}
});
test("a later source with a surviving path reopens the merge and counts as new", async () => {
@@ -780,6 +783,9 @@ test("a failed comparison waits for every started worker batch", async () => {
await release.promise;
return JSON.stringify({ reviews: [] });
},
(error: unknown) => {
throw error;
},
);
const rejected = assert.rejects(check, /comparison failed/).then(() => {
finished = true;
@@ -1010,3 +1016,351 @@ test("a merged report cannot lend its extra citation to a later comparison", asy
[2, 1],
);
});
for (const conflict of ["reviews", "sources"]) {
test(`conflicting ${conflict} cannot hide an independent finding`, async () => {
const { checkSameFix } = await importSource(
join(import.meta.dirname, "../src/deep-scan/same-fix.ts"),
);
const groups = [
{ id: 0, worker: 0 },
{ id: 1, worker: 0 },
];
const records = groups.map(() => ({
locations: [["fixture.py", 1, 1]],
evidence: [["fixture.py", "lookup(id)"]],
}));
const matches = await checkSameFix(
groups,
[],
records,
new Map(),
new Map(groups.map(({ id }) => [id, [lookup]])),
async (
_prompt: string,
schema: { properties: Record<string, unknown> },
) => {
if ("reviews" in schema.properties) {
const approve = samePair(0);
return JSON.stringify({
reviews:
conflict === "reviews"
? [approve, { ...approve, decision: "keep" }]
: [approve],
});
}
const approve = {
id: 0,
same: true,
fixA: "validate",
fixB: "validate",
survivingPaths: [],
};
return JSON.stringify({
sources:
conflict === "sources"
? [
approve,
{
...approve,
same: false,
survivingPaths: ["second handler"],
},
]
: [approve],
});
},
(error: unknown) => {
throw error;
},
);
assert.equal(matches.size, 0);
});
}
test("repeated original observations require one source comparison", async () => {
const observations = Array.from({ length: 8 }, () => lookup);
let sourceChecks = 0;
const alias = {
...lookup,
title: "Another description of the shared lookup",
};
const { draft } = await scanLoop([[...observations, alias]], {
maxDiscoveryRuns: 1,
stopAfterNoNew: 1,
comparisons: [
() => ({
uncertain: observations.map((_, i) => i).concat(observations.length),
defects: [],
}),
],
sameFix: approvePairs,
sameSource: () => {
sourceChecks++;
return true;
},
});
assert.equal(draft.findings.length, 1);
assert.equal(draft.findings[0]!.provenance.sourceFindings!.length, 9);
assert.equal(sourceChecks, 1);
});
test("review batches limit pair counts and isolate rejected and stale decisions", async () => {
const { checkSameFix } = await importSource(
join(import.meta.dirname, "../src/deep-scan/same-fix.ts"),
);
const groups = Array.from({ length: 9 }, (_, id) => ({ id, worker: 0 }));
const records = groups.map(() => ({
locations: [["fixture.py", 1, 1]],
evidence: [["fixture.py", "lookup(id)"]],
}));
const sizes: number[] = [];
const failures: unknown[] = [];
const expected = new Map<number, Set<number>>();
const matches = await checkSameFix(
groups,
[],
records,
new Map(),
new Map(groups.map(({ id }) => [id, [lookup]])),
async (prompt: string, schema: { properties: Record<string, unknown> }) => {
const input = JSON.parse(prompt.split("\n").at(-1)!);
if ("reviews" in schema.properties) {
const { pairs } = input as PairCheck;
sizes.push(pairs.length);
if (sizes.length === 1) throw new Error("review failed");
const last = pairs.at(-1)!;
const earlier = expected.get(last.right) ?? new Set<number>();
earlier.add(last.left);
expected.set(last.right, earlier);
// ID zero belongs to the failed first batch.
return JSON.stringify({ reviews: [samePair(0), samePair(last.id)] });
}
return JSON.stringify({
sources: input.map(({ id }: { id: number }) => ({
id,
same: true,
survivingPaths: [],
})),
});
},
(error: unknown) => failures.push(error),
);
assert.deepEqual(sizes, [16, 16, 4]);
assert.deepEqual(matches, expected);
assert.equal(failures.length, 1);
});
test("legacy provenance cannot drop or overwrite visible findings on resume", async () => {
const { mergeBatch } = await importSource(
join(import.meta.dirname, "../src/deep-scan/iteration.ts"),
);
const { parseScanUnion } = await importSource(
join(import.meta.dirname, "../src/deep-scan/artifact-validation.ts"),
);
const findings = [lookup, { ...lookup, title: "Independent report" }];
for (const metadata of [
"old model annotation",
[],
[{ order: 0, sources: ["missing:0"] }],
[{ order: 2147483647, sources: ["w:0"] }],
[{ order: 0, sources: ["w:0"] }],
]) {
const restored = parseScanUnion({
scanId: randomUUID(),
findings: findings.map((finding, i) => ({
...finding,
provenance: {
...finding.provenance,
sourceFindingIds: [`w:${i}`],
sourceFindings: [{ id: `w:${i}`, finding }],
// Older reducers could put arbitrary model-supplied fields here.
deepScanRepairGroups: i ? [{ order: 0, sources: ["w:1"] }] : metadata,
},
})),
});
const unexpected = () => {
throw new Error("unexpected model call");
};
await mergeBatch(restored, [], "/tmp", unexpected, unexpected);
assert.deepEqual(
restored.findings.map((f: typeof lookup) => f.title),
findings.map((f) => f.title),
);
assert.ok(
restored.findings.every(
(f: typeof lookup) => f.provenance.deepScanRepairGroups === undefined,
),
);
}
});
test("resuming partial source ancestry isolates only the ambiguous finding", async () => {
const { mergeBatch } = await importSource(
join(import.meta.dirname, "../src/deep-scan/iteration.ts"),
);
const { parseScanUnion, persistedScanUnion, scanUnionToDraft } =
await importSource(
join(import.meta.dirname, "../src/deep-scan/artifact-validation.ts"),
);
for (const ancestry of [
{
sourceFindings: [{ id: "w:0", finding: { title: "old" } }],
sourceFindingIds: ["w:0"],
},
{
sourceFindings: [
{ id: "w:0", finding: { title: "old", locations: lookup.locations } },
],
},
{ sourceFindingIds: ["w:0"] },
{},
]) {
const scanId = randomUUID();
const old = {
...lookup,
title: "Previously visible report",
provenance: { ...lookup.provenance, ...ancestry },
};
let saved = parseScanUnion({ scanId, findings: [old] });
const titles = ["Current bug", "Alias of current bug"];
const worker = (id: string, entries: string[]) => ({
id,
resultPath: join("/tmp", id, "result.json"),
result: {
...standardScanDraft(scanId, undefined, id),
findings: entries.map((title) => ({ ...lookup, title })),
},
});
const fail = (error: unknown) => {
throw error;
};
let reviews = 0;
await mergeBatch(
saved,
[worker("second", titles)],
"/tmp",
async (
prompt: string,
schema: { properties: Record<string, unknown> },
) => {
const input = JSON.parse(prompt.split("\n").at(-1)!);
if ("reviews" in schema.properties) {
reviews++;
assert.deepEqual(
input.pairs.map((p: { left: number; right: number }) => [
p.left,
p.right,
]),
[[1, 2]],
);
return JSON.stringify(approvePairs(input));
}
if ("sources" in schema.properties)
return JSON.stringify({
sources: input.map(({ id }: { id: number }) => ({
id,
same: true,
survivingPaths: [],
})),
});
// The old report and the new primary share a proposed direct assignment;
// the alias also lists a second assignment and needs same-fix confirmation.
return JSON.stringify({
uncertain: [],
defects: [[0, 1, 2], [2]].map((ids) => ({
operation: "lookup",
failure: "check",
path: "fixture.py",
reports: ids.map((id) => ({ id, evidence: 0 })),
})),
});
},
fail,
);
assert.equal(reviews, 1);
saved = parseScanUnion(
JSON.parse(JSON.stringify(persistedScanUnion(saved))),
);
await mergeBatch(
saved,
[worker("third", [titles[1]!])],
"/tmp",
fail,
fail,
);
const result = scanUnionToDraft(saved);
assert.deepEqual(
result.findings.map((f: typeof lookup) => f.title),
[old.title, titles[0]],
);
assert.deepEqual(result.findings[0].provenance, old.provenance);
assert.deepEqual(result.findings[1].provenance.sourceFindingIds, [
"second:0",
"second:1",
"third:0",
]);
}
});
for (const partialSource of ["primary", "secondary"] as const) {
test(`an exact repeat stays merged after reloading a partial ${partialSource} source`, async () => {
const { mergeBatch } = await importSource(
join(import.meta.dirname, "../src/deep-scan/iteration.ts"),
);
const { parseScanUnion, persistedScanUnion, scanUnionToDraft } =
await importSource(
join(import.meta.dirname, "../src/deep-scan/artifact-validation.ts"),
);
const scanId = randomUUID();
const sources = [lookup, lookup].map((finding, index) => ({
id: `old:${index}`,
finding:
index === (partialSource === "primary" ? 0 : 1)
? { title: finding.title }
: finding,
}));
const checkpoint = {
scanId,
findings: [
{
...lookup,
provenance: { ...lookup.provenance, sourceFindings: sources },
},
],
};
const result = parseScanUnion(
JSON.parse(JSON.stringify(persistedScanUnion(checkpoint))),
);
const worker = {
id: "new",
resultPath: "/tmp/new/result.json",
result: {
...standardScanDraft(scanId, undefined, "new"),
findings: parseScanUnion({ scanId, findings: [lookup] }).findings,
},
};
let comparisons = 0;
const compare = async () => {
comparisons++;
return JSON.stringify({ uncertain: [0, 1], defects: [] });
};
assert.deepEqual(
await mergeBatch(result, [worker], "/tmp", compare, () => {}),
[0],
);
const published = scanUnionToDraft(result).findings;
assert.equal(published.length, 1);
assert.equal(comparisons, 0);
assert.equal(published[0].title, lookup.title);
assert.deepEqual(published[0].provenance.sourceFindingIds, [
"old:0",
"old:1",
"new:0",
]);
assert.deepEqual(
published[0].provenance.sourceFindings.slice(0, 2),
sources,
);
});
}
@@ -34,6 +34,20 @@ try {
assert.equal(terminal?.status, "succeeded", terminal?.error);
assert.equal(executor.discoveryCalls, 1);
assert.equal(store.iterations.length, 1);
assert.deepEqual(
events.filter(({ event }) => event === "dedup_committed"),
[
{
event: "dedup_committed",
scanId: fixture.run.scanId,
workerId: store.iterations[0]!.id,
pass: 1,
count: 1,
newFindings: 1,
retainedFindings: 1,
},
],
);
for (const event of [
"coordinator_started",
"discovery_accepted",
+3 -3
View File
@@ -199,9 +199,9 @@ do not. Use `python -m pytest -n 0` to reproduce Python failures serially.
Each week `test-quality` runs the mutation trial on Linux. On Linux, macOS, and
Windows it runs the test files that import the shared property options, using
the workflow run number as the property seed. The filesystem properties read
the plugin's checked-in schemas and example scan. Each platform uploads its JUnit
report. To replay the weekly jobs, dispatch with `compare-layouts` disabled.
the workflow run number as the property seed. The filesystem properties use the
same bundled plugin as the SDK tests to read the example scan and validate its
sealed artifacts. Each platform uploads its JUnit report. To replay the weekly jobs, dispatch with `compare-layouts` disabled.
Ordinary source pull requests run focused contracts for the shard runner, timing
metadata, report comparator, and Windows test-root helper in the required SDK suite.
+7 -7
View File
@@ -1275,13 +1275,13 @@ failed or interrupted attempt:
- An unavailable, failed, or canceled scan starts a new attempt at the pinned
revision, preserving old artifacts and checkouts.
Each committed receipt in `results.jsonl` needs a nonempty task ID and output
directory, a positive integer attempt, and a supported status. Optional knowledge
extraction and severity-policy flags must be booleans. Invalid records stop both
ordinary resume and `--recover`. The error identifies the line, and the original
ledger and any interrupted tail stay intact.
Restore a complete ledger backup that includes every committed attempt, or start
a separate campaign in a new `--output-dir`.
Each nonempty committed line in `results.jsonl` must be valid JSON with a nonempty
task ID and output directory, a supported status, and a positive safe integer attempt
number. Optional failure flags must be booleans. If a line fails these checks,
the command reports its line number and preserves the ledger. Restore a complete
ledger backup that includes every committed attempt, or start a separate campaign
in a new `--output-dir`. If a repository exhausts its attempt numbers, starting
a fresh attempt requires a new campaign.
New attempts use `recovery-checkouts/<id>/attempt-<n>`. Recovery defaults to four
workers and one recovery/new attempt per repository. A resume connection failure
+4 -4
View File
@@ -59,7 +59,7 @@
"scripts": {
"audit:prod": "pnpm audit --prod --audit-level high",
"clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
"build": "node --run clean && node scripts/generate-plugin-defaults.mjs && tsc -p tsconfig.build.json && node scripts/generate-project-config-schema.mjs",
"build": "node --run clean && node scripts/generate-plugin-defaults.mjs && tsc -p tsconfig.build.json && node scripts/build-embedding-tokenizer.mjs && node scripts/generate-project-config-schema.mjs",
"build:ci": "tsc -p tsconfig.ci.json",
"build:evals": "node --run build && tsc -p ../../evals/tsconfig.json",
"build:examples": "tsc -p tsconfig.examples.json",
@@ -81,7 +81,7 @@
"types": "node scripts/generate-plugin-defaults.mjs --check && node scripts/generate-project-config-schema.mjs --check && pnpm run generate:models:check && pnpm run generate:external-import-models:check && pnpm --dir ../../plugins/codex-security/mcp-app run typecheck && tsc --noEmit"
},
"dependencies": {
"@inquirer/prompts": "8.7.4",
"@inquirer/prompts": "8.7.5",
"@linear/sdk": "100.0.0",
"@octokit/core": "7.0.8",
"@openai/codex": "0.166.0",
@@ -90,7 +90,6 @@
"fflate": "0.8.3",
"incur": "0.7.1",
"ink": "8.0.0",
"js-tiktoken": "1.0.21",
"papaparse": "5.7.0",
"pdfjs-dist": "6.4.299",
"react": "19.3.1",
@@ -105,7 +104,7 @@
},
"devDependencies": {
"@types/bun": "1.4.4",
"@types/node": "26.6.5",
"@types/node": "26.6.6",
"@types/papaparse": "5.5.2",
"@types/react": "19.3.0",
"@types/semver": "7.8.0",
@@ -113,6 +112,7 @@
"esbuild": "0.28.2",
"fast-check": "4.10.2",
"ink-testing-library": "4.0.0",
"js-tiktoken": "1.0.21",
"json-schema-to-typescript": "16.0.0",
"json5": "2.2.3",
"prettier": "3.9.10",
+115 -115
View File
@@ -9,8 +9,8 @@ importers:
.:
dependencies:
'@inquirer/prompts':
specifier: 8.7.4
version: 8.7.4(@types/node@26.6.5)
specifier: 8.7.5
version: 8.7.5(@types/node@26.6.6)
'@linear/sdk':
specifier: 100.0.0
version: 100.0.0(graphql@17.0.2)
@@ -35,9 +35,6 @@ importers:
ink:
specifier: 8.0.0
version: 8.0.0(@types/react@19.3.0)(react@19.3.1)
js-tiktoken:
specifier: 1.0.21
version: 1.0.21
papaparse:
specifier: 5.7.0
version: 5.7.0
@@ -76,8 +73,8 @@ importers:
specifier: 1.4.4
version: 1.4.4
'@types/node':
specifier: 26.6.5
version: 26.6.5
specifier: 26.6.6
version: 26.6.6
'@types/papaparse':
specifier: 5.5.2
version: 5.5.2
@@ -99,6 +96,9 @@ importers:
ink-testing-library:
specifier: 4.0.0
version: 4.0.0(@types/react@19.3.0)
js-tiktoken:
specifier: 1.0.21
version: 1.0.21
json-schema-to-typescript:
specifier: 16.0.0
version: 16.0.0
@@ -286,12 +286,12 @@ packages:
peerDependencies:
graphql: ^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0
'@inquirer/ansi@2.0.9':
resolution: {integrity: sha512-0Ywt3S8tqM6TWUcsRlBFQ1x+X3/o8kktX0ZiKAnByYb9GFDknnOhse1PVtfiD2BXPI8ar+BWx9PV9R0lQIcygw==}
'@inquirer/ansi@2.0.10':
resolution: {integrity: sha512-dwrc+1aqVZpHNkNDswXGtn1typ+Pxpo5FHZRyBw1le7onEJUkPUkYOY1FIFC1LvFMYUqqLuWBwElhAmencL7MQ==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
'@inquirer/checkbox@5.2.7':
resolution: {integrity: sha512-/+QmGE/9bvE/EobaZDnzYe+T+QWoJrnmxwBQNtoi2OVSUR9d1znYsNyEoUrOZvFSxDYttrhzRIpXpaLkN+iIsg==}
'@inquirer/checkbox@5.2.8':
resolution: {integrity: sha512-NY/S1EalQhlonqhwwsarrcnkH7s9ByQuvjWYdk1jB2Gb9EPQJjKkhCTWjM3yQ0UpHaLm1XbIL89b+32G8rhO5w==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
@@ -299,8 +299,8 @@ packages:
'@types/node':
optional: true
'@inquirer/confirm@6.3.4':
resolution: {integrity: sha512-ZwnaZZDa1zxsyVrN32s447ydMnKcw7e8WWNT+R+Qsu0zAn8Rs6yi9d1B80Kob1Ul2cfUi7t8JD2t4/K7uEZpqA==}
'@inquirer/confirm@6.3.5':
resolution: {integrity: sha512-BJ59BOyURiZiAxdr9AuRu38/k+rV+DcTIM2fUF/c/BXrab6H8zMZTTOl3LgkSJH96Xob2vOJxDiBkHiz32Xx2w==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
@@ -308,8 +308,8 @@ packages:
'@types/node':
optional: true
'@inquirer/core@12.0.5':
resolution: {integrity: sha512-c0ZSnO9oVk/IlEGoZK3u8b3IZQeu9I6jUkXJSQnQEVRXsjKvtAq3AGqFL2LgfJhlzMZne08pZHWRWasIcI3Rew==}
'@inquirer/core@12.0.6':
resolution: {integrity: sha512-5yxn2LsJ8Tu4ei2a+yNkmFRhM/cb+JMEsEs/AW6CCOnBnpMy4IjYiPMFyHtYq8weOmlTyqqCx40y0DsD7OsEPw==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
@@ -317,8 +317,8 @@ packages:
'@types/node':
optional: true
'@inquirer/editor@5.3.5':
resolution: {integrity: sha512-6lU3/pPx5z3lHWejFW061MV4qZooBQYv/+EeGhNOPiP/i+hrYsHfxxBnnDGsAfg8YdLUd69YckoeOjtr3QuAUg==}
'@inquirer/editor@5.3.6':
resolution: {integrity: sha512-Z5SOeRC5VNkINfKN4rY8BSaYKb3GYi8iSEqZZRqogsE2GhBBToQ0Xw25SbI+4bcatLzU009mZ5d9EuJNiJuUCg==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
@@ -326,8 +326,8 @@ packages:
'@types/node':
optional: true
'@inquirer/expand@5.1.7':
resolution: {integrity: sha512-eiJ31YFCaB6fLoJCqLIn8S6eqUyME6vwr8KcP5h8cxmA+bV9RRVPO+kywoxb7G63HduDXV6sN/SM7o2R+ahEcQ==}
'@inquirer/expand@5.1.8':
resolution: {integrity: sha512-dMEnTkpLqzM/sbILwL7QJgx9iX5hoEM8+bh6shgwd9mYJamdOnth7y2mMaFd08Glj9AXEFKllWcGYyBqnJsHrA==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
@@ -335,8 +335,8 @@ packages:
'@types/node':
optional: true
'@inquirer/external-editor@3.0.6':
resolution: {integrity: sha512-rWmw6WG8JZ7LMn/srXEylYGhL6EXXJeROE7/4x4GREh6NgzqJBDbIgpNGsYoLPfobeb4VZtEYzPGnT5EFNYhiQ==}
'@inquirer/external-editor@3.0.7':
resolution: {integrity: sha512-enNqTJpojgISCG+a5acjnfJ02hcRTFUBVm8uXiCY40PRPZtSzFnNLskOTU+kDUUEODYma90syxuea1rRtUFh0Q==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
@@ -344,12 +344,12 @@ packages:
'@types/node':
optional: true
'@inquirer/figures@2.0.9':
resolution: {integrity: sha512-EAWgUTGQ/Umgga51dE3B2PUHbufuXarDfg86uVgoSgNHNNQnyFKcOrQLWVqYMghuSyHh8+2HUH0Js9cTC1WAdg==}
'@inquirer/figures@2.0.10':
resolution: {integrity: sha512-51elrUJV3jZpvD0ygz8+U10Kc6+Lzqln+/tYmnbhy6jo5oXpE6hMCcv+OTBC0enwJXsb3JIuT3VtEinRNCSK2A==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
'@inquirer/input@5.1.8':
resolution: {integrity: sha512-psOSTgkL8y/OtgJJYbqJ0oISr2QBE0U1Ro/qQdA/EKjeJiwiUTQgQmq8o4ESNzVOWthIeh3YLD7BCUR9dKnR5g==}
'@inquirer/input@5.1.9':
resolution: {integrity: sha512-2Vd5T7lTxfgJMpAd3aOu6bQpbUnCU7tBgvTQIZkP/7juJzmRmTM2t5XfOCuirFduWLTSJI/WZp32Cq1E01TVeg==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
@@ -357,8 +357,8 @@ packages:
'@types/node':
optional: true
'@inquirer/number@4.2.5':
resolution: {integrity: sha512-lEy7LWsdF5qHx5QjHZqabUqM9P7i5uTMCt8GRzqxmwXXKbapKJDA+ucVflVVPAyj4snD5DTAD4L+sct85XOlOQ==}
'@inquirer/number@4.2.6':
resolution: {integrity: sha512-22LnGGCDm1M/pKXxxF8n6ppr/1IztdsxqeqeBRUMTTNnJTkjIBiAkewiDM4u/gjtazj/FvZS+nk9AbO/vEcBFQ==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
@@ -366,8 +366,8 @@ packages:
'@types/node':
optional: true
'@inquirer/password@5.2.4':
resolution: {integrity: sha512-T7ir3fflSSVCYEVqNyMBq+pIMsilQRtbZcD5gxn6Ewsin5TJWBxrGBdXveWtmeXVAeoInfhS+BhBUZaL4sFSDg==}
'@inquirer/password@5.2.5':
resolution: {integrity: sha512-0v0wLQA4uhWbybmdH6oPl7ooxCiymNylkvi2gCSc+mA5ZQB6QoJLVhoHq12T82lhozpp9fpMJnJkC1nJrU/A+A==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
@@ -375,8 +375,8 @@ packages:
'@types/node':
optional: true
'@inquirer/prompts@8.7.4':
resolution: {integrity: sha512-SAJt+QhY5rOJAIgZBw9TrHWfgrp6wsb9cqRCyqax+Hl6EiFfRXmD9EsIWkST8yq/dQ8H46Is2Sr/JG7Ls/LQ+Q==}
'@inquirer/prompts@8.7.5':
resolution: {integrity: sha512-l/IWwC+QhOyXgxkZloOh+n5quGzc1m5ZawyzBmoizCZaxbJeLRdS3pStoqg/JVInJRXaG5aHMhjK6H6oYiBC9A==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
@@ -384,8 +384,8 @@ packages:
'@types/node':
optional: true
'@inquirer/rawlist@5.3.7':
resolution: {integrity: sha512-XveEe8v3BHj9ec00n+9i8FHjWhXjS6+jCTizYvXCqKUKtgkrq9xid8S5j3mYGW96qfxG3mwNoud3m3v8GDk9Pw==}
'@inquirer/rawlist@5.3.8':
resolution: {integrity: sha512-h+6Y4pPvYvuRbksn1kIBdD9tCYD+E468W5sIcVfLmoLP5IasnY0r33N+r+46ej/P8b2PCREjyKR+MnnfPGdTzg==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
@@ -393,8 +393,8 @@ packages:
'@types/node':
optional: true
'@inquirer/search@4.3.5':
resolution: {integrity: sha512-kIUecMugEN2YTvTmff+uYz0nAE0f9RFNDVZknfrh264vAQM9P8tnsXiUp7z8XbGuNIBEtFMJhvc9QquawpC46A==}
'@inquirer/search@4.3.6':
resolution: {integrity: sha512-JZj9ttkIvuaFQIc2oxsyqC1ad05WL02ku6W/INVKTCzNaVq1KkhP3AfTRC0m7OWlKZyw+EWwPBFZfYiG9jF6Yw==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
@@ -402,8 +402,8 @@ packages:
'@types/node':
optional: true
'@inquirer/select@5.2.7':
resolution: {integrity: sha512-pRDWO4dTqSAvFQdO8yclKMtXNDm9K9HmvWB5UZmT3clw2OlOBNXveHzhyFmO/0d0yJMqlPcNITus1Jtpm6t8VQ==}
'@inquirer/select@5.2.8':
resolution: {integrity: sha512-BklkkAAOpjdCfuQw5fVGcDuhKxA7T1iBpn6b2JUvDDdkIsO3Ftlg+WnWUCVpkUBFagL2o036OFW+xL4lC9wIPw==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
@@ -411,8 +411,8 @@ packages:
'@types/node':
optional: true
'@inquirer/type@4.2.0':
resolution: {integrity: sha512-2rnHX8RPo4glJYqnFc/v3nQeIhDcjyRRyaT7MGcfL/8xv/8K03SXYoA2tX06WVSKywWOE/ncbG3dtuzLjR5TCQ==}
'@inquirer/type@4.2.1':
resolution: {integrity: sha512-lDkPsnv5M5CcYB2T1qTc3dobNTPkVr4DU3Ic2Q6SW8/qVRHgvzdRdmVZ6YqG9Ag1aJTeMsLU0s0WPRh3CZWDQQ==}
engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
@@ -597,8 +597,8 @@ packages:
'@types/lodash@4.17.25':
resolution: {integrity: sha512-+K1NIO8I+F9/wNulfVvu23QYd0Pe9/OCqRrim4NoYIf1VoEDL90Ve4ClzpyqBLc7NpGGWRvYNCKZ1BE/Jpf8dQ==}
'@types/node@26.6.5':
resolution: {integrity: sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==}
'@types/node@26.6.6':
resolution: {integrity: sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==}
'@types/papaparse@5.5.2':
resolution: {integrity: sha512-gFnFp/JMzLHCwRf7tQHrNnfhN4eYBVYYI897CGX4MY1tzY9l2aLkVyx2IlKZ/SAqDbB3I1AOZW5gTMGGsqWliA==}
@@ -1192,124 +1192,124 @@ snapshots:
dependencies:
graphql: 17.0.2
'@inquirer/ansi@2.0.9': {}
'@inquirer/ansi@2.0.10': {}
'@inquirer/checkbox@5.2.7(@types/node@26.6.5)':
'@inquirer/checkbox@5.2.8(@types/node@26.6.6)':
dependencies:
'@inquirer/ansi': 2.0.9
'@inquirer/core': 12.0.5(@types/node@26.6.5)
'@inquirer/figures': 2.0.9
'@inquirer/type': 4.2.0(@types/node@26.6.5)
'@inquirer/ansi': 2.0.10
'@inquirer/core': 12.0.6(@types/node@26.6.6)
'@inquirer/figures': 2.0.10
'@inquirer/type': 4.2.1(@types/node@26.6.6)
optionalDependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
'@inquirer/confirm@6.3.4(@types/node@26.6.5)':
'@inquirer/confirm@6.3.5(@types/node@26.6.6)':
dependencies:
'@inquirer/core': 12.0.5(@types/node@26.6.5)
'@inquirer/type': 4.2.0(@types/node@26.6.5)
'@inquirer/core': 12.0.6(@types/node@26.6.6)
'@inquirer/type': 4.2.1(@types/node@26.6.6)
optionalDependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
'@inquirer/core@12.0.5(@types/node@26.6.5)':
'@inquirer/core@12.0.6(@types/node@26.6.6)':
dependencies:
'@inquirer/ansi': 2.0.9
'@inquirer/figures': 2.0.9
'@inquirer/type': 4.2.0(@types/node@26.6.5)
'@inquirer/ansi': 2.0.10
'@inquirer/figures': 2.0.10
'@inquirer/type': 4.2.1(@types/node@26.6.6)
cli-width: 4.1.0
fast-wrap-ansi: 0.2.2
mute-stream: 3.0.0
signal-exit: 4.1.0
optionalDependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
'@inquirer/editor@5.3.5(@types/node@26.6.5)':
'@inquirer/editor@5.3.6(@types/node@26.6.6)':
dependencies:
'@inquirer/core': 12.0.5(@types/node@26.6.5)
'@inquirer/external-editor': 3.0.6(@types/node@26.6.5)
'@inquirer/type': 4.2.0(@types/node@26.6.5)
'@inquirer/core': 12.0.6(@types/node@26.6.6)
'@inquirer/external-editor': 3.0.7(@types/node@26.6.6)
'@inquirer/type': 4.2.1(@types/node@26.6.6)
optionalDependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
'@inquirer/expand@5.1.7(@types/node@26.6.5)':
'@inquirer/expand@5.1.8(@types/node@26.6.6)':
dependencies:
'@inquirer/core': 12.0.5(@types/node@26.6.5)
'@inquirer/type': 4.2.0(@types/node@26.6.5)
'@inquirer/core': 12.0.6(@types/node@26.6.6)
'@inquirer/type': 4.2.1(@types/node@26.6.6)
optionalDependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
'@inquirer/external-editor@3.0.6(@types/node@26.6.5)':
'@inquirer/external-editor@3.0.7(@types/node@26.6.6)':
dependencies:
chardet: 2.2.0
iconv-lite: 0.7.3
optionalDependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
'@inquirer/figures@2.0.9': {}
'@inquirer/figures@2.0.10': {}
'@inquirer/input@5.1.8(@types/node@26.6.5)':
'@inquirer/input@5.1.9(@types/node@26.6.6)':
dependencies:
'@inquirer/core': 12.0.5(@types/node@26.6.5)
'@inquirer/type': 4.2.0(@types/node@26.6.5)
'@inquirer/core': 12.0.6(@types/node@26.6.6)
'@inquirer/type': 4.2.1(@types/node@26.6.6)
optionalDependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
'@inquirer/number@4.2.5(@types/node@26.6.5)':
'@inquirer/number@4.2.6(@types/node@26.6.6)':
dependencies:
'@inquirer/core': 12.0.5(@types/node@26.6.5)
'@inquirer/type': 4.2.0(@types/node@26.6.5)
'@inquirer/core': 12.0.6(@types/node@26.6.6)
'@inquirer/type': 4.2.1(@types/node@26.6.6)
optionalDependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
'@inquirer/password@5.2.4(@types/node@26.6.5)':
'@inquirer/password@5.2.5(@types/node@26.6.6)':
dependencies:
'@inquirer/ansi': 2.0.9
'@inquirer/core': 12.0.5(@types/node@26.6.5)
'@inquirer/type': 4.2.0(@types/node@26.6.5)
'@inquirer/ansi': 2.0.10
'@inquirer/core': 12.0.6(@types/node@26.6.6)
'@inquirer/type': 4.2.1(@types/node@26.6.6)
optionalDependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
'@inquirer/prompts@8.7.4(@types/node@26.6.5)':
'@inquirer/prompts@8.7.5(@types/node@26.6.6)':
dependencies:
'@inquirer/checkbox': 5.2.7(@types/node@26.6.5)
'@inquirer/confirm': 6.3.4(@types/node@26.6.5)
'@inquirer/editor': 5.3.5(@types/node@26.6.5)
'@inquirer/expand': 5.1.7(@types/node@26.6.5)
'@inquirer/input': 5.1.8(@types/node@26.6.5)
'@inquirer/number': 4.2.5(@types/node@26.6.5)
'@inquirer/password': 5.2.4(@types/node@26.6.5)
'@inquirer/rawlist': 5.3.7(@types/node@26.6.5)
'@inquirer/search': 4.3.5(@types/node@26.6.5)
'@inquirer/select': 5.2.7(@types/node@26.6.5)
'@inquirer/checkbox': 5.2.8(@types/node@26.6.6)
'@inquirer/confirm': 6.3.5(@types/node@26.6.6)
'@inquirer/editor': 5.3.6(@types/node@26.6.6)
'@inquirer/expand': 5.1.8(@types/node@26.6.6)
'@inquirer/input': 5.1.9(@types/node@26.6.6)
'@inquirer/number': 4.2.6(@types/node@26.6.6)
'@inquirer/password': 5.2.5(@types/node@26.6.6)
'@inquirer/rawlist': 5.3.8(@types/node@26.6.6)
'@inquirer/search': 4.3.6(@types/node@26.6.6)
'@inquirer/select': 5.2.8(@types/node@26.6.6)
optionalDependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
'@inquirer/rawlist@5.3.7(@types/node@26.6.5)':
'@inquirer/rawlist@5.3.8(@types/node@26.6.6)':
dependencies:
'@inquirer/core': 12.0.5(@types/node@26.6.5)
'@inquirer/type': 4.2.0(@types/node@26.6.5)
'@inquirer/core': 12.0.6(@types/node@26.6.6)
'@inquirer/type': 4.2.1(@types/node@26.6.6)
optionalDependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
'@inquirer/search@4.3.5(@types/node@26.6.5)':
'@inquirer/search@4.3.6(@types/node@26.6.6)':
dependencies:
'@inquirer/core': 12.0.5(@types/node@26.6.5)
'@inquirer/figures': 2.0.9
'@inquirer/type': 4.2.0(@types/node@26.6.5)
'@inquirer/core': 12.0.6(@types/node@26.6.6)
'@inquirer/figures': 2.0.10
'@inquirer/type': 4.2.1(@types/node@26.6.6)
optionalDependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
'@inquirer/select@5.2.7(@types/node@26.6.5)':
'@inquirer/select@5.2.8(@types/node@26.6.6)':
dependencies:
'@inquirer/ansi': 2.0.9
'@inquirer/core': 12.0.5(@types/node@26.6.5)
'@inquirer/figures': 2.0.9
'@inquirer/type': 4.2.0(@types/node@26.6.5)
'@inquirer/ansi': 2.0.10
'@inquirer/core': 12.0.6(@types/node@26.6.6)
'@inquirer/figures': 2.0.10
'@inquirer/type': 4.2.1(@types/node@26.6.6)
optionalDependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
'@inquirer/type@4.2.0(@types/node@26.6.5)':
'@inquirer/type@4.2.1(@types/node@26.6.6)':
optionalDependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
'@jsdevtools/ono@7.1.3': {}
@@ -1456,13 +1456,13 @@ snapshots:
'@types/lodash@4.17.25': {}
'@types/node@26.6.5':
'@types/node@26.6.6':
dependencies:
undici-types: 8.9.0
'@types/papaparse@5.5.2':
dependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
'@types/react@19.3.0':
dependencies:
@@ -1472,7 +1472,7 @@ snapshots:
'@types/yauzl@3.4.0':
dependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
'@typescript/typescript-aix-ppc64@7.0.2':
optional: true
@@ -1561,7 +1561,7 @@ snapshots:
bun-types@1.4.4:
dependencies:
'@types/node': 26.6.5
'@types/node': 26.6.6
undici-types: 8.9.0
chalk@6.0.1: {}
@@ -0,0 +1,56 @@
import { build } from "esbuild";
import { valid } from "semver";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
const output = "dist/server/embedding-tokenizer";
const bundle = await build({
entryPoints: ["src/server/embedding-tokenizer.ts"],
outfile: output + ".js",
bundle: true,
format: "esm",
platform: "node",
sourcemap: true,
sourcesContent: false,
metafile: true,
});
// Inventory the modules actually included. pnpm can nest multiple node_modules
// directories, including different versions of the same package.
const roots = new Set();
for (const path of Object.keys(bundle.metafile.inputs)) {
const dependency = /^(.*\bnode_modules\/(?:@[^/]+\/)?[^/]+)\//u.exec(path);
if (dependency) roots.add(dependency[1]);
}
const components = [];
const required = new Set(["base64-js", "js-tiktoken"]);
for (const directory of [...roots].sort()) {
const { name, version, license } = JSON.parse(
await readFile(join(directory, "package.json"), "utf8"),
);
if (!required.delete(name) || !valid(version) || license !== "MIT") {
throw new Error(
`Review the tokenizer's bundled component ${name}@${version} (${license}).`,
);
}
components.push({
type: "library",
name,
version,
purl: `pkg:npm/${name}@${encodeURIComponent(version)}`,
licenses: [{ license: { id: license } }],
});
}
if (required.size) {
throw new Error(
`Missing tokenizer bundle inputs: ${[...required].join(", ")}.`,
);
}
await writeFile(
output + ".cdx.json",
JSON.stringify(
{ bomFormat: "CycloneDX", specVersion: "1.6", version: 1, components },
null,
2,
) + "\n",
);
@@ -158,6 +158,7 @@ const distModules = [
"saved-scan",
"saved-scan-bootstrap",
"scan-skill-paths",
"server/embedding-tokenizer",
"server/embeddings",
"server/errors",
"server/sqlite-store",
@@ -173,8 +174,11 @@ const distModules = [
"worker-progress",
];
export const packageDistFiles = distModules.flatMap((module) =>
["js", "js.map", "d.ts", "d.ts.map"].map(
(extension) => `package/dist/${module}.${extension}`,
export const packageDistFiles = [
"package/dist/server/embedding-tokenizer.cdx.json",
...distModules.flatMap((module) =>
["js", "js.map", "d.ts", "d.ts.map"].map(
(extension) => `package/dist/${module}.${extension}`,
),
),
);
];
+33
View File
@@ -1,5 +1,6 @@
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import {
chmod,
cp,
@@ -437,6 +438,38 @@ try {
{ cwd: consumer },
);
const { OpenAiFindingEmbedder } = await import(
pathToFileURL(join(installedRoot, "dist/server/api.js")).href
);
const finding = { description: "🔒 café 中文 ".repeat(1800) };
const chunks = [];
const embedder = new OpenAiFindingEmbedder(
"synthetic",
async (_url, init) => {
const { model, dimensions, input } = JSON.parse(init.body);
chunks.push(...input);
return Response.json({
model,
data: input.map((_, index) => ({
index,
embedding: Array(dimensions).fill(1),
})),
});
},
);
await embedder.embed([finding]);
assert.deepEqual(
chunks.map((chunk) => chunk.length),
[8192, 813],
);
// Generated with js-tiktoken 1.0.21 using cl100k_base on JSON.stringify(finding).
// The installed-package job runs in a clean checkout with no SDK build dependencies.
assert.equal(
createHash("sha256").update(JSON.stringify(chunks.flat())).digest("hex"),
"ed8b5af712556ad433415337fcc69ea7a564c89f892855eea729c6d5c49bcf04",
"Installed embedding token IDs differ from the upstream cl100k_base encoding.",
);
await cp(
join(packageRoot, "scripts", "fixtures", "package-consumer.ts"),
join(consumer, "consumer.ts"),
+14 -8
View File
@@ -63,6 +63,8 @@ const LOCK_HEARTBEAT_MS = 5_000;
const WINDOWS_DEVICE_PATH_NAME =
/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu;
class AttemptNumberExhaustedError extends Error {}
type MultiscanTask = ReturnType<typeof parseInventory>[number];
interface MultiscanReceipt extends MultiscanTask {
@@ -349,11 +351,7 @@ async function runCampaign(
continue;
}
if (artifactsPresent) {
if (
receipt.status === "completed" &&
Number.isSafeInteger(receipt.attempt) &&
receipt.attempt > 0
) {
if (receipt.status === "completed") {
try {
if (receipt.cleanupPending === "checkout") {
await rm(join(output, "checkouts", task.id), {
@@ -418,6 +416,13 @@ async function runCampaign(
const knowledge = knowledgeByMode[task.mode];
const history = receipts.get(task.id.toLowerCase());
let maxAttempt = history?.maxAttempt ?? 0;
const nextAttempt = () => {
if (maxAttempt === Number.MAX_SAFE_INTEGER)
throw new AttemptNumberExhaustedError(
`No more attempt numbers are available for ${task.id}. Start a separate campaign in a new --output-dir.`,
);
return ++maxAttempt;
};
let recoveryAttempt = history?.scan?.attempt ?? 0;
const artifactRoot = join(output, "artifacts", task.id);
if (options.recoverScan !== undefined) {
@@ -433,7 +438,7 @@ async function runCampaign(
for (let retry = 0; retry < options.maxAttempts; retry += 1) {
options.signal?.throwIfAborted();
let attempt = maxAttempt;
if (options.recoverScan === undefined) attempt = ++maxAttempt;
if (options.recoverScan === undefined) attempt = nextAttempt();
else if (retry === 0) attempt = recoveryAttempt;
let scanDir = join(artifactRoot, `attempt-${attempt}`);
let checkout: string | undefined;
@@ -495,7 +500,7 @@ async function runCampaign(
}
const scanSettings = options.scanOptionsByMode?.[task.mode];
if (result === undefined) {
if (options.recoverScan !== undefined) attempt = ++maxAttempt;
if (options.recoverScan !== undefined) attempt = nextAttempt();
scanDir = join(artifactRoot, `attempt-${attempt}`);
notifyProgress(options, {
repository: task.id,
@@ -591,6 +596,7 @@ async function runCampaign(
if (result.manifest.scan.status !== "completed")
throw new Error(`Multiscan scan ${result.manifest.scan.status}.`);
} catch (error) {
if (error instanceof AttemptNumberExhaustedError) throw error;
if (options.signal?.aborted === true) options.signal.throwIfAborted();
if (error instanceof ScanCostLimitExceededError) {
cost = error.cost;
@@ -1067,7 +1073,7 @@ async function readReceipts(
if (typeof saved?.id !== "string" || !saved.id.trim())
throw new Error("Expected a receipt with a nonempty string id");
if (!Number.isSafeInteger(saved.attempt) || saved.attempt < 1)
throw new Error("Expected a positive safe integer attempt");
throw new Error("Expected a positive integer receipt attempt");
if (saved.status === "completed_with_incomplete_coverage")
saved.status = "completed";
if (saved.status !== "completed" && saved.status !== "failed")
@@ -0,0 +1,31 @@
/*!
* MIT License
*
* js-tiktoken: Copyright (c) 2022 OpenAI, Shantanu Jain
* base64-js: Copyright (c) 2014 Jameson Little
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { Tiktoken } from "js-tiktoken/lite";
import cl100kBase from "js-tiktoken/ranks/cl100k_base";
export function createEmbeddingEncoder(): (text: string) => number[] {
const encoding = new Tiktoken(cl100kBase);
return (text) => encoding.encode(text, [], []);
}
+3 -4
View File
@@ -1,8 +1,7 @@
import { Tiktoken } from "js-tiktoken/lite";
import cl100kBase from "js-tiktoken/ranks/cl100k_base";
import { errorMessage } from "../errors.js";
import type { Finding } from "../models.js";
import { VERSION } from "../version.js";
import { createEmbeddingEncoder } from "./embedding-tokenizer.js";
import { FindingsError } from "./errors.js";
import type { FindingEmbedding } from "./storage.js";
@@ -23,7 +22,7 @@ interface Chunk {
}
export class OpenAiFindingEmbedder implements FindingEmbedder {
private readonly encoding = new Tiktoken(cl100kBase);
private readonly encode = createEmbeddingEncoder();
constructor(
private readonly apiKey:
@@ -51,7 +50,7 @@ export class OpenAiFindingEmbedder implements FindingEmbedder {
let chunks: Chunk[] = [];
let requestTokens = 0;
for (const [findingIndex, finding] of findings.entries()) {
const tokens = this.encoding.encode(JSON.stringify(finding), [], []);
const tokens = this.encode(JSON.stringify(finding));
for (let start = 0; start < tokens.length; start += MAX_INPUT_TOKENS) {
const chunk = tokens.slice(start, start + MAX_INPUT_TOKENS);
if (
@@ -0,0 +1,26 @@
import { execFile } from "node:child_process";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect, test } from "bun:test";
test("rejects a tokenizer build with no inventoried packages", async () => {
const root = await mkdtemp(join(tmpdir(), "embedding-tokenizer-"));
try {
await mkdir(join(root, "src/server"), { recursive: true });
await writeFile(
join(root, "src/server/embedding-tokenizer.ts"),
"export {};",
);
const build = fileURLToPath(
new URL("../scripts/build-embedding-tokenizer.mjs", import.meta.url),
);
await expect(
promisify(execFile)("node", [build], { cwd: root }),
).rejects.toThrow("Missing tokenizer bundle inputs");
} finally {
await rm(root, { recursive: true, force: true });
}
});
@@ -546,7 +546,7 @@ describe("multiscan", () => {
);
await expect(runMultiscan(configured)).rejects.toThrow(
`${ledger}:1: Expected a positive safe integer attempt`,
"Expected a positive integer receipt attempt",
);
expect(scans).toHaveBeenCalledTimes(1);
expect(await readFile(preserved, "utf8")).toBe("preserved\n");
@@ -515,10 +515,12 @@ describe("multiscan", () => {
["non-object", "null", false],
["missing ID", "{}", false],
["non-string ID", '{"id":42}', false],
["known repository with a missing attempt", { attempt: undefined }, false],
["zero attempt", { attempt: 0 }, false],
["unsafe attempt", { attempt: Number.MAX_SAFE_INTEGER + 1 }, false],
["unknown status", { status: "pending" }, false],
["missing attempt", '{"id":"receipt"}', false],
["string attempt", '{"id":"receipt","attempt":"1"}', false],
["zero attempt", '{"id":"receipt","attempt":0}', false],
["fractional attempt", '{"id":"receipt","attempt":1.5}', true],
["blank ID", { id: " " }, false],
["unknown status", { status: "pending" }, true],
["missing output directory", { outputDir: undefined }, false],
["non-boolean knowledge failure", { knowledgeBaseFailure: "false" }, false],
["non-boolean policy outcome", { policyFailed: "true" }, false],
@@ -535,35 +537,30 @@ describe("multiscan", () => {
];
const deps = dependencies();
const run = mock(completeRun);
const runWorkbench = mock(deps.runWorkbench);
const configured: Parameters<typeof main>[3] = {
...deps,
runWorkbench,
createSecurity: (config) => ({ ...deps.createSecurity(config), run }),
};
expect(await createCliTest(main).runCli(args, configured)).toBe(0);
const ledger = join(paths.output, "results.jsonl");
const valid = await readFile(ledger, "utf8");
const artifactRoot = join(paths.output, "artifacts", "receipt");
const report = join(artifactRoot, "attempt-1", "report.md");
const report = join(
paths.output,
"artifacts",
"receipt",
"attempt-1",
"report.md",
);
const originalReport = await readFile(report);
const record =
typeof bad === "string"
? bad
: JSON.stringify({
...JSON.parse(valid),
status: "failed",
attempt: 2,
outputDir: join(artifactRoot, "attempt-2"),
...bad,
});
: JSON.stringify({ ...JSON.parse(valid), attempt: 2, ...bad });
const damaged = Buffer.concat([
Buffer.from(`${valid}\n${record}\n`),
...(middle ? [Buffer.from(valid), Buffer.from([0xe2, 0x82])] : []),
]);
await writeFile(ledger, damaged);
const campaignFiles = (await readdir(paths.output)).sort();
runWorkbench.mockClear();
for (const flags of [[], ["--recover"]]) {
const cli = createCliTest(main);
expect(await cli.runCli([...args, ...flags], configured)).toBe(2);
@@ -573,12 +570,50 @@ describe("multiscan", () => {
expect(cli.stderr.text()).toContain("Restore a complete");
expect(cli.stderr.text()).toContain("new --output-dir");
expect(await readFile(ledger)).toEqual(damaged);
expect((await readdir(paths.output)).sort()).toEqual(campaignFiles);
expect(await readdir(artifactRoot)).toEqual(["attempt-1"]);
expect(await readFile(report)).toEqual(originalReport);
expect(
(await readdir(paths.output)).filter((name) =>
name.startsWith("results.jsonl.interrupted-"),
),
).toEqual([]);
}
expect(run).toHaveBeenCalledTimes(1);
expect(runWorkbench).not.toHaveBeenCalled();
},
);
test.each(["rerun", "recover receipt", "recover directory"])(
"preserves exhausted attempt numbers on %s",
async (mode) => {
const { paths } = await repositoryFixture("repo");
const setup = options(paths, client(rejecting("Initial failure")), {
maxAttempts: 1,
});
const { resultsPath: ledger } = await runMultiscan(setup);
const root = join(paths.output, "artifacts", "repo");
const last = join(root, `attempt-${Number.MAX_SAFE_INTEGER}`);
if (mode === "recover directory") {
await mkdir(last);
} else {
const [receipt] = await results(ledger);
await writeFile(
ledger,
JSON.stringify({
...receipt,
attempt: Number.MAX_SAFE_INTEGER,
outputDir: last,
}) + "\n",
);
}
const saved = await readFile(ledger, "utf8");
const directories = await readdir(root);
const run = mock(completeRun);
const configured = options(paths, client(run), {
...(mode === "rerun" ? {} : { recoverScan: async () => undefined }),
});
await expect(runMultiscan(configured)).rejects.toThrow("attempt numbers");
expect(run).not.toHaveBeenCalled();
expect(await readFile(ledger, "utf8")).toBe(saved);
expect(await readdir(root)).toEqual(directories);
},
);
@@ -1863,11 +1898,12 @@ describe("multiscan", () => {
const checkout = join(paths.output, "checkouts", "invalid-recovery");
await mkdir(checkout, { recursive: true, mode: 0o700 });
await writeFile(join(checkout, "retained.txt"), "Original checkout.");
const nextAttempt = newerAttempt ? Number.MAX_SAFE_INTEGER : 2;
const nextOutput = join(
paths.output,
"artifacts",
"invalid-recovery",
"attempt-2",
`attempt-${nextAttempt}`,
);
if (newerAttempt) await completedScan(nextOutput);
const recoverScan = mock(async (path: string) => ({
@@ -1895,7 +1931,7 @@ describe("multiscan", () => {
);
expect((await results(summary.resultsPath)).at(-1)).toMatchObject({
status: "completed",
attempt: 2,
attempt: nextAttempt,
});
},
);