Merge main into contributor PR #2051

This commit is contained in:
Codex
2026-11-01 22:34:36 +00:00
123 changed files with 6081 additions and 8675 deletions
+3 -3
View File
@@ -17,8 +17,8 @@ Use its security workflows in Codex, or automate them with the
- Draft `SECURITY.md` policies and save threat models for later review.
- Browse saved scans and findings, identify duplicates, assess severity against
your own rubric, and suggest owners from source and Git history.
- Import GitHub code scanning alerts, export SARIF, JSON, or CSV, and publish
findings to Linear or a findings service.
- Import Semgrep, Snyk, and Wiz findings locally or publish them to Codex Security Cloud. [All scanner import guides](docs/scanner-imports/README.md).
- Export SARIF, JSON, or CSV, and publish findings to Linear or a findings service.
- Automate scans across repositories or project components, including in CI and
containers.
@@ -272,7 +272,7 @@ for examples.
- [Online documentation](https://learn.chatgpt.com/docs/security/cli)
- [Agent workflows and recovery](docs/agent-workflows.md)
- [CLI reference](sdk/typescript/docs/cli.md)
- [Scanner file import schema and capability guide](docs/scanner-imports/schema-guide.md)
- [Imported finding identity and evidence](docs/scanner-imports/schema-guide.md)
- [Project configuration](docs/project-configuration.md)
- [Examples](examples/README.md)
+13 -6
View File
@@ -1,12 +1,19 @@
# Plugin connectors
Codex Security uses optional connected apps for ticket intake and finding tracking. Their identities are declared in `plugins/codex-security/.app.json`.
Codex Security uses optional connected apps for Cloud reads, finding intake
and tracking. The [app manifest](../plugins/codex-security/.app.json)
declares their identities.
| App | Workflows |
| --------- | ------------------------------------------------- |
| Linear | Ticket intake and finding tracking |
| GitHub | Finding intake, source lookup, and issue tracking |
| Atlassian | Jira Cloud ticket intake and finding tracking |
| App | Workflows |
| -------------------- | --------------------------------------------------------- |
| Codex Security Cloud | Read existing findings, evidence, reports and scan status |
| Linear | Ticket intake and finding tracking |
| GitHub | Finding intake, source lookup and issue tracking |
| Atlassian | Jira Cloud ticket intake and finding tracking |
For scanner imports, use a connected tool or signed-in CLI to obtain the
requested records. Follow the [scanner import guide](scanner-imports/README.md)
to select and preview the evidence for your destination.
Finding tracking and CLI publication share issue associations when they use the same local state directory, including reuse across scan occurrences. The tracking skill reads them with `get_codex_security_finding_issues` and records accepted writes or verified reuse with `record_codex_security_finding_issues`. Provider reads still confirm saved candidates and search for unrecorded duplicates. Accepted writes remain recorded even when follow-up reads fail. The tools accept sealed scan bundles without requiring their original local scan history and keep receipts outside those bundles.
+86
View File
@@ -0,0 +1,86 @@
# Import external scanner findings
Choose the guide for your report. Each guide shows how to preview the findings
in a local checkout and which source key to reuse on later imports.
Use a supported report or retrieve the full records for the requested repository
and ref with a connected tool or signed-in CLI. Fetch selected IDs directly when
the provider supports it. If a saved report or collector covers more findings,
use the provider's selection controls or retain only the selected native records
where the report format permits. Check the accepted findings and their evidence
in the JSON preview against the requested selection before saving or publishing.
Use an API response only for an input and destination supported by the provider
guide. Otherwise, ask for a supported report. A fresh scan produces new results.
| Guide | Supported input |
| ----------------------------------------------------------- | ------------------------------------------------------------------------------- |
| [Amazon Inspector](inspector.md) | Inspector2 `ListFindings` JSON for one Code Security repository |
| [Black Duck SCA](blackduck.md) | BOM component vulnerabilities for one project version |
| [Endor Labs](endor.md) | Finding JSON from `endorctl`, or SARIF with finding UUIDs |
| [GitHub code scanning](github-code-scanning.md) | Alerts selected for one repository and Git ref |
| [GitHub Dependabot](github-dependabot.md) | Dependency alerts exported from one repository |
| [GitHub Security Advisories](github-security-advisories.md) | Selected repository or global advisories |
| [OpenGrep](opengrep.md) | Native scan JSON, optionally gzip-compressed |
| [Semgrep Code](semgrep.md) | CLI/CI JSON, self-contained SARIF, or selected Platform API pages (local SDK) |
| [Snyk Open Source](snyk.md) | CLI JSON, a Codex plugin export, or SARIF |
| [SonarQube Cloud](sonar.md) | Issues selected with the signed-in Sonar CLI, or saved issue-search pages |
| [Veracode Static Analysis](veracode.md) | Findings API pages for one application's policy flaws |
| [Wiz](wiz.md) | Native JSON, normalized JSONL, or detailed repository package vulnerability CSV |
## Preview a report
Enable external imports in the shell where you run the CLI.
```sh
export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1
```
In PowerShell, use `$env:CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS = '1'`.
Follow your guide's quick start to collect or select the report. Run examples
that use `--repository .` from the checkout root, or pass the same checkout
path you used previously. Use `--dry-run` to review the repository, source key,
findings, and exclusions.
Keep the export private. In automation, direct stdout and stderr for collection,
preview, confirmation, and readback to private files outside the checkout.
For examples that use `mktemp -d` without a path, set `TMPDIR` to a private
directory outside the checkout if temporary files would otherwise land inside it.
## Save or publish and verify
The steps below apply to `publish findings FILE`. For `import sonar`,
[confirm the capture returned by the Sonar preview](sonar.md#import-and-verify).
**Local workbench.** Run the same command with the same file, checkout, and
source key. Remove `--dry-run` and confirm the prompt.
For noninteractive use, add `--yes` after reviewing that preview. Read back
the stored evidence using the checkout path from the preview:
```sh
codex-security findings imported /path/to/project --format json
```
**Codex Security Cloud.** Use a file-backed ChatGPT login for a deployment that
accepts the provider and a repository environment you can publish to. See
[Cloud setup](../../sdk/typescript/docs/cli.md#preview-and-publish). Keep the
file, provider, source key, and scanner-specific options. Set `--to cloud` and
replace the local checkout in `--repository` with the connected repository URL
or Cloud repository ID. Use the ID if several connectors share the URL.
Run with `--dry-run` first. Check that `cloudApiUrl`
is the intended API endpoint, then review the account, repository, environments,
and exclusions. Remove `--dry-run` and confirm, or use `--yes` after that
review. Check `status`, the `verified` and
`unacknowledged` counts, and the `failures` and `excluded` lists. For a `partial`
result, correct exclusions or resolve version conflicts before starting a new
submission. If an `interrupted` result includes `savedSubmission`,
[resume from that checkpoint](schema-guide.md#retry-a-cloud-submission).
## Work with imported findings
Imported records start with assessment state `not_assessed`. Use the source
evidence to check whether a finding affects your repository. For the identity
of a record, the fields each reader retains, and how repeat imports update
evidence, see [Imported finding identity and evidence](schema-guide.md).
For findings from a completed Codex scan, see
[Track findings in Linear, Jira, or GitHub](../../plugins/codex-security/skills/track-findings/SKILL.md)
or [Export findings for ServiceNow](../../sdk/typescript/docs/cli.md#export-findings-for-servicenow).
+64 -63
View File
@@ -1,28 +1,73 @@
# Import Black Duck SCA repository vulnerabilities
# Import Black Duck SCA findings
Use `--provider blackduck` to import vulnerable BOM components from one Black Duck
SCA project version. Check the scan configuration to confirm which Git repository
the project version represents. Project names, API hosts and component download
URLs cannot establish that mapping. Aggregate product BOMs, image-only scans,
license violations and global advisory catalogs are outside this import.
Import vulnerable BOM components from one Black Duck SCA project version.
Verify in the scan configuration which Git repository that version represents.
## Export a complete collection
## Quick start
Use a read-only token and request the project version’s `vulnerable-components`
relation with media type `application/vnd.blackducksoftware.bill-of-materials-6+json`.
The importer requires BOM-6. If the deployment serves only BOM-8 or another
inventory format, stop the export.
[Enable external imports](README.md#preview-a-report) and use a read-only token to
[export the BOM-6 collection](#export-the-bom-6-collection). From the matching
checkout root, preview the saved file with the verified Git URL and a source key
for this deployment, project, and version.
```sh
codex-security publish findings /private/path/blackduck.json \
--to local --repository . --provider blackduck \
--source-repository-url https://github.com/example/project \
--source-key blackduck/deployment-alias/project-id/version-id \
--dry-run --format json
```
## Import and verify
Check the source Git URL against the checkout’s configured remotes or the
authorized GitHub repository in Cloud. A project name or component download
URL alone cannot establish that link.
[Save or publish and verify](README.md#save-or-publish-and-verify) using the same
source key for subsequent exports of this project version.
## Reference
### Identity and evidence
Each occurrence is identified by its project version, component version,
origin, advisory source, and advisory name. Package URLs and origin coordinates
supply the package identity. The `advisory_ids` field preserves
`vulnerabilityName` and any distinct `relatedVulnerability` verbatim, including
Black Duck resource URLs. The original row retains its CWE, matched-files link,
and remediation status. Imported records start unassessed. The importer does
not infer a fix, Git revision, or source location. Aggregate product BOMs,
image-only scans, license violations, and global advisory catalogs are outside
this import.
For SDK imports, select the `blackduck` provider when replaying retained BOM
records. Reader-supplied repository references must agree with the repository
on local findings. Opaque IDs and caller-authored text alone cannot establish
repository ownership.
### Export the BOM-6 collection
The [Black Duck SCA MCP](https://github.com/blackducksoftware/sca-mcp#capabilities)
can locate the project version with `search_projects_versions`. Its
`fetch_project_vulnerabilities` tool returns a summary and CSV. Use the REST
export below for BOM rows. The MCP’s `scan` starts a new scan. Coverity and
Polaris reports use different formats.
Request the project version’s `vulnerable-components` relation with media type
`application/vnd.blackducksoftware.bill-of-materials-6+json`. The importer
requires BOM-6. If the deployment only serves BOM-8 or another inventory format,
it cannot supply this collection.
Install the vendor’s `blackduck` Python client in a trusted virtual environment
outside the checkout. Set `BLACKDUCK_URL` to the deployment’s HTTPS URL,
`BLACKDUCK_TOKEN` to the read-only token and `BLACKDUCK_PROJECT_ID` and
`BLACKDUCK_VERSION_ID` to the two UUIDs. The client exchanges the token before
reading the collection, so disable redirects for the entire session.
`BLACKDUCK_TOKEN` to the read-only token, and `BLACKDUCK_PROJECT_ID` and
`BLACKDUCK_VERSION_ID` to their UUIDs. Keep redirects disabled for the client
session, including the token exchange.
Save the script outside the checkout and run it with
`/path/to/venv/bin/python -I /private/path/export.py` to keep checkout modules
and `PYTHONPATH` off the import path. Redirect stdout to a private temporary file
and rename it after the script succeeds.
and rename it to `blackduck.json` after the script succeeds.
```python
import json
@@ -91,51 +136,7 @@ print(json.dumps({"_meta": {"href": url}, "totalCount": total, "items": items}))
```
Keep the original rows and collection total. If the BOM changes during offset
pagination, export it again after the scan finishes. To import only selected
occurrences, supply an array of native rows that each identify the same project
version.
## Preview and repeat
```bash
export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1
codex-security publish findings blackduck.json \
--to local --repository ./project --provider blackduck \
--source-repository-url https://github.com/example/project \
--source-key blackduck/deployment-alias/project-id/version-id \
--dry-run --format json
```
Check the source, destination and excluded rows before repeating the command
without `--dry-run`. Reuse the source key for later exports from this deployment,
project and version. For Cloud, select an authorized GitHub repository with
`--to cloud` on a deployment that accepts `blackduck`. Reading a saved report
requires no Black Duck login. Local imports also require no Cloud login.
If an interrupted Cloud upload reports `result.savedSubmission`, keep its
checkpoint and use the same build, state directory, account and import settings.
Preview the original export with `--dry-run --format json`. Check `accountId`
and `destination`. When `resumed` is false, review the new upload before approving it.
For `prepareNormalizedExternalPublication`, pass your original normalized
`ExternalFindings` and check `preview.resumed` before calling `publish()`.
Different normalized findings prepare a new upload.
Cloud checks retained and declared source repository URLs against the selected
repository. For local SDK imports, reader-supplied repository references must
agree with the repository on the findings. Local imports also check comparable
Git remotes on the selected checkout. Select the `blackduck` provider for
retained Black Duck BOM records. Caller-authored text and opaque IDs alone
cannot establish repository ownership.
Each occurrence is identified by its project version, component version, origin,
advisory source and advisory name. Reimporting updates the occurrence when its
evidence changes. Rows absent from a later export remain open.
Supported package URLs and origin coordinates supply the package identity.
`advisory_ids` preserves the vendor’s `vulnerabilityName` and any distinct
`relatedVulnerability` value verbatim, including Black Duck resource URLs.
The native row retains its CWE, matched-files link and remediation status.
Findings start unassessed, with no inferred fix, Git revision or source location.
References: [official Python REST client](https://github.com/blackducksoftware/hub-rest-api-python),
[vendor example of vulnerable BOM components](https://github.com/blackducksoftware/hub-client-go/blob/5f78f7257c00fe9cebabf1bf89a6fc36a4d1f095/hubapi/testdata/vulnerableBomComponents.json).
pagination, export it again after the scan finishes. For a selection, supply
an array of native rows that each identify the same project version. See the
[Black Duck Python client](https://github.com/blackducksoftware/hub-rest-api-python)
and its [vulnerable BOM component example](https://github.com/blackducksoftware/hub-client-go/blob/5f78f7257c00fe9cebabf1bf89a6fc36a4d1f095/hubapi/testdata/vulnerableBomComponents.json).
+59 -67
View File
@@ -1,85 +1,77 @@
# Import Endor Labs findings
Vendor finding import and readback require `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1`.
See the [opt-in instructions](../../sdk/typescript/docs/cli.md#import-vendor-findings-locally)
and [how saved scanner reports map to imported evidence](schema-guide.md).
Import findings from one Endor Labs project and scan context. Native Finding
JSON preserves the scanned commit, severity, and dependency and location
details reported by Endor.
Use authenticated `endorctl` to export complete native Finding JSON through the
[official CLI API](https://docs.endorlabs.com/developers-api/cli/commands/api).
Scope the export to one project and context, omit `--field-mask`, and use
`--list-all` to fetch every page. Replace the namespace and project UUID below
to select the project's default-branch findings:
## Quick start
[Enable external imports](README.md#preview-a-report) and
[export the native findings](#native-finding-json) from the intended project
and context. From the matching checkout root, preview the saved file. Replace
the file path, namespace, and project UUID.
```sh
endorctl api list --resource Finding --namespace "YOUR_NAMESPACE" \
--filter 'context.type==CONTEXT_TYPE_MAIN and spec.project_uuid=="PROJECT_UUID"' \
--list-all --output-type json > endor-findings.json
codex-security publish findings endor-findings.json --to local \
--provider endor --repository ./project \
--source-key "YOUR_NAMESPACE/PROJECT_UUID/main" --dry-run
codex-security publish findings /private/path/endor-findings.json \
--to local --repository . --provider endor \
--source-key "YOUR_NAMESPACE/PROJECT_UUID/main" --dry-run --format json
```
Use `--to local` with a local repository path to store unassessed source evidence
without a Cloud login or model call. After reviewing the preview, remove
`--dry-run` to confirm the import. Read the stored records with
`codex-security findings imported ./project --format json`.
## Import and verify
To publish the same export to Cloud, select its connected repository instead:
Confirm the project and context belong to this repository. The importer retains
the project UUID but does not look up its Git repository.
[Save or publish and verify](README.md#save-or-publish-and-verify) using the same
source key for later exports from this context.
## Reference
### Native Finding JSON
Authenticate `endorctl` for the namespace that owns the project. Replace
`YOUR_NAMESPACE` and `PROJECT_UUID`, then export the findings.
```sh
codex-security publish findings endor-findings.json --to cloud \
--provider endor --repository "CLOUD_REPOSITORY_ID" \
--source-key "YOUR_NAMESPACE/PROJECT_UUID/main" --dry-run
out=$(mktemp -d) &&
endorctl api list --resource Finding --namespace "YOUR_NAMESPACE" \
--filter 'context.type==CONTEXT_TYPE_MAIN and spec.project_uuid=="PROJECT_UUID"' \
--list-all --output-type json > "$out/endor-findings.tmp" &&
mv "$out/endor-findings.tmp" "$out/endor-findings.json"
```
Confirm that the selected Endor project and context correspond to the destination
repository. Native JSON retains the project UUID, but the importer does not look
it up to verify that association. For another branch or scan context, change the
Endor filter and use a distinct, stable source key. An unfinished paginated
response is rejected by the importer. Remove `--dry-run` to review and confirm
the upload.
The filter selects default-branch findings. For another context, change both
the filter and source key. Keep `--list-all` and omit `--field-mask` to export
complete Finding objects. The saved file is `$out/endor-findings.json`.
The official [Endor Labs Agent Kit for Codex](https://github.com/endorlabs/ai-plugins/tree/main/plugins/codex/endor-labs-agent-kit)
can help with setup and interactive investigation. Its Findings Browser summaries,
counts and field-masked results do not replace the complete Finding objects used
here. `endorctl` reads the Endor API; the Codex Security importer reads the saved
export. It does not establish a persistent API connection or write changes back
to Endor.
The importer accepts a single Finding, an array, or a `ListFindingsResponse`
containing `list.objects`. An unfinished paginated response is rejected. Native
JSON retains the complete Finding and maps severity, dependency and advisory
details, scanned commit SHA, and primary SAST or AI SAST locations when
available. See the [Endor CLI API](https://docs.endorlabs.com/developers-api/cli/commands/api)
and [Finding model](https://github.com/endorlabs/endorlabs-sdk/blob/8a41756890c2dee3bb089fee881cae4f2adbde03/src/endorlabs/generated/models/finding_service.py).
Native JSON is the preferred import format: it preserves Endor severity,
dependency and advisory details, the scanned commit SHA, primary SAST/AI SAST
locations, and the complete original Finding. The importer accepts a single
Finding, an array, or a `ListFindingsResponse` containing `list.objects`. Mapping
follows Endor's public [Finding model](https://github.com/endorlabs/endorlabs-sdk/blob/8a41756890c2dee3bb089fee881cae4f2adbde03/src/endorlabs/generated/models/finding_service.py).
The [Endor Labs Agent Kit for Codex](https://github.com/endorlabs/ai-plugins/tree/main/plugins/codex/endor-labs-agent-kit)
can identify UUIDs. For a fresh export, append `and uuid in ["UUID_A","UUID_B"]`
to the project and context filter above, using the requested UUIDs. For a saved
export, select their complete objects from `list.objects`. Before import, verify
the preview contains each requested UUID once, no other IDs, and no exclusions.
[Endor filter syntax](https://docs.endorlabs.com/developers-api/rest-api/using-the-rest-api/filters#values)
Existing self-contained `endorctl` SARIF 2.1.0 reports are accepted as a lossy
compatibility format. The importer retains finding UUIDs and links but does not
infer native Endor severity or scanned revisions from SARIF. Diagnostic levels
and CVSS stay in the original evidence;
displayed severity remains unknown. Direct repository paths and reported SAST or
Secrets lines are mapped. Indexed or base-relative artifact references remain in
the original evidence. Run artifact inventories that are unrelated to the selected
finding are omitted from its evidence. Declared SARIF repository URLs must
match the selected Cloud repository for a new upload. For local imports, those
URLs must match a configured Git remote when the checkout has remotes.
### SARIF and repeat imports
Both formats use the native finding UUID as identity within the selected
repository and source key. Keep the source key stable across repeated imports.
Importing the same UUID from SARIF after native JSON updates the same source
record: it replaces the evidence snapshot rather than merging it. Severity can
become unknown, and commit, package, advisory and other native detail absent from
SARIF is no longer present in that snapshot. Importing native JSON again replaces
it with the richer native evidence. Use native JSON consistently for ongoing
imports.
Self-contained `endorctl` SARIF 2.1.0 reports preserve finding UUIDs, links,
direct repository paths, and reported SAST or Secrets lines. Native severity
and scanned revision are unavailable. Diagnostic levels, CVSS, and indexed or
base-relative artifact references stay in the original evidence. Unrelated run
artifact inventories are omitted. For a new Cloud submission, declared
repository URLs must match the selected repository. For local imports, they
must match a comparable configured Git remote when one is available.
Recommended upgrades, reachability, dismissals and other Endor assessments remain
source claims. Local records remain unassessed and separate from completed scans;
imports do not automatically investigate or patch them. Records omitted from a
later local import remain stored. Saved Cloud requests retain their destination
repository ID when resumed.
Both formats identify a record by finding UUID within the repository and source
key. Reimporting replaces its evidence snapshot. Importing SARIF after native
JSON can clear commit, package, and advisory details and make severity unknown.
For ongoing imports use native JSON and the same source key. Local records
omitted from later imports remain stored.
The adapter can be tested with synthetic records and the public SARIF sample.
Verifying acquisition requires an authenticated Endor namespace with findings.
Verifying Cloud publication also requires a Cloud environment that supports
finding imports.
Upgrades, reachability, and dismissals remain Endor’s claims. Imported findings
start unassessed and are separate from completed scans.
@@ -0,0 +1,48 @@
# Import GitHub code scanning findings
Import code scanning alerts from one repository and Git ref. The collector
saves each alert with the instance that GitHub returned for the selected ref.
## Quick start
Sign in with `gh auth login`. A fine-grained token needs **Code scanning alerts: read**.
A classic token needs `security_events`, or `public_repo` for a public repository.
[GitHub API permissions](https://docs.github.com/en/rest/code-scanning/code-scanning#list-code-scanning-alerts-for-a-repository)
For GitHub Enterprise, set `GH_HOST` to the host you signed in to.
If `gh` is unavailable, the SDK accepts `githubHost` and a `githubToken` for that host.
From the destination checkout root, set `repo` to its GitHub repository. Set
`source_key` to your existing code scanning key exactly, including case. For a
first import, choose a key for the host, repository and finding family. Replace
`/path/to/private/reports` with an existing private directory outside the checkout,
then preview the default branch’s open alerts.
```sh
export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1
repo=OWNER/REPO
source_key=github.com/example/project/code-scanning
out=$(mktemp -d "/path/to/private/reports/github.XXXXXX") &&
codex-security import github "$repo" --format json > "$out/alerts.json" &&
codex-security publish findings "$out/alerts.json" \
--to local --repository . --provider github \
--source-key "$source_key" --dry-run --format json
```
## Import and verify
Check the ref and alert numbers in the preview. The alert repository must match
a comparable local Git remote when available or the selected Cloud repository.
Reuse the source key when you [save or publish and verify](README.md#save-or-publish-and-verify).
## Reference
- To select another ref, add `--github-ref refs/heads/BRANCH` to the collector.
Use `--github-state all` to include fixed and dismissed alerts, or repeat
`--github-alert NUMBER` to select exact alerts regardless of state.
- Save the collector’s complete JSON array. Omit field or token filters and
`--full-output` when saving it for the reader.
- The GitHub host, repository, alert number and ref identify a finding, so the
same alert on two refs retains separate evidence. Missing security severity
stays `unknown`.
- See the [GitHub SDK examples](../../sdk/typescript/docs/cli.md#import-github-findings-locally-or-to-cloud)
for programmatic collection and destination-specific normalization.
+57 -52
View File
@@ -1,64 +1,69 @@
# Import GitHub Dependabot repository alerts
# Import GitHub Dependabot findings
A Dependabot alert identifies a vulnerable dependency in one repository. Its GHSA
describes the affected software. GitHub code scanning and published security
advisories have separate import formats.
Import Dependabot alerts from one GitHub repository. An alert identifies a
dependency occurrence in a manifest. Its advisory describes the vulnerability.
## Export one repository
## Quick start
Use a fine-grained token or GitHub App installation with **Dependabot alerts: read**
for the repository. The GitHub CLI reads the alerts. Codex Security imports the
saved file offline. Keep the export outside the checkout.
[Enable external imports](README.md#preview-a-report) and
[export the repository alerts](#export-repository-alerts). From the matching
checkout root, replace the file path, hostname, and repository in this preview.
```bash
set -eu
umask 077
out=$(mktemp -d)
gh api --hostname github.com --method GET --paginate \
-H 'Accept: application/vnd.github+json' \
-H 'X-GitHub-Api-Version: 2022-11-28' \
--jq 'if type == "array" then tojson else error("expected an alert page") end' \
'repos/OWNER/REPO/dependabot/alerts?per_page=100' > "$out/pages.tmp"
test -s "$out/pages.tmp"
mv "$out/pages.tmp" "$out/dependabot.jsonl"
```
Replace the hostname and `OWNER/REPO` in both examples. The command follows every
page and includes open, fixed, dismissed, and auto-dismissed alerts. Each line
contains one page, including `[]` for an empty collection. If a request fails,
check repository access before retrying.
## Preview and import
```bash
export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1
codex-security publish findings "$out/dependabot.jsonl" \
--to local --repository ./project --provider github \
```sh
codex-security publish findings /private/path/dependabot.jsonl \
--to local --repository . --provider github \
--source-key github.com/OWNER/REPO/dependabot --dry-run --format json
```
Review the destination, ready records, and exclusions, then remove `--dry-run`.
Use `--to cloud` with an authorized repository ID or URL for Cloud publication.
For a local checkout, the alert repository must match a configured network
remote when one is available. If the checkout has only filesystem remotes or
no remote, verify the export belongs to it before importing.
## Import and verify
Keep the export and reuse its source key for the same repository. The host,
repository, and alert number identify an occurrence. Two alerts for the same
GHSA keep separate histories. A later selection updates the alerts it includes
and leaves omitted alerts in place.
The alert repository must match a configured network remote when one is
available. For a checkout with only filesystem remotes or no remote, verify
the export belongs to it. [Save or publish and verify](README.md#save-or-publish-and-verify)
using the same source key for later exports from this repository.
## Reference
### Identity and evidence
The host, repository, and alert number identify an occurrence, so two alerts
for one GHSA keep separate histories. Reimport updates included alerts and
leaves omitted alerts in place.
Each finding records the matched package, ecosystem, manifest path, vulnerable
version range, first patched version when available, and advisory IDs. The
native alert retains GitHub’s state and timestamps. An alert identifies a
manifest dependency without establishing the installed version, an affected
line, or a Codex assessment. The importer rejects conflicts between alert
identities, affected packages, or ranges, and requires repository-relative
manifest paths.
native alert retains GitHub’s state and timestamps. An alert does not establish
the installed version, an affected line, or a Codex assessment. The importer
requires repository-relative manifest paths and rejects conflicts between
alert identities, affected packages, or ranges.
Read local evidence with `codex-security findings imported ./project --format json`.
To trace the affected package and evaluate an upgrade in Codex, use
[`$resolve-dependency-alert`](../../plugins/codex-security/skills/resolve-dependency-alert/SKILL.md)
with the saved alert and the checkout.
See the [GitHub Dependabot alerts endpoint](https://docs.github.com/en/rest/dependabot/alerts#list-dependabot-alerts-for-a-repository)
and the [GitHub CLI pagination options](https://cli.github.com/manual/gh_api).
To investigate a local alert, use the
[`$resolve-dependency-alert` skill](../../plugins/codex-security/skills/resolve-dependency-alert/SKILL.md)
with the saved alert and checkout. GitHub [code scanning](github-code-scanning.md)
and [security advisories](github-security-advisories.md) have separate guides.
### Export repository alerts
Authenticate the GitHub CLI with a fine-grained token or GitHub App installation
that has read access to Dependabot alerts for the repository. Replace `github.com`
and `OWNER/REPO` with the alert host and repository.
```bash
out=$(mktemp -d) && (
set -eu
umask 077
gh api --hostname github.com --method GET --paginate \
-H 'Accept: application/vnd.github+json' \
-H 'X-GitHub-Api-Version: 2022-11-28' \
--jq 'if type == "array" then tojson else error("expected an alert page") end' \
'repos/OWNER/REPO/dependabot/alerts?per_page=100' > "$out/pages.tmp" &&
test -s "$out/pages.tmp" &&
mv "$out/pages.tmp" "$out/dependabot.jsonl"
)
```
The export contains one JSON array per line, including `[]` for an empty page.
It follows every page and includes open, fixed, dismissed, and auto-dismissed
alerts. The saved file is `$out/dependabot.jsonl`. See the
[Dependabot alerts endpoint](https://docs.github.com/en/rest/dependabot/alerts#list-dependabot-alerts-for-a-repository)
and [GitHub CLI pagination](https://cli.github.com/manual/gh_api).
@@ -0,0 +1,60 @@
# Import GitHub Security Advisories
Import repository disclosures or selected entries from GitHub's global advisory
database. Use the affected packages and version ranges to investigate whether
a dependency in your checkout is affected.
## Quick start
Sign in with `gh auth login`. For GitHub Enterprise, set `GH_HOST` to the host
you signed in to. If `gh` is unavailable, the SDK accepts `githubHost` and a
`githubToken` for that host.
From the destination checkout root, set `repo` to its GitHub
repository and `source_key` to your existing advisories key exactly, including
case. For a first import, choose a key for the host, repository and finding
family. Replace `/path/to/private/reports` with an existing private directory
outside the checkout. Collect published advisories as a complete JSON array
without field or token filters or `--full-output`, then preview the saved file.
```sh
export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1
repo=OWNER/REPO
source_key=github.com/example/project/security-advisories
out=$(mktemp -d "/path/to/private/reports/github.XXXXXX") &&
codex-security import github-advisories "$repo" --format json > "$out/advisories.json" &&
codex-security publish findings "$out/advisories.json" \
--to local --repository . --provider github \
--source-key "$source_key" --dry-run --format json
```
## Import and verify
Check the advisory IDs and source in the preview. For repository advisories, the
source must match a comparable local Git remote when available or the selected
Cloud repository. Use a source key separate from code scanning and Dependabot
when you [save or publish and verify](README.md#save-or-publish-and-verify).
## Reference
- **Repository advisories.** Repeat `--github-advisory GHSA-xxxx-xxxx-xxxx` to select exact
IDs. To list an unpublished state instead, pass `--github-state draft`,
`triage`, or `closed`. Private advisories require repository advisory read
permission and access to the disclosures.
- **Global advisories.** Add `--github-advisory-source global` and at least one
`--github-advisory GHSA-xxxx-xxxx-xxxx` to the collector. The repository argument selects
the context for investigation. A global record has no source repository.
- An advisory retains the GHSA ID, reported packages and affected version
ranges. Check the installed versions in your repository separately. For
programmatic imports, see the [advisory SDK examples](../../sdk/typescript/docs/cli.md#import-ghsa-advisories-separately).
To collect a specific global advisory, use the same shell and replace the
example ID. Preview `"$out/global-advisories.json"` with the same command and
advisories source key. Each finding’s ID already distinguishes global and
repository scope.
```sh
codex-security import github-advisories "$repo" \
--github-advisory-source global --github-advisory GHSA-2345-6789-cfgh \
--format json > "$out/global-advisories.json"
```
+68 -60
View File
@@ -1,13 +1,69 @@
# Import Amazon Inspector repository findings
# Import Amazon Inspector findings
Import package and code vulnerabilities from one Amazon Inspector Code Security
repository. Each finding ARN identifies one occurrence within your source key.
repository. Findings from EC2, ECR, Lambda, and network resources are excluded.
## Export one repository
## Quick start
In Inspector coverage, find the account, Region and full resource ID for the
repository. A project name alone can match several integrations. With
`inspector2:ListFindings` permission, export the findings outside the checkout.
[Enable external imports](README.md#preview-a-report) and
[export the repository findings](#export-repository-findings). In your SCM
integration, verify the Inspector project ARN and set `VERIFIED_PROJECT_ARN`
to that value. From the matching checkout root, preview the file with the
verified Git URL and your source key. Omit `--inspector-project-arn` when the
findings already include the matching native Git URL.
```sh
codex-security publish findings /private/path/inspector.json \
--to local --repository . --provider inspector \
--source-repository-url https://github.com/example/project \
--inspector-project-arn "$VERIFIED_PROJECT_ARN" \
--source-key inspector/account-alias/us-east-1/example/project \
--dry-run --format json
```
## Import and verify
Check the finding ARNs and repository in the preview, then
[save or publish and verify](README.md#save-or-publish-and-verify). For a Cloud
retry, supply the same verified ARN and Git URL used to prepare the submission.
## Reference
### Identity and repository mapping
A finding ARN identifies an occurrence within the source key. Reuse the key
across exports to update matching ARNs. Omitted findings and empty exports
leave earlier occurrences in place.
Package findings retain the advisory and reported dependency versions. Code
findings retain detector details and safe repository-relative locations when
available. Native status, severity, and remediation remain source evidence.
A closed or suppressed finding stays unassessed.
Custom GitHub hosts need a native GitHub provider hint for Cloud publication.
Self-managed GitLab is supported locally. If the GitLab web URL includes a
prefix the SSH clone URL omits, use the verified HTTPS clone URL as a checkout
remote. Keep the verified URL’s path casing on custom hosts. For home-relative
SSH paths, verify the account when the URL omits the login. SDK callers can
pass verified ARN-to-URL pairs through `inspectorProjectMap` for raw and
normalized imports.
### Export repository findings
In Inspector coverage, find the account, Region, and full resource ID for the
repository. Project names can match several integrations. With
`inspector2:ListFindings` permission, replace the example Region, account ID, and
repository resource ID in this export.
For ARNs selected with the [AWS Codex plugin](https://github.com/aws/agent-toolkit-for-aws#codex),
keep the Region, account, and repository filters below. Add a `findingArn` array
with one `{"comparison":"EQUALS","value":"FINDING_ARN"}` per ARN, up to
[10 per request](https://docs.aws.amazon.com/inspector/v2/APIReference/API_FilterCriteria.html#inspector2-Type-FilterCriteria-findingArn).
Combine the native `findings` arrays from all fully paginated batches into one
`{"findings":[...]}` report. From a saved scoped export, select those rows locally.
If the selected rows cannot establish the repository together, request a native
capture of those same ARNs with the missing evidence. Before import, verify the
preview contains each requested ARN once, no other ARNs, and no exclusions.
```bash
set -eu
@@ -18,61 +74,13 @@ aws inspector2 list-findings --region us-east-1 --output json \
"awsAccountId":[{"comparison":"EQUALS","value":"ACCOUNT_ID"}],
"resourceType":[{"comparison":"EQUALS","value":"CODE_REPOSITORY"}],
"resourceId":[{"comparison":"EQUALS","value":"REPOSITORY_RESOURCE_ID"}]
}' > "$out/inspector.json.tmp"
mv "$out/inspector.json.tmp" "$out/inspector.json"
}' > "$out/inspector.json.tmp" &&
mv "$out/inspector.json.tmp" "$out/inspector.json"
```
Start at the first page with automatic pagination enabled. Omit
`--starting-token`, `--no-paginate`, `--max-items` and `--query`. The
Start an export on the first page with AWS CLI automatic pagination enabled.
Omit `--starting-token`, `--no-paginate`, `--max-items`, and `--query`. The
importer rejects continuation tokens but cannot distinguish a final page
saved on its own from a complete export.
## Bind the Inspector project to a Git repository
Inspector often reports a project ARN and a name such as `example/project`.
That name can exist on multiple Git hosts. Verify the project ARN and its
canonical Git URL in your SCM integration setup. Set `VERIFIED_PROJECT_ARN`
to that ARN and pass the pair explicitly.
Copying an ARN from the report alone cannot verify who owns the repository.
When the findings already include a matching native Git URL, omit
`--inspector-project-arn`.
## Preview, import and read back
```bash
export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1
codex-security publish findings "$out/inspector.json" \
--to local --repository ./project --provider inspector \
--source-repository-url https://github.com/example/project \
--inspector-project-arn "$VERIFIED_PROJECT_ARN" \
--source-key inspector/account-alias/us-east-1/example/project \
--dry-run --format json
```
Review the destination, ready findings and exclusions. Remove `--dry-run` to
import, then run `codex-security findings imported ./project --format json`.
Reuse the source key across exports. Reimport updates an existing ARN.
Omitted findings and empty exports leave earlier occurrences in place.
For Cloud, use `--to cloud --repository CLOUD_REPOSITORY_ID` on a deployment
that accepts the Inspector provider. Cloud checks the authorized GitHub
destination. Custom GitHub hosts need a native GitHub provider hint.
Self-managed GitLab is supported locally. If the GitLab web URL includes an
installation prefix that the SSH clone URL omits, use the verified HTTPS clone
URL as a checkout remote. Use the verified URL’s path casing on custom hosts.
For home-relative SSH paths, verify the account when a URL omits the login.
Supply the same verified ARN and URL when resuming a Cloud submission prepared
with that binding. SDK callers can pass verified ARN-to-URL pairs through the
`inspectorProjectMap` option on raw and normalized imports.
## Evidence
Package findings retain the advisory and reported dependency versions. Code
findings retain detector details and safe repository-relative locations when
available. Native status, severity and remediation remain source evidence.
A closed or suppressed finding stays unassessed. EC2, ECR, Lambda and network
findings are excluded.
saved on its own from a complete export. See the
[AWS CLI export](https://docs.aws.amazon.com/cli/latest/reference/inspector2/list-findings.html)
and [repository fields](https://docs.aws.amazon.com/inspector/v2/APIReference/API_CodeRepositoryDetails.html).
and [Inspector repository fields](https://docs.aws.amazon.com/inspector/v2/APIReference/API_CodeRepositoryDetails.html).
+67 -135
View File
@@ -1,146 +1,78 @@
# Import OpenGrep findings
Set `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1` in the command environment to enable external imports.
Import native OpenGrep JSON, plain or gzipped, to retain observations,
available traces and scan diagnostics.
Import native OpenGrep JSON, including gzip-compressed reports, into the local
workbench or Cloud. This reader accepts scanner output, not SARIF, normalized
JSONL, or an API summary. It preserves findings as unassessed scanner evidence.
## Quick start
From the source repository root, use a fresh report directory outside the
checkout. The following commands use the shell's temporary directory:
[Enable external imports](README.md#preview-a-report). From the scanned
checkout root, preview the saved JSON using its credential-free HTTP(S) repository
URL and an OpenGrep-specific source key. To get a new report,
[run OpenGrep locally](#diagnostics-and-coverage).
For an existing report, set its path in the same shell.
```sh
opengrep_report=../reports/opengrep.json
```
Preview the selected report.
```sh
codex-security publish findings "$opengrep_report" --to local --repository . \
--provider opengrep --source-repository-url https://github.com/example/project \
--source-key opengrep/example/project/main --dry-run --format json
```
## Import and verify
Check the findings, exclusions and `report.errors`, including when the
findings list is empty. Keep `--provider opengrep` for
[local import or Cloud publication](README.md#save-or-publish-and-verify).
Both destinations store `semgrep` as the provider and record OpenGrep in
`details.scanner_origin`.
## Reference
### Provider identity and evidence
Use a distinct OpenGrep source key for the organization, project and branch.
The rule, path and range identify an occurrence. Moving a match or changing
its Windows path spelling can create a new record.
Multiple traces at one occurrence are grouped. Evidence retains the rule
level, snippets, ignored state and fingerprints when supplied. Severity is
`unknown` because OpenGrep levels such as `ERROR` describe rule matches.
If individually valid traces together exceed the Cloud 256 KiB limit, the
whole occurrence is excluded. [Imported evidence](schema-guide.md)
### Diagnostics and coverage
To create a report, run OpenGrep with your rules from the repository root
and save native JSON outside the checkout. Add `--verbose` for skipped-target
details. Preview the file after the scan succeeds.
[OpenGrep output options](https://github.com/opengrep/opengrep/blob/main/src/osemgrep/cli_scan/Scan_CLI.ml)
```sh
opengrep_report=
report_dir=$(mktemp -d) &&
opengrep scan --config /path/to/rules.yaml --json --output "$report_dir/opengrep.json" . &&
codex-security publish findings "$report_dir/opengrep.json" --to local \
--provider opengrep --source-key opengrep/ORGANIZATION/PROJECT/BRANCH \
--source-repository-url https://github.com/example/project \
--repository . --dry-run --format json
opengrep scan --config /path/to/rules.yaml --json --output "$report_dir/opengrep.json" . &&
opengrep_report="$report_dir/opengrep.json"
```
Native JSON includes dataflow traces when the scanner produces them.
`--dataflow-traces` controls text and SARIF rendering; it is not required for JSON.
See OpenGrep's [output options](https://github.com/opengrep/opengrep/blob/main/src/osemgrep/cli_scan/Scan_CLI.ml)
and [JSON formatter](https://github.com/opengrep/opengrep/blob/main/src/osemgrep/reporting/Cli_json_output.ml).
The reader accepts native JSON only. A report can contain matches alongside
parse errors or timeouts. Check the scanner's exit status and retain the
original JSON for run-wide details. The preview includes run metadata in
`report`. Stored findings keep the version, raw observations in
`source_data.results` and the diagnostic count in `source_data.scan_error_count`.
Cloud needs at least one supported finding.
Review the source repository, findings, exclusions, diagnostics, and destination.
Repeat the import without `--dry-run` to confirm interactively, or add `--yes`
after reviewing the preview. Local imports require no Cloud login or model call.
Read the stored evidence with:
### Assess an imported finding locally
```sh
codex-security findings imported . --format json
```
For Cloud, use the same report and source namespace with a Cloud destination:
```sh
codex-security publish findings "$report_dir/opengrep.json" --to cloud \
--provider opengrep --source-key opengrep/ORGANIZATION/PROJECT/BRANCH \
--source-repository-url https://github.com/example/project \
--repository https://github.com/example/project --dry-run --format json
```
`--source-repository-url` is required and declares where the report came from.
The importer checks it against configured local Git remotes or the selected
Cloud repository. It does not infer the scanner's revision from the current
checkout. Cloud preview requires the existing ChatGPT login and an authorized
repository and environment; review the preview before approving the upload.
## Provider identity and evidence
`--provider opengrep` selects the OpenGrep reader. Local storage and Cloud use the
existing `semgrep` source-provider contract for compatibility, while typed
`scanner_origin` identifies **OpenGrep**. The preview shows this mapping. This
does not add a native OpenGrep provider to the Cloud service. Cloud publication
requires that deployment to support the existing Semgrep import contract;
successful local imports do not verify hosted availability.
Keep an OpenGrep-specific source key, such as
`opengrep/ORGANIZATION/PROJECT/BRANCH`, stable across runs. Occurrence IDs use the
rule, path, and source range. The importer normalizes redundant slash-separated
components in repository-relative paths and preserves literal backslashes in
filenames. An unmapped path keeps its original spelling in the occurrence ID.
Keep Windows path spellings consistent across runs because changing them can
create a second record. Multiple dataflow traces for the same occurrence are
grouped into one finding. For Cloud imports, check `excluded` for traces that
could not fit. If independently valid traces exceed the 256 KiB limit together,
the whole occurrence is excluded. Moving a match creates a new record and leaves
its earlier record intact. The raw scanner
fingerprints remain evidence and do not override this location-based identity.
Omitting a finding from a later report does not close or delete it.
The adapter retains rule metadata, source ranges, snippets, traces, ignored state,
and original severity. Normalized severity is `unknown`: OpenGrep rule levels
such as `ERROR` or `WARNING` are not a verified vulnerability severity. Ignored
matches remain source evidence, separate from a Codex assessment. Importing a
report does not assess findings, apply fixes, or create a completed Codex scan.
## Diagnostics and coverage
OpenGrep can return matches alongside parse failures, partial parsing, timeouts,
and other diagnostics. Warning diagnostics can accompany exit code 0 with the
default `--no-strict`; `--strict` changes warning handling, while `--error`
separately makes findings produce exit code 1. Inspect the report's diagnostics
and the scanner's exit status. Neither zero findings nor a successful exit
establishes complete coverage. See OpenGrep's
[error classification](https://github.com/opengrep/opengrep/blob/main/src/core/Core_error.ml).
The JSON preview and result retain the native report envelope, without `results`,
in `report`, including diagnostics and path metadata for an empty local report.
Individual stored findings retain the original observations in
`source_data.results` and a `source_data.scan_error_count`. Their compact
`source_data.report` retains only the scanner version, keeping scan-wide metadata
such as diagnostics and matching explanations outside each finding's evidence
budget. Full report metadata is
returned by the SDK and CLI; it is not saved as a separate durable scan record.
Keep the original JSON if you need the complete run metadata later.
Add OpenGrep's `--verbose` when collecting
skipped-target details; its [output handling](https://github.com/opengrep/opengrep/blob/main/src/osemgrep/reporting/Output.ml)
can omit those details otherwise.
Publication status describes import processing and acknowledged records, not
scanner coverage. A `complete` publication does not resolve scan diagnostics or
establish a clean security result. Cloud publication requires at least one
supported finding; an empty report can still be previewed locally with its
metadata. Review exclusions before approving either destination.
## Assess an imported finding locally
Copy an imported record's `id` from `findings imported --format json`. Use an
authorized checkout corresponding to the report's revision, then pass its
evidence to the existing SDK validator:
```ts
import {
CodexSecurity,
listLocalExternalFindings,
} from "@openai/codex-security";
const repositoryPath = "/path/to/repository";
const [record] = await listLocalExternalFindings({
repository: repositoryPath,
id: "IMPORTED_FINDING_ID",
});
if (!record) throw new Error("Imported finding not found.");
const security = new CodexSecurity();
try {
const assessment = await security.validate({
repositoryPath,
finding: record.evidence,
});
console.log(record.id, assessment.disposition);
console.log(assessment.report);
} finally {
await security.close();
}
```
Validation sends the finding evidence, including snippets and traces, to the
configured Codex model provider. A hosted provider requires network connectivity.
The validator reads the checkout in a read-only tool sandbox with network access
disabled. It returns an assessment and leaves the stored import `not_assessed`. See
[standalone validation](../../sdk/typescript/README.md#validate-an-existing-finding)
for dispositions and report handling. Hosts that already provide model execution
can use [validateRecords](../../sdk/typescript/docs/validate-records.md) instead.
Use the local record's `id` with `listLocalExternalFindings({ repository, id })`.
On a `CodexSecurity` instance, pass `record.evidence` to
`security.validate({ repositoryPath, finding: record.evidence })` using the
checkout for the scanned revision. This sends evidence to your configured
model provider and returns a separate assessment. The stored import remains
`not_assessed`. [SDK validation example](../../sdk/typescript/README.md#validate-an-existing-finding)
and [host-provided validation](../../sdk/typescript/docs/validate-records.md)
+76 -188
View File
@@ -1,210 +1,98 @@
# How saved scanner reports map to imported evidence
# Imported finding identity and evidence
The **reader** selected by `publish findings --provider` interprets a saved
scanner export. Acquisition produces the artifact:
for example, `snyk test` scans a workspace, while `codex-security import github`
retrieves selected code-scanning alerts. File ingestion reads the saved report.
Use the mappings to decide what one record represents, whether a later export
updates it, and what evidence a consumer can use. For setup and confirmation,
see
[import vendor findings locally](../../sdk/typescript/docs/cli.md#import-vendor-findings-locally).
See the [scanner import guides](README.md) for accepted inputs, repository
requirements and export examples.
This reference explains which records a repeat import updates, what the fields
mean and how to interpret the result.
## Choose the record and source key
A stored source record is scoped to **destination repository + provider + source
key + source finding ID**. Choose the key for the stream you intend to replay,
not the export date. A CVE or GHSA names an advisory; a CWE or rule ID describes
a class of issue. Neither identifies a particular installed dependency, code
location, or affected asset. Matching titles, packages or advisories are reasons
to investigate records together, not instructions to merge them.
A source record is identified by its destination repository, stored provider,
source key and source finding ID. Use the same source key for each export of the
same stream, such as an organization, project and branch. A date or run ID in
the key creates a new set of records on each run.
| Reader and accepted input | Source finding ID basis | Keep the source key stable for |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ |
| [Wiz package JSON or detailed CSV](../../sdk/typescript/docs/cli.md#package-vulnerability-inputs); CSV requires `CloudPlatform=GitHub` and `CloudProviderURL` for a GitHub repository `/tree/<ref>` | Vendor occurrence `id` (CSV: `ID`), not the CVE | Tenant and finding family |
| [Wiz named repository collections](../../sdk/typescript/docs/cli.md#sast-repository-secrets-and-iac-inputs) | `sast:<id>`, `secret:<id>`, `iac:<id>` | Tenant and finding family |
| [Endor Finding JSON or endorctl SARIF](endor.md) | Finding `uuid` or SARIF `properties["finding-uuid"]` | Namespace, project and context |
| [Amazon Inspector Code Security ListFindings JSON](inspector.md) | Full Inspector finding ARN | AWS account, Region and repository project |
| [Snyk Open Source CLI JSON, plugin v1 or SARIF](snyk.md) | CLI: manager, manifest, advisory, package/version and dependency path; plugin: supplied composite; SARIF: advisory, manifest set and project when known | Repository, branch, scan target and format |
| [Semgrep Code CLI/CI JSON or SARIF](semgrep.md) | Fingerprint; otherwise rule, literal path and start/end lines and columns | Organization, project and branch |
| [SonarQube Cloud capture or native issue-search pages](sonar.md) | Sonar issue key | Cloud instance, org, project and ref |
| [GitHub Dependabot repository REST alerts](github-dependabot.md) | Host, repository and alert number | Host, repository and Dependabot family |
| [GitHub saved `import github` output](../../sdk/typescript/docs/cli.md#import-github-findings-locally-or-to-cloud) | Host, repository, alert number and hash of selected ref | Host, repository and code-scanning family |
| [GitHub saved `import github-advisories` output](../../sdk/typescript/docs/cli.md#import-ghsa-advisories-separately) | Host, repository **or** global scope, and GHSA ID | Separate advisory stream from alerts |
| [Black Duck BOM-6 collection or selected rows](blackduck.md) | Project version, component version, origin, advisory source and advisory name | Deployment, project and version |
| [Veracode Static Analysis Findings API pages](veracode.md) | API origin, application and context, and native issue ID | Deployment, application and static policy |
The reader derives the source finding ID from the export. The differences matter
when a finding moves, an advisory affects several packages, or the export format
changes.
Within **one input**, duplicate IDs are ambiguous, not corroboration. Wiz and
GitHub reject a selection with duplicate accepted IDs. Endor, Snyk and Semgrep
exclude every record with the colliding identity. Black Duck rejects duplicate occurrences in a complete collection, and excludes all colliding rows in an explicit selection.
Veracode rejects a capture that repeats an issue ID for the same scan type.
Inspect the source and select
the intended occurrence; don't rename records simply to make them import. Across
**separate local imports**, changed evidence updates the same record; omission
does not delete or resolve it. Cloud publication sends an expected version;
resuming a saved request keeps that value. An item error such as
`version_conflict` or `stale_source_snapshot` can reject an update instead of
replacing a newer report. Inspect the item error and current source report
before preparing a fresh submission.
| Report | What identifies one record |
| ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Amazon Inspector](inspector.md), [Endor Labs](endor.md), [SonarQube Cloud](sonar.md) | Inspector finding ARN, Endor Finding UUID or Sonar issue key. Endor native JSON and SARIF use the same UUID. |
| [Wiz](wiz.md) | Package occurrence ID, or a SAST, repository-secret or IaC occurrence ID prefixed with its family. Normalized JSONL uses the supplied ID. |
| [GitHub Dependabot](github-dependabot.md), [code scanning](github-code-scanning.md) | Host, repository, alert family and alert number. Code scanning also includes the selected ref. Two alerts citing one GHSA remain separate. |
| [GitHub advisories](github-security-advisories.md) | Host, repository or global scope, and GHSA ID. This identifies a disclosure. Check installed packages separately. |
| [Snyk Open Source](snyk.md) | Native CLI JSON distinguishes manifest, package manager, advisory, package name and version, and dependency path. Plugin and SARIF reports use different identities. |
| [Black Duck SCA](blackduck.md), [Veracode Static Analysis](veracode.md) | Black Duck combines project version, component version, origin and advisory identity. Veracode scopes a native issue ID to its API origin, application and context. |
| [Semgrep CLI or CI reports](semgrep.md), [OpenGrep](opengrep.md) | Semgrep prefers a fingerprint and falls back to rule, path and range. OpenGrep groups traces by rule, path and range. Both store provider `semgrep`. Use a separate OpenGrep source key. |
| [Semgrep Platform SAST](semgrep.md#import-selected-semgrep-platform-sast-findings-with-the-sdk) | Deployment, project ID, SAST product, full Git ref and native finding ID. The same occurrence keeps its identity when its file moves. |
## Interpret the provider evidence
- **Wiz:** `detailedName`, version, advisory and fixed version describe a
package occurrence. Repository-branch paths can be manifests; container paths
cannot. JSON prefers `vendorSeverity` over `severity`; repository CSV uses
`Severity`, then `VendorSeverity`, then `CVSSSeverity`. Keep named
`sastFindings`, `secretInstances` or `iacFindings` nodes with a repository URL
or matching inventory. SAST can map a range, snippet, CWE and vendor verdict;
repository secrets map detector and validation metadata, not a scanned
revision from the introduced commit; IaC maps expected/actual configuration,
not proof of deployment. The Wiz file reader does not map workload secrets,
cloud configuration or external network scans. It also accepts explicitly
normalized JSONL: supply the reviewed `source_finding_id` and `evidence`,
retaining the raw row. The reader does not infer a mapping for other CSV
profiles.
- **Amazon Inspector.** Supply a complete export for one repository project.
A matching native URL or the operator's full project ARN mapping establishes
the Git host. Local import and Cloud replay check the destination again.
Each finding ARN identifies one occurrence. Duplicate ARNs exclude all
colliding rows. Package and code evidence retain the native finding.
- **Endor Labs:** Prefer a complete native Finding, array or `list.objects`.
`spec.level`, dependency paths/versions, advisory aliases, source SHA and
primary SAST/AI SAST locations map when present. The project UUID does not
verify the repository. Proposed upgrades, reachability and dismissals remain
source claims. SARIF keeps the rule/result and direct locations but reports
`unknown` severity, not CVSS or diagnostic level. Importing SARIF over native
JSON for the same UUID **replaces**, rather than enriches, its snapshot.
- **Snyk CLI, plugin and Open Source SARIF:** Prefer ungrouped native
`snyk test` JSON for package versions,
dependency chains, advisory aliases and fix advice. A different dependency
path can be another occurrence of the same advisory. Plugin evidence can be
abbreviated; SARIF groups occurrences. Scan-target-relative manifests are not
Git-root locations, and a synthetic SARIF line 1 is not a code finding. The
formats do not reconcile their IDs. Licenses, Code, Container, IaC and
platform backlog are outside these Open Source file formats.
- **Semgrep Code CLI and SARIF:** Supply `--source-repository-url` for these
file formats. JSON `extra.fingerprint` or
SARIF `matchBasedId/v1` survives a location change; without a usable
fingerprint, a move creates a new record. Use the mapped rule, range, snippet
and CWE to locate code. Ignored/suppressed is source state. JSON distinguishes
Critical from High; both become diagnostic `error`, mapped to High, in Semgrep
SARIF. Inspect the selected result for trace/fix details. Platform/MCP
envelopes and general Supply Chain/Secrets feeds are not Code CLI or SARIF exports.
- **OpenGrep.** Use native JSON and supply `--source-repository-url`. The
[OpenGrep guide](opengrep.md) covers export and occurrence identity.
- **SonarQube Cloud.** Use [the Sonar import workflow](sonar.md) to capture
security issues for one project and branch or PR through the authenticated
Sonar CLI. Keep the capture to import and publish the same native evidence.
The issue key identifies the occurrence. The rule identifies the check that
raised it.
- **GitHub:** For code scanning, the selected instance supplies path/range, ref
and commit. The rule's `security_severity_level` supplies severity; diagnostic
`error` alone means `unknown`. An alert-wide dismissal takes precedence over
instance state. For GHSA, a repository disclosure identifies its publisher; a
global disclosure has no source repository. Both can carry CVE aliases,
affected ranges and patched versions. Neither proves installation or
applicability. Both readers require saved collector output.
- **GitHub Dependabot.** Use `gh api --paginate` to save native repository
alert pages as JSONL for the `github` reader. Each alert identifies the
matched package, manifest and vulnerable range. The embedded advisory supplies advisory IDs.
Each alert number has its own history, including when several alerts cite the
same GHSA. GitHub secret-scanning alerts remain outside the file reader.
Repeat local imports replace changed evidence for the same identity. Identical
evidence is unchanged, and records omitted from a later report remain stored.
For example, importing Endor SARIF after native JSON for the same UUID can
remove details from the stored snapshot. If one export contains colliding IDs,
inspect the reader’s exclusions or input error before retrying.
## Read the right field
- The
[evidence schema](../../sdk/typescript/schemas/external-findings.schema.json)
separates the source ID from `evidence`. Its required `title` and `severity`
are reported evidence, not a Codex rating. Severity is one of `critical`,
`high`, `medium`, `low`, `informational`, or `unknown`; source status,
confidence, verdicts and fix advice do not change `assessment.state`.
- `packages[].installed_version` is an observation; `vulnerable_version_range`
is a claim about affected versions; `fixed_versions` is source guidance. Use
`locations[].path/line` for repository navigation and optional
`details.code.end_line` for the first location. Missing evidence stays
missing; don't fill in a commit from the current checkout.
- Optional `details.kind` is **not** a universal scanner taxonomy. Its values
are `sast`, `secret`, `iac` and `advisory`. Package occurrences from Wiz/Snyk
and native Endor findings use top-level fields without requiring a kind. For
an advisory, inspect `details.advisory.source`, not the chosen destination, to
distinguish repository and global scope.
- Use `source_data` to inspect what the reader actually received: e.g. a Wiz
row, Endor Finding, Snyk vulnerability plus project context, Semgrep result or
GitHub collector envelope. It's selected evidence, not necessarily the whole
export: unrelated scan inventories can be omitted and plugin or SARIF output
may already be lossy. Retain the input privately if collection scope matters.
Imported records start with `assessment.state` set to `not_assessed`. The
[evidence schema](../../sdk/typescript/schemas/external-findings.schema.json)
defines the fields the reader can populate.
| Field | How to use it |
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `title`, `severity` | Required source evidence. Severity can be `unknown`. A scanner verdict or suppression can be reported alongside it. |
| `packages[]` | Compare an observed `installed_version` with the reported `vulnerable_version_range` and `fixed_versions`. An advisory may supply only a range or fix. |
| `locations[]`, `code_revision` | Navigate to a reported repository path and line at the scanned revision when available. `details.code.end_line` extends the first location. |
| `details` | Optional context for `sast`, `secret`, `iac` or `advisory` findings. For GHSA, `details.advisory.source` distinguishes repository and global disclosures. |
| `source_data` | The vendor fields retained for this record. Keep the original export when you need scan-wide diagnostics or inventory. |
## Operate the two destinations
Local readback returns `sourceKey`, `sourceFindingId`, `version`, `evidence` and
`assessment` alongside the local record ID. The Cloud publisher sends
`source.provider` and `source.source_key` with an expected version, source
finding ID and evidence for each item. Receipt IDs for the source report,
observation and canonical finding are **destination** references, not vendor
occurrence IDs. Use the source report for evidence, not the receipt counts.
**Local.** Run `codex-security findings imported PATH --format json` with the
repository path from the preview. Each record includes
`sourceKey`, `sourceFindingId`, `version`, `evidence` and `assessment`.
**One project, local triage.** From a checkout with a saved native Snyk report
outside it:
**Cloud.** Each item includes a `source_finding_id` and an `expected_version`.
Check the per-item result for conflicts. The receipt's source-report,
observation and canonical-finding IDs identify Cloud records. Read the source
report for the imported evidence.
```sh
export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1
codex-security publish findings ../reports/snyk.json --to local --provider snyk \
--repository . --source-key example/project/main/root/native-sca --dry-run --format json
```
Cloud allows up to 256 KiB and 20 levels of nesting per finding. The publisher
batches up to 100 items and 5 MiB per request. Local file imports do not apply
these Cloud limits.
Check the selected repository, IDs, evidence and exclusions. Repeat without
`--dry-run` and confirm; then run
`codex-security findings imported . --format json`. Workbench SQLite stores the
snapshot and version. Repeating identical evidence is unchanged. A source
repository claim is checked against configured remotes when available; when
provenance is absent you must verify the target yourself. These records remain
`not_assessed`, separate from `findings list` and completed scans. To
investigate, compare the reported installed version or location against the
selected revision; import alone is not validation.
Select only authorized scanner metadata when collecting a report. Exclude
credential values before import. A reader can retain the entire selected record in
`evidence.source_data`. Confirm the destination before publishing.
**Many repositories, reviewed publication.** Partition complete exports by
repository and source namespace first; don't attach a fleet-wide export to one
destination. For example, preview one Endor project and context against its
connected repository:
Reports, output and saved requests can contain source snippets, private
advisories and secret metadata. Keep the export, preview, import result and
readback private. If a job captures terminal output, redirect standard output
and diagnostics for all three commands to private files outside the checkout.
Keep these files out of job logs and public issues.
```sh
codex-security publish findings ../reports/endor-project-main.json --to cloud \
--repository https://github.com/example/project --provider endor \
--source-key example-namespace/example-project/main --dry-run --format json
```
### Retry a Cloud submission
This reads authorized destination state; it doesn't upload. Check the account,
repository, environments, eligible records and exclusions before confirming.
Local file imports do not apply the Cloud evidence limits. Cloud limits include
256 KiB per finding, depth 20 and 5 MiB per request; an oversized record is
excluded, not truncated. For example, 240 eligible findings for one destination
require at least three requests at the 100-item ceiling, possibly more for size
or environment boundaries.
A partial result can include accepted records. Inspect the receipts, item
failures and exclusions. If the connection dropped, Cloud may have accepted a
request before the response was lost.
Read the
[result and recovery contract](../../sdk/typescript/docs/cli.md#results-and-exit-codes):
`partial` (exit 1) can include acknowledged records alongside exclusions or item
errors. Correct the rejected records; do not treat the whole selection as
failed. After `interrupted` (exit 2), a lost response is **not** proof of
rejection. A reset can also fail during preparation. Inspect the error,
receipts, cumulative counts and unacknowledged items before choosing how to
recover:
1. If the interrupted result includes `savedSubmission`, keep that checkpoint.
Preview the original export with `--dry-run --format json` using the same
build, state directory, Cloud account, endpoint and import settings.
2. Check `accountId`, `destination` and `resumed` in the preview. When `resumed`
is true, confirm the command to continue with the saved request IDs, bodies
and expected versions. When it is false, review the fresh submission before
confirming. If a repository reset retires the old submission and preparation
returns an error, run `--dry-run` again and review the new destination and
environment before confirming.
- **`savedSubmission` identifies an existing checkpoint:** rerun the same
approved command with unchanged input, source key, destination and endpoint to
resume its saved requests. This also applies if the initial request was saved
but persisting a later receipt failed.
- **No resumable checkpoint:** a repository reset retires the old request, and
an initial checkpoint-write failure may leave no request to resume. Inspect
the destination and correct the error; run a fresh `--dry-run` and get fresh
approval before publishing. Do not blindly replay a command containing
`--yes`.
With the SDK, repeat the preparation call that created the submission, using
the same options. For `prepareExternalPublication()`, supply the original
export file. For `prepareNormalizedExternalPublication()`, supply the original
`ExternalFindings`. Check `preview.resumed` before calling `publish()`.
Changing the findings prepares a new submission.
Verified source-report readback is evidence of import, not a security
assessment, UI visibility or a vendor state change.
**Privacy.** Reports, full JSON previews, local state and saved Cloud request
bodies can contain source snippets, secret metadata, internal paths, private
advisories and vendor links. Select only authorized metadata (not credential
values), keep artifacts outside the checkout with restricted access and review
the destination before uploading. Don't paste raw evidence or checkpoints into
public tickets, CI logs or PRs. The readers do not promise to redact them.
See [results and exit codes](../../sdk/typescript/docs/cli.md#results-and-exit-codes)
for cumulative counts and interrupted readback.
+146 -103
View File
@@ -1,127 +1,170 @@
# Import Semgrep Code findings
Vendor finding import and readback require `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1`.
See the [opt-in instructions](../../sdk/typescript/docs/cli.md#import-vendor-findings-locally)
and [how saved scanner reports map to imported evidence](schema-guide.md).
Import native Code CLI or CI JSON to retain severities and available snippets.
Self-contained Semgrep SARIF 2.1.0 is also supported. Either format can be gzipped.
For selected findings from the Semgrep Platform API, use the
[local SDK example](#import-selected-semgrep-platform-sast-findings-with-the-sdk).
Prefer native **Semgrep Code/SAST CLI or CI JSON** for this reader. It preserves
the scanner's original severity and source evidence. Self-contained SARIF 2.1.0
is a compatibility path. Both formats may be plain or gzip-compressed.
## Quick start
This reader does not accept Platform API, Guardian or MCP response envelopes,
or a general Supply Chain or Secrets feed. Those products and acquisition
contracts require separate mappings; installing a plugin does not change the
formats accepted here.
[Enable external imports](README.md#preview-a-report). From the scanned checkout root,
preview a saved SAST report using the repository's credential-free HTTP(S) URL
and a stable key for the organization, project and branch. If you need a report,
[capture one with Semgrep](#ci-artifacts).
To produce JSON locally, run the following from the source repository root with
your selected SAST rules. This runs a new scan; it does not retrieve earlier
findings from Semgrep AppSec Platform.
For an existing report, set its path in the same shell.
```sh
semgrep scan --config /path/to/sast-rules.yaml --json-output semgrep.json .
codex-security publish findings semgrep.json --to local \
--provider semgrep --source-key ORGANIZATION/PROJECT/BRANCH \
--source-repository-url https://github.com/example/project \
--repository . --dry-run --format json
semgrep_report=../reports/semgrep.json
```
Existing CI jobs can add `--json-output semgrep.json` to their SAST scan and pass
that artifact to the publisher. With authenticated `semgrep ci`, select `--code`;
its output follows the job's policy and PR/baseline scope and may contain only new
blocking findings. It is not a complete inventory of Platform findings.
[CLI output and scope reference](https://docs.semgrep.dev/cli-reference).
Review the findings, source repository and exclusions, then repeat the command
without `--dry-run` and confirm the import, or add `--yes` after review. Local
imports require no Cloud login and store unassessed evidence in the workbench
SQLite database. Read it with `codex-security findings imported . --format json`.
Repeated imports with the same source identity update the same records; omitted
records remain stored. See the movement behavior under Evidence and identity.
They do not create a completed scan or automatically assess or patch findings.
For Cloud, use the same report and source selection with a Cloud destination:
Preview the selected report.
```sh
codex-security publish findings semgrep.json --to cloud \
--provider semgrep --source-key ORGANIZATION/PROJECT/BRANCH \
--source-repository-url https://github.com/example/project \
--repository https://github.com/example/project --dry-run --format json
codex-security publish findings "$semgrep_report" --to local --repository . \
--provider semgrep --source-repository-url https://github.com/example/project \
--source-key example/project/main --dry-run --format json
```
Keep the same source key for one organization, project and branch across runs.
`--source-repository-url` declares where the report came from; the importer checks
it against configured local Git remotes or the Cloud destination. Cloud requires
an authorized repository and support for the `semgrep` provider. Local SARIF
imports also check every original `versionControlProvenance.repositoryUri` on
accepted findings. Unknown Git hosts keep case-sensitive repository paths.
## Import and verify
## Existing Platform findings
Check the declared source URL against the checkout's Git remote. With an empty
or wholly excluded report, the preview alone does not establish a repository match.
[Save or publish and verify](README.md#save-or-publish-and-verify) using the
same source URL and key. Cloud uses the `semgrep` provider.
Semgrep's official
[Guardian Codex plugin](https://docs.semgrep.dev/semgrep-guardian/ide-setup/codex)
can select and inspect existing findings. Its output is not accepted by this
reader. A Platform importer needs a mapping qualified against the hosted tools'
actual responses, repository/ref filters and pagination using an authorized test
tenant. The separate local `semgrep mcp` server also exposes `semgrep_findings`,
but its current tool
returns a limited list without continuation metadata. It cannot establish a
complete export. [Official MCP implementation](https://github.com/semgrep/semgrep/blob/fe209763a4a2ccfcdf6434e6c332edc24a2f586e/cli/src/semgrep/mcp/server.py).
## Reference
For an automated acquisition path, Semgrep's
[findings API](https://docs.semgrep.dev/semgrep-appsec-platform/semgrep-api) supports
pagination with a Web API token. Its Platform finding objects
need their own mapping into the shared publisher; they are not CLI `results`
objects. Do not rename an API/MCP response to `semgrep.json` or reconstruct a scan
report from a summary. No manual website export is required for either path.
### CI artifacts
## Evidence and identity
Use a saved artifact from a Code-only `semgrep ci` job. Policy and baseline
determine which matches it contains. Exit 1 can indicate blocking findings
even when the report is valid. Check the job's product selection and exit status.
JSON preserves original severity, rule, CWE IDs, source range, snippets when
available and ignored state. SARIF retains its selected result and rule, including
trace and fix evidence. Its Critical and High ratings both become diagnostic
`error`, displayed here as High; prefer JSON when that distinction matters.
Original evidence stays in `source_data`, and source state stays separate from a
Codex assessment.
To create a local report, run Semgrep from the repository root with your
SAST rules. Write to a private directory outside the checkout. After a
successful scan, use that file in the preview above. [Semgrep CLI reference](https://docs.semgrep.dev/cli-reference)
Cloud imports apply the service's evidence limits, including a maximum JSON
depth of 20. A deeply nested taint trace can exceed that bound and be excluded
with a reason in the Cloud preview. Local storage does not impose the Cloud
size or depth limits. Neither path flattens or truncates accepted traces.
```sh
semgrep_report=
report_dir=$(mktemp -d) &&
semgrep scan --config /path/to/sast-rules.yaml --json-output "$report_dir/semgrep.json" . &&
semgrep_report="$report_dir/semgrep.json"
```
Keep the supplied JSON `extra.fingerprint` or SARIF `matchBasedId/v1`
fingerprint. If a later report supplies the same fingerprint after the code
moves, importing it under the same repository and source key updates that record
with the new range; the raw fingerprint stays in `source_data`.
### Evidence and identity
Community Edition may omit the fingerprint or emit `requires login`. The fallback
identity uses the rule, literal path and range. Moving such a finding creates a
second record, and the earlier record remains stored. The importer does not
infer that they are the same finding, merge them or delete the earlier record.
Read back both with `codex-security findings imported . --format json` before
selecting evidence for assessment. A current checkout does not establish the
report's revision or branch.
Native JSON retains the result, rule, CWE IDs, range, snippets and ignored
state when supplied. SARIF retains the selected rule and result, including
traces and fixes. SARIF `error` imports as high even if the original severity
was critical. Check Cloud exclusions for deeply nested traces.
[Semgrep output fields](https://docs.semgrep.dev/semgrep-appsec-platform/json-and-sarif)
The adapter accepts SAST only. Select SAST rules or a Code-only CI scan, since
SARIF may omit enough product metadata to distinguish Secrets. Identifiable
Supply Chain and Secrets records are excluded. Reports with scan errors,
unsuccessful SARIF invocations or scan-error notifications are rejected. The
preview reports invalid findings and duplicate source identities before import.
The match ID uses JSON `extra.fingerprint` or SARIF `matchBasedId/v1`.
Reimporting the same fingerprint under the same source key and repository
updates its location. If the fingerprint is absent or says `requires login`,
the ID uses rule, literal path and range. Moving the match then creates a new
record. [Imported evidence and identity](schema-guide.md)
SARIF supports direct artifact URIs and Semgrep's native `%SRCROOT%` marker without
a base definition. Native paths retain literal percent characters; direct URIs
are decoded once. Indexed artifacts and unresolved bases remain in original
evidence without mapped repository locations. CE records with these references
are excluded because they lack a usable identity. JSON scan-wide path inventories
and timing tables are omitted from individual findings. SARIF artifact inventories
are omitted when they are unrelated to the selected finding; required inventories
retain their original entries and indexes. Empty external-property reference
containers are accepted, while actual external file references are rejected.
Use SAST-only rules. Identifiable Supply Chain and Secrets results are
excluded, but SARIF can omit the product metadata. Scan errors or unsuccessful
SARIF invocations stop import. Direct artifact URIs and native `%SRCROOT%`
paths can supply locations. Indexed artifacts or unresolved bases remain in
raw evidence and require a fingerprint for identity. Use the original report
for run-wide inventories and timing.
SDK callers pass `{ sourceRepositoryUrl }` to `normalizeSemgrepFindings`,
`normalizeSemgrepSarif`, or `readSemgrepFindings`. When passing that normalized
output directly to `prepareNormalizedLocalImport`, supply the original SARIF
repository references in the third argument's `sourceRepositories`; the file
importer forwards them automatically. For an independently known GitHub custom
host, use `{ url, platform: "github" }` for its references. The Semgrep file reader
accepts native reports, not normalized JSON/JSONL exports.
See the [native output fields](https://docs.semgrep.dev/semgrep-appsec-platform/json-and-sarif).
SDK callers pass `sourceRepositoryUrl` to the native or SARIF normalizer.
When using `prepareNormalizedLocalImport` directly, pass the original SARIF
repository references in the third argument's `sourceRepositories`. Use
`{ url, platform: "github" }` for a verified custom GitHub host.
### Import selected Semgrep Platform SAST findings with the SDK
Request `issue_type=sast` and save the original project lookup and findings
pages as response text. Pass each findings page separately. The SDK checks
every row on pages that contain a selected ID for conflicting product evidence.
When a page contains only fields shared by several products, the original
request filter identifies the product.
To find existing Code findings in Codex, sign in to Guardian and ask for the
deployment, project and full ref you want to inspect. Guardian returns a
selection for review. For this SDK import, confirm the candidate findings in
the original Web API results and use the IDs from those records. The SDK also
accepts saved responses from an authorized operator. Fetching new responses
directly requires Web API read access.
[Guardian sign-in](https://docs.semgrep.dev/semgrep-guardian/quickstart) ·
[Query existing findings](https://semgrep.dev/products/product-updates/query-your-semgrep-findings-by-asking-guardian/) ·
[Findings Web API](https://docs.semgrep.dev/api-reference/v1/findingsservice/list-code-supply-chain-or-ai-powered-detection-findings)
Use the full ref from the findings, such as `refs/heads/main` or
`refs/tags/v1`. Supply the credential-free HTTP(S) repository URL you verified
for the checkout. The native `project.url` and any selected
`finding.repository.url` must match it exactly.
- An exact finding URL is sufficient when `repository.id` is absent, even if
the display names differ. If several projects share the URL and ref, choose
the finding IDs from the intended project.
- Any `repository.id` supplied must match `project.id`. When the finding has
no URL, it must include both the matching project ID and a `repository.name`
equal to the decoded, namespace-qualified path in the supplied URL, such as
`example/project`.
[Enable external imports](README.md#preview-a-report). In a Node.js project
you control outside the scanned checkout, install `@openai/codex-security`
and save this script as `preview-semgrep.mjs`. Set the deployment, ref,
repository URL, source key and finding IDs for your selection. Pass the IDs as
positive decimal strings without leading zeros to preserve 64-bit IDs.
```js
import { readFile } from "node:fs/promises";
import {
normalizeSelectedSemgrepPlatformFindings,
prepareNormalizedLocalImport,
} from "@openai/codex-security";
const [checkout, projectFile, ...findingsFiles] = process.argv.slice(2);
const sourceRepositoryUrl = "https://github.com/example/project";
const selected = normalizeSelectedSemgrepPlatformFindings({
deployment: "example",
ref: "refs/heads/main",
sourceRepositoryUrl,
projectResponse: await readFile(projectFile, "utf8"),
findingsResponses: await Promise.all(
findingsFiles.map((file) => readFile(file, "utf8")),
),
findingIds: ["123"],
});
const prepared = await prepareNormalizedLocalImport(
selected,
{
provider: "semgrep",
sourceKey: "example/project/platform/main",
repository: checkout,
},
{ sourceRepositories: [{ url: sourceRepositoryUrl }] },
);
console.log(JSON.stringify(prepared.preview, null, 2));
```
Run the script from your SDK project. Pass the checkout, project response and
each saved findings page as absolute paths.
```sh
node preview-semgrep.mjs /path/to/checkout /path/to/reports/semgrep-project.json \
/path/to/reports/semgrep-findings-1.json
```
Review the repository, findings and exclusions. To save the selection, append
`await prepared.import()` to a copy of the script in your SDK project and run
that copy with the same inputs.
[Read back the local records](README.md#save-or-publish-and-verify) using the
checkout path from the preview.
Keep the same source key on replay. Each occurrence is identified by deployment,
project ID, SAST product, full ref and native finding ID.
The stored evidence includes the selected finding and the project's ID, name
and URL. Larger positive integer IDs are retained without rounding. Equivalent
numeric spellings (`2` and `2.0`) and key order do not change the stored record.
Preview excludes findings that lack both a native rule name and a message.
Only repository-relative files become locations. URI-like and directory-only
paths stay in the native evidence.
+71 -134
View File
@@ -1,172 +1,109 @@
# Snyk Open Source imports
# Import Snyk Open Source findings
Vendor finding import and readback require `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1`.
See the [opt-in instructions](../../sdk/typescript/docs/cli.md#import-vendor-findings-locally)
and [how saved scanner reports map to imported evidence](schema-guide.md).
Import dependency vulnerabilities from a saved `snyk test` JSON report, a
`snyk-findings-export/v1` plugin bundle or self-contained Open Source SARIF.
Native CLI JSON preserves individual dependency paths and remediation details.
Use the [official Snyk Codex plugin](https://github.com/snyk/studio-recipes/tree/main/plugins/codex)
to collect a fresh workspace scan. The existing
[`publish findings` command](../../sdk/typescript/docs/cli.md#import-snyk-open-source-findings)
accepts its `snyk-findings-export/v1` bundle with `--provider snyk` for local
storage or Cloud publication. For CLI automation, prefer native JSON from
`snyk test`; Open Source SARIF remains a compatibility input.
## Quick start
**Scope: Open Source SCA vulnerabilities only.** License findings, Snyk Code,
Container, IaC, SBOM results and existing platform backlog ingestion are outside
this adapter. License records in otherwise supported reports appear as explicit
exclusions; they are not imported as vulnerabilities.
[Enable external imports](README.md#preview-a-report). For a first local import,
set the destination from the checkout root. Choose a key for the repository,
branch, original scan target and format. If you ran Snyk in `services/api`,
replace `root` in the example key with `services/api`.
```sh
codex plugin marketplace add snyk/studio-recipes
codex plugin add snyk@snyk-studio-recipes
snyk_repository=$(pwd -P)
snyk_source_key=github.com/example/project/main/root/native-sca
```
Ask Codex: “Use snyk-findings-export to export SCA findings from this repository’s Git root to
snyk-findings.json. Run SCA only.” The plugin uses the local Snyk MCP server and
needs Snyk authentication and the package tooling required by the project. Check
its scan coverage and limitations before importing. Preview local storage with a
repository path; no Cloud login is required:
For a repeat import, set `snyk_repository` and `snyk_source_key` to the
previous local preview's exact `repository` and `source.source_key`. Keep the
original destination even if it was a package subdirectory. Changing either
value creates a separate set of records.
Set `snyk_report` to the absolute path of your saved, ungrouped Open Source
JSON report so it still resolves if you change directories.
```sh
codex-security publish findings snyk-findings.json --to local \
--provider snyk --repository ./project \
--source-key github.com/example/project/main/root/plugin-sca --dry-run
snyk_report=/path/to/reports/snyk-open-source.json
```
Or preview publication to a connected Cloud repository:
If you need a new report, [run the Snyk CLI](#native-cli-json) and keep the
`snyk_report` it sets. Preview the selected report.
```sh
codex-security publish findings snyk-findings.json --to cloud \
--provider snyk --repository https://github.com/example/project \
--source-key github.com/example/project/main/root/plugin-sca --dry-run
codex-security publish findings "$snyk_report" --to local --repository "$snyk_repository" \
--provider snyk --source-key "$snyk_source_key" \
--dry-run --format json
```
Remove `--dry-run` from the selected command to review and confirm the import.
The existing `--yes` option allows an already approved, noninteractive import.
Read local records with `codex-security findings imported ./project --format json`.
See the common [local import flow](../../sdk/typescript/docs/cli.md#import-vendor-findings-locally)
or [Cloud publication flow](../../sdk/typescript/docs/cli.md#import-wiz-findings)
for destination requirements, confirmation and result handling. The publisher
imports the saved evidence; it does not start another Snyk scan or assessment.
## Import and verify
This adapter imports Open Source SCA vulnerabilities. Other products, licenses
and SBOM results in a mixed plugin bundle appear as exclusions. It preserves the
complete selected finding, native MCP record, collection context, availability
states and coverage limitations. Ignored status remains source evidence; it does
not mark the finding fixed or assessed locally or in Cloud. A dirty workspace retains its
revision in the original evidence without claiming it as the exact scanned commit.
Review coverage and exclusions, especially unsupported products and license
records. Check the destination checkout when the report lacks a Git URL.
[Save or publish and verify](README.md#save-or-publish-and-verify) with the
same source key for subsequent exports in this format.
The MCP output is a projection: its SCA mapper shortens descriptions and can omit
alternate dependency paths. The plugin cannot recover data its MCP server did
not return. See the [official SCA mapper](https://github.com/snyk/studio-mcp/blob/main/internal/oss/map.go).
The bundle's composite occurrence identity includes package version and dependency
path. Keep the same source key for each repository, branch and scan target across
exports. A change to the composite identity produces a new source ID; changing
only the evidence preserves that ID. Plugin v1 paths are relative to the scan
target and do not carry its Git-root offset. They remain in original evidence
without being projected as repository locations or package manifest paths.
## Reference
### How to read import counts
For the same repository and source key, `created` means a new source identity.
For an existing identity, `updated` means the whole evidence snapshot changed;
`unchanged` means it did not. These counts describe imported Snyk evidence, not
new vulnerabilities, fixes, or Codex assessments.
Each plugin finding retains its collection context. If a scan's `issueCount`
falls from three to two, both remaining findings can get a new version even if
neither occurrence changed. Their source IDs stay the same, and omitting the
third finding does not close it. Native CLI JSON likewise retains the project's
[`uniqueCount`](https://github.com/snyk/cli/blob/8b2d0a695c6b1b31f681e32039db958fba6f0c2f/src/lib/snyk-test/run-test.ts#L555)
when supplied. It counts distinct vulnerabilities, not dependency-path
occurrences: two paths to the same advisory contribute one to the count.
Keep the original evidence; do not edit or strip scan metadata to suppress updates.
Use the saved report for an earlier scan. `snyk test` and the Studio plugin’s
`snyk-findings-export` scan the current workspace. Evo MCP’s `query_issues`
retrieves AI asset policy violations. [Studio export scope](https://github.com/snyk/studio-recipes/blob/3752dd05a462184dcce44af3c247f287b41e35de/plugins/codex/skills/snyk-findings-export/SKILL.md#L15-L20) · [Evo MCP tools](https://docs.snyk.io/agent-security/evo-by-snyk/platform-surfaces/evo-mcp-server#policies-and-issues)
### Native CLI JSON
For automation, use the [Snyk CLI](https://docs.snyk.io/developer-tools/snyk-cli/commands/test)
with `--json-file-output`. This preserves native descriptions, dependency paths,
identifiers and remediation evidence before the MCP or SARIF projections. For
example, run from the selected repository root:
To create a report, run the authenticated Snyk CLI with the project's package
tooling. For a project with `package.json`, run this from its root. Exit 1
means findings. A higher exit code stops acquisition. [Snyk CLI test](https://docs.snyk.io/developer-tools/snyk-cli/commands/test)
```sh
snyk_report=
report_dir=$(mktemp -d) || exit "$?"
snyk_status=0
snyk test --file=package.json --json-file-output=snyk-open-source.json || snyk_status=$?
snyk test --file=package.json --json-file-output="$report_dir/snyk-open-source.json" || snyk_status=$?
if [ "$snyk_status" -gt 1 ]; then
exit "$snyk_status"
fi
codex-security publish findings snyk-open-source.json --to cloud \
--provider snyk --repository https://github.com/example/project \
--source-key github.com/example/project/main/root/native-sca --dry-run
snyk_report="$report_dir/snyk-open-source.json"
```
Snyk exits 1 when it finds vulnerabilities. Other failures must stop acquisition;
do not publish an older report after a failed scan. `snyk test --json` emits the
same result to stdout. A single project object and the array produced by
`--all-projects` under one scan root are supported. For multiple projects, replace
`--file=package.json` with `--all-projects --fail-fast` and keep the exit-code
handling above. Snyk's [`--fail-fast` option](https://github.com/snyk/cli/blob/main/help/cli-commands/test.md#--fail-fast)
stops the scan when a project fails. Without it, Snyk continues and omits
vulnerability results for projects it could not scan. Keep independent scan roots
in separate reports and source keys; identical manifest and dependency paths from
different roots otherwise have ambiguous identities. A project error in the
supplied JSON stops the import, including an error mixed with successful results.
A successful empty scan has zero findings; a license-only report instead lists
its records as exclusions. Use the default ungrouped JSON output;
`--group-issues` combines package and dependency-path fields and is not supported.
For several projects under one scan root, use `--all-projects --fail-fast`
in place of `--file=package.json`. Without `--fail-fast`, Snyk can omit
projects it could not scan. Project errors present in the input stop import.
Keep independent scan roots in separate reports with separate keys.
The mapper follows the CLI's [native result types and dependency-path producer](https://github.com/snyk/cli/blob/main/src/lib/snyk-test/legacy.ts).
It preserves the complete selected vulnerability and the surrounding project
context. Identity uses the package manager, literal display manifest (falling back
to the target file), advisory, package name/version and dependency path. Different
occurrences remain separate. A duplicate identity is excluded rather than merged.
Native JSON does not establish a Git-root offset, repository URL or exact scanned
revision: paths and scan context stay in original evidence, without being claimed
as repository locations or manifest paths. Suggested upgrades and fixed versions
remain source advice, not verified patches.
A native occurrence is identified by package manager, manifest, advisory,
package name and version, and dependency path. The reader retains the
vulnerability, project context and suggested fixes. Manifest paths are
target-relative. [Native result fields](https://github.com/snyk/cli/blob/main/src/lib/snyk-test/legacy.ts)
To store this JSON locally, use the same file, provider and source key with
`--to local --repository .` from the repository root. No Cloud login is required.
### Snyk plugin export
From the repository's Git root, ask the Snyk plugin's `snyk-findings-export`
skill to run an SCA-only scan and save the bundle outside the checkout.
Use the bundle as input and a key ending in `plugin-sca`. The bundle retains
collection context, ignored status and each selected MCP record. The mapper
can shorten descriptions and omit alternate dependency paths. Paths are
target-relative. A dirty workspace does not establish the scanned commit.
[Install the Snyk plugin](https://github.com/snyk/studio-recipes/tree/main/plugins/codex)
and [SCA mapper](https://github.com/snyk/studio-mcp/blob/main/internal/oss/map.go)
### SARIF compatibility
Existing Open Source SARIF exports are still accepted. Generate one with
`snyk test --file=package.json --sarif-file-output=snyk-open-source.sarif` and
handle the exit code as above. For multiple projects, use `--all-projects --fail-fast`
with the same exit-code handling. Import with `--provider snyk` and a stable source
key ending in `sarif-sca`. The mapper follows the
[Open Source SARIF formatter](https://github.com/snyk/cli/blob/main/src/lib/formatters/open-source-sarif-output.ts).
It retains the selected rule, result and report context. Unrelated artifact
inventories are omitted when direct manifest locations do not depend on them;
indexed context and matching artifact metadata are retained. Empty
external-reference containers are accepted; reports with actual external property
references remain unsupported. SARIF groups an advisory's occurrences and exposes
one package coordinate, so native JSON is preferable for preserving individual
dependency paths and remediation fields. Manifest paths are literal target-relative
paths, including percent characters, without a Git-root offset. They stay in
original evidence with synthetic line numbers instead of being projected as
repository locations or package manifest paths. Snyk
Code, Container, IaC, external SARIF property files and indexed or base-relative
manifest locations are unsupported.
For SARIF, replace `--json-file-output` with `--sarif-file-output` and keep the
exit-code check above. Use a key ending in `sarif-sca`. SARIF groups an
advisory's occurrences and exposes one package coordinate. The reader
retains the rule, result and report context. Use a self-contained report. Manifest paths are
optional. If present, use direct URIs. Indexed or base-relative manifest
locations are unsupported. [Snyk Open Source SARIF formatter](https://github.com/snyk/cli/blob/main/src/lib/formatters/open-source-sarif-output.ts)
### Identities and provenance
All three formats support either destination, but their source IDs differ. Use
one acquisition format consistently for a repository, branch and scan target,
with a stable source key. Use a separate key if switching formats; the importer
does not guess equivalence between plugin occurrences, native JSON occurrences
and SARIF advisory groups. Switching does not remove earlier imported records.
Native JSON, plugin bundles and SARIF produce different source IDs. Give
each format a separate key. Changes in collection context such as a plugin
scan's `issueCount` can update a stored snapshot even if the occurrence
stays the same. [Imported evidence and identity](schema-guide.md)
Unsafe or absolute paths remain in original evidence. Known source repository
claims must match the selected Cloud repository or, for local imports when Git
remotes are configured, one of those remotes. For Cloud publication, standard SSH
remotes on the selected connected GitHub or GitHub Enterprise host match its HTTPS
repository when using the default SSH port or port 22. The public
`ssh://git@ssh.github.com:443/owner/repository.git` endpoint also matches
`github.com`. Other hosts, nondefault SSH ports and explicit HTTPS ports remain
distinct; the importer does not infer an Enterprise host from the artifact alone.
Unknown repository context requires the user to select the correct destination.
Gzip and UTF-8 BOM input are supported. Records exceeding the destination's
field or total-size limits appear as exclusions in the preview, without
truncation. Inspect preview exclusions before importing. Synthetic tests do
not establish live tenant, plugin-runtime or deployed Cloud compatibility.
Known source Git URLs must match a comparable configured local remote when
one is available, or the selected Cloud repository. Snyk Code, Container,
IaC, SBOM results and hosted backlog responses use other formats.
+64 -88
View File
@@ -1,117 +1,93 @@
# Import SonarQube Cloud security issues
# Import SonarQube Cloud findings
Import the open security issues for a SonarQube Cloud project or the issues
you selected in the SonarQube plugin for Codex. The live import uses the
authenticated `sonar` CLI to read findings from the project's Issues view.
Keep the same Sonar server and organization selected until the fetch finishes.
A live fetch saves a capture so you can review and publish the same records later.
Collect security issues for one project and branch or pull request. The
collector uses the authenticated Sonar CLI and saves the selection in a
capture you can import locally or publish to Cloud.
## Start in Codex
## Quick start
In the checkout, ask the SonarQube plugin to show security issues on a branch
or pull request. Then ask Codex Security to “import those two findings locally”
or “import those two findings locally and publish them to Codex Security Cloud.”
The [publish-findings skill](../../plugins/codex-security/skills/publish-findings/SKILL.md#sonarqube-cloud-issues)
uses the project's key, the selected ref, and the original Sonar issue keys to
retrieve the full records and preview the destination. You can also start in
the terminal with those same identifiers. If you installed only the Codex
Security plugin, install a version of `@openai/codex-security` that includes
the Sonar importer from a trusted directory, then run that CLI in the checkout.
## Preview a local import
Run the command from the matching checkout. Enable external imports for the
session. If you already use the Sonar plugin's issue list, the collector uses
the same `sonar` login. For first-time setup, sign in with `sonar auth login`
using an account that can browse the selected project.
[Enable external imports](README.md#preview-a-report). From the matching
checkout, sign in to the project's Sonar organization with browse access
(`sonar auth login`). Preview a selection using project and issue keys from
Sonar's Issues view or the SonarQube plugin for Codex.
[Sonar CLI authentication](https://docs.sonarsource.com/sonarqube-cli/quickstart-guide#step-2-authenticate)
```sh
export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1
codex-security import sonar --sonar-project example_project --sonar-branch main \
--sonar-issue ISSUE_A --sonar-issue ISSUE_B --dry-run --format json
```
For a pull request, replace `--sonar-branch main` with, for example,
`--sonar-pull-request 42`. With neither ref option, the collector reads the
project's main branch. Omit the issue options to collect open security
issues for the selected project and ref. If the search exceeds Sonar's
10,000-result window, pass the keys of the issues you want to import.
You can omit `--sonar-project` when
Sonar binds the checkout's Git origin to exactly one project in the signed-in
organization. For a monorepo with several Sonar projects, pass the project key
you want to import. If Sonar cannot supply the project's
repository binding, verify its Git URL in Sonar and retry the preview with
`import sonar CAPTURE --source-repository-url GIT_URL --dry-run --format json`
using the reported capture path. Check the target and selection before importing.
A selection by key includes the requested security issues regardless of
status. Omit `--sonar-issue` to preview open and confirmed security issues
for the selected ref. For a pull request, replace `--sonar-branch main` with
`--sonar-pull-request 42`. Omit both to use the project's main branch.
If the checkout uses an SSH host alias, supply the project's verified HTTPS URL
with `--source-repository-url` so the importer can compare the repository path.
The saved preview remembers that mapping for this checkout and its configured
fetch URLs, including when you preview the capture for Cloud. If the fetch URLs
change, verify the new mapping and preview again. SDK callers can pass the same
URL as `sourceRepositoryUrl` when preparing a local import.
## Import and verify
The preview saves a private copy even when the input is a file. Use the path
it returns in `capture` to import the reviewed evidence into the local
workbench. Use the preview's `repository` path to read the findings back:
Review the repository, ref, issues and exclusions in the `import sonar`
preview. Confirm using the private `capture` path it returned.
```sh
codex-security import sonar "/path/from/capture.json" --yes
codex-security findings imported "/checkout/from/preview" --format json
codex-security import sonar "/path/from/local-preview.json" --yes
```
For a portable capture, or if you change the checkout or Codex Security state
directory, run `--dry-run` there first and pass the returned path to `--yes`.
Codex Security keeps each Sonar issue key and its native evidence, including
reported file ranges and available data-flow traces. For monorepos, Codex
Security maps paths relative to the Sonar project when it can verify the
project's base directory in the checkout. When the base is unknown, the
native components, ranges and flows remain available in the evidence.
Reimporting the same issue in the same source and repository updates its
record. Imported records start as unassessed findings.
## Publish the same capture to Cloud
From the same checkout, preview the capture with your Codex Security Cloud
login. Your Cloud account must be enabled for external imports, and the
deployment must accept the `sonar` source provider. Review the Cloud account,
repository, environments, counts, and exclusions before confirming. Use
the `capture` path from this Cloud preview to confirm. If the destination
changes, preview again and confirm using the new path. Replaying the capture
works without a Sonar login. For a checkout without a usable Git remote,
verify the Sonar project's repository and pass `--source-repository-url` to
the Cloud preview. If the configured remotes point to another repository,
use the matching checkout or add its verified upstream remote before previewing.
To import locally **and** publish to Cloud, start from the same checkout.
Replay needs no Sonar login. Use a separate file-backed ChatGPT login with
access to the connected Cloud repository and an authorized environment on a
deployment that accepts the `sonar` provider. Review the Cloud account,
repository and environment, then confirm with the **new Cloud capture**.
```sh
codex-security import sonar "/path/from/local-preview.json" --to cloud --dry-run --format json
codex-security import sonar "/path/from/cloud-preview.json" --to cloud --yes
```
For a single local-and-Cloud workflow, add `--to cloud` to the first live
preview and confirm using its saved capture. If Cloud authentication or
repository selection fails, you can finish the local import, then rerun the
Cloud preview with the saved capture. If an approved upload is interrupted,
retry with the same file and destination.
Read back the local records in the preview's `repository` and check the Cloud
verification result if you published. Preview again if the checkout, state
directory or destination changes. To resume an interrupted upload, reuse the
approved capture and destination. [Readback and verification](README.md#save-or-publish-and-verify)
## Use a native JSON export
## Reference
If you already have the complete response from `GET /api/issues/search` for
one project and ref, save the page object or an array containing every page.
The file reader uses the repository URL you verified for that Sonar project:
### Project and repository selection
Omit `--sonar-project` only when the checkout's Git origin maps to exactly
one project in the active organization. For monorepos, supply the project
key. When a search exceeds 10,000 results, select issue keys.
[SonarQube plugin](https://www.sonarsource.com/blog/now-available-sonarqube-plugin-for-codex/)
and [Codex Security import workflow](../../plugins/codex-security/skills/publish-findings/SKILL.md#sonarqube-cloud-issues)
If Sonar lacks a repository binding, the checkout uses an SSH host alias or
Cloud preview finds no usable remote, verify the project's Git URL in Sonar.
Pass it as `--source-repository-url` when previewing the capture. At least
one comparable remote must match if the checkout has any. A changed fetch
URL requires a new preview.
Each Sonar issue key identifies one record within its source and repository.
Reimport updates its evidence, including file ranges and available data flows.
In a monorepo, repository-relative locations require a verified Sonar project
base directory.
### Use a native JSON export
For a saved `GET /api/issues/search` response, use a single page if it
contains the complete result. Otherwise supply an array of all pages in
order for the same project and ref. Pages can omit repository and ref context.
Run the example from the checkout root and supply its verified repository URL.
The example source key is for a new stream.
To update issues from an earlier capture, use its preview's `repository` path
for `--repository` and its exact `sourceKey` (`sonar:<hash>`) for `--source-key`.
The local `publish findings` preview shows `source.source_key`, and each stored
record has a `sourceKey`. Updating a matching issue replaces its evidence.
Native pages can omit the issue URL and repository-relative locations. Replay
the capture to preserve those fields, or use another key to store both versions.
```sh
codex-security publish findings "/path/to/sonar-pages.json" --provider sonar \
codex-security publish findings ../reports/sonar-pages.json --provider sonar \
--to local --repository . --source-repository-url https://github.com/example/project \
--source-key sonarcloud.io/example/example_project/branch/main --dry-run --format json
```
Keep the source key stable for the same Sonar instance, organization, project,
and ref. For updates to a previous import, use its exact source key. The
native page can omit the branch, project repository URL, and Sonar instance.
Only a Codex Security capture carries the collector's context for offline replay.
See [Sonar's Codex plugin](https://www.sonarsource.com/blog/now-available-sonarqube-plugin-for-codex/),
[Sonar CLI authentication](https://docs.sonarsource.com/sonarqube-cli/quickstart-guide#step-2-authenticate),
and the [Codex Security Cloud publication guide](../../sdk/typescript/docs/cli.md#publish-findings-to-cloud).
[Save and verify the native file](README.md#save-or-publish-and-verify) with the
same `publish findings` command.
+61 -61
View File
@@ -1,18 +1,56 @@
# Import Veracode Static Analysis policy findings
# Import Veracode Static Analysis findings
Use `--provider veracode` for the **Findings API** backlog of one Veracode
application mapped to one source repository. This importer handles
`scan_type=STATIC` in the application context. A Veracode application may
aggregate multiple repositories or binary modules: do not bind that aggregate
to a single checkout. Pipeline Scan JSON, sandboxes, SCA, DAST, policy pass/fail
summaries and the findings converter's SARIF output are not this format.
Import Findings API policy flaws from one Veracode application that maps to
one source repository. Use the application context and `scan_type=STATIC`.
## Export unmodified Findings API pages
## Quick start
Set `VERACODE_APPLICATION_GUID` to the application you intend to import. Use a
client with read access to that application and the Results API. This example
uses HTTPie with the Veracode HMAC plugin and `jq`. Set `api` to the hostname
for your region. Store the exported pages outside the checkout.
[Enable external imports](README.md#preview-a-report) and
[export the complete Findings API pages](#export-findings-api-pages) with read
access to the application and Results API. From the matching checkout root,
preview the file with its verified Git URL and a source key for this application.
```sh
codex-security publish findings /private/path/policy-findings.json \
--to local --repository . --provider veracode \
--source-repository-url https://github.com/example/project \
--source-key veracode/region/application-guid/static \
--dry-run --format json
```
## Import and verify
Verify the application represents the destination repository. An application
GUID or a backlog aggregated from several repositories cannot establish the
mapping. [Save or publish and verify](README.md#save-or-publish-and-verify)
using the same source key for repeat exports from this application and context.
## Reference
### Identity and evidence
The API origin, application and context, and native `issue_id` identify one
policy flaw. Build number, source line, CWE, and Pipeline flaw ID are separate
fields. The original record retains numeric severity, CWE, flaw description,
status, mitigation, and resolution. Location evidence includes the reported
static analysis path, line, and module. The importer does not verify that the
path exists in the checkout or infer a column or Git commit.
Imported findings start unassessed. Replaying an upstream resolution does not
verify a fix. Omitted findings remain stored. `veracode static scan <package>`
runs a new Pipeline Scan with different flaw IDs. Retrieve existing policy
flaws with the Findings API export below. Sandbox, SCA, DAST, policy summaries,
and converted SARIF also use other formats. [Veracode static scan](https://docs.veracode.com/r/veracode_static_scan)
For SDK replay with the Veracode provider, keep each finding’s original
`source_finding_id` and `evidence.source_data` so the SDK can verify its
application and repository.
### Export Findings API pages
Set `VERACODE_APPLICATION_GUID` to the application GUID and `api` to the API
origin for its region. This example uses HTTPie with the Veracode HMAC plugin
and `jq`. It writes `policy-findings.json` in the temporary directory `$out`.
```bash
set -eu
@@ -27,59 +65,21 @@ page=0
while :; do
http --ignore-stdin --check-status --body --timeout 20 --auth-type veracode_hmac GET \
"$api/appsec/v2/applications/$guid/findings" \
scan_type==STATIC page=="$page" size==100 > "$out/page.tmp"
scan_type==STATIC page=="$page" size==100 > "$out/page.tmp" || exit "$?"
pages=$(jq -er --arg app "$application" --argjson n "$page" '
select(._links.application.href == $app and .page.number == $n) |
.page.total_pages | numbers' "$out/page.tmp")
cat "$out/page.tmp" >> "$out/pages.stream"
.page.total_pages | numbers' "$out/page.tmp") || exit "$?"
cat "$out/page.tmp" >> "$out/pages.stream" || exit "$?"
page=$((page + 1))
[ "$page" -lt "$pages" ] || break
done
jq -s '.' "$out/pages.stream" > "$out/policy-findings.json"
jq -s '.' "$out/pages.stream" > "$out/report.tmp" &&
mv "$out/report.tmp" "$out/policy-findings.json"
```
Collect every page from the configured API host and keep each page intact.
Apply any Findings API filters when downloading the pages and use the same
selection throughout. The importer checks page counts, application scope and
the selection reported in the HAL links. Its preview includes the returned
rows with their original evidence, including any annotations. If the backlog
changes during pagination, collect it again.
## Preview and import
```bash
export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1
codex-security publish findings "$out/policy-findings.json" \
--to local --repository ./project --provider veracode \
--source-repository-url https://github.com/example/project \
--source-key veracode/region/application-guid/static \
--dry-run --format json
```
Review the destination, count and exclusions. Remove `--dry-run` to import.
Use the same source key for later exports from the same application and
context; an application GUID is not evidence of a Git URL. For Cloud use an
authorized GitHub repository and a deployment that accepts provider `veracode`.
Local import compares the source with the checkout’s Git remotes when
comparable remotes are configured.
If an interrupted Cloud upload reports `result.savedSubmission`, keep its
checkpoint and use the same build, state directory, account and import settings.
Preview the original export with `--dry-run --format json`. Check `accountId`
and `destination`. When `resumed` is false, review the new upload before approving it.
For `prepareNormalizedExternalPublication`, pass your original normalized
`ExternalFindings` and check `preview.resumed` before calling `publish()`.
Passing different normalized findings prepares a new upload. Save each finding
with its original `source_finding_id` and `evidence.source_data` so the SDK can
verify its application and repository when replayed with the Veracode provider.
| Veracode evidence | What Codex Security tracks |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| API origin, application/context and `issue_id` | A stable policy flaw occurrence. Build number, line, CWE and the separate Pipeline flaw ID are not its identity. |
| Native severity, CWE and flaw description | SAST evidence, preserving the original numeric severity, description and status in the raw record. |
| Static analysis path, line and module | Reported evidence, not proof that a similarly named file exists in the checkout. No fabricated column or Git commit. |
| Finding status, mitigation and resolution | Upstream workflow history, not a Codex assessment. Replaying an update does not mark a fix verified; omissions do not delete records. |
References: [Veracode Findings API](https://docs.veracode.com/r/c_findings_v2_intro),
[vendor-supported policy and Pipeline conversion examples](https://github.com/veracode/veracode-pipeline-scan-results-to-sarif).
Keep each page intact. Apply any Findings API filters when downloading the
pages and use the same selection throughout. The importer checks page counts,
application scope, and the selection reported in the HAL links. If the backlog
changes during pagination, collect it again. See the
[Veracode Findings API](https://docs.veracode.com/r/c_findings_v2_intro) and
[policy and Pipeline conversion examples](https://github.com/veracode/veracode-pipeline-scan-results-to-sarif).
+56
View File
@@ -0,0 +1,56 @@
# Import Wiz findings
Import saved Wiz package vulnerabilities, SAST findings, repository secrets or
IaC findings. The file reader accepts native JSON, normalized JSONL and detailed
repository package vulnerability CSV, including gzip-compressed files.
## Quick start
For package vulnerabilities, apply the requested repository, branch or build,
and finding filters where available in Wiz **Vulnerability Findings**. Choose
**Save as → Report**, then **Repository Branch**,
**JSON** and **Detailed** columns. Download the completed report outside the
checkout. From the destination checkout root, set the path and replace `TENANT_ID`
with your stable Wiz tenant identifier.
```sh
export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1
report=../reports/wiz-packages.json
codex-security publish findings "$report" \
--to local --repository . --provider wiz \
--source-key TENANT_ID/vulnerability-finding --dry-run --format json
```
## Import and verify
For an explicit selection, proceed only if the JSON preview's `excluded` array
is empty and `findings[].source_finding_id` lists each requested occurrence ID
exactly once, with its family prefix where applicable, and no other IDs.
Check that the preview covers the intended assets or builds and review excluded
records. Reuse the source key for the same tenant and finding family across
exports and project filters. [Save or publish and verify](README.md#save-or-publish-and-verify).
## Reference
- **Connected Wiz account.** List findings for the repository and family, then
retrieve the selected records by Wiz finding ID. If a shared pull request scan
event cannot identify each occurrence, request a scoped native capture.
- **Native JSON.** Package vulnerabilities accept individual records or
`data.vulnerabilityFindings.nodes`. SAST, repository secrets and IaC require
the named `data.sastFindings.nodes`, `data.secretInstances.nodes` or
`data.iacFindings.nodes` collection.
- **Paginated API or MCP results.** Check every finding and inventory page for
GraphQL `errors`, even when the page contains nodes. If any page reports an
error, resolve it and collect a complete selection before combining pages.
Put the selected nodes under the original collection name in one JSON object. If
findings use inventory to identify their repository, finish the inventory
pages too and combine their nodes under `data.versionControlResources.nodes`
in the same object. Retain the final page info for each collection. An array
or JSONL stream of GraphQL page envelopes cannot be imported.
- **CSV.** Use **Detailed** repository package vulnerability columns. The reader
requires a GitHub repository-branch URL and preserves each original cell.
Other finding families require native JSON or an explicit normalized mapping.
- Package findings retain the Wiz occurrence ID. SAST, repository secrets and
IaC use `sast:`, `secret:` and `iac:` ID prefixes. See the
[Wiz format reference](../../plugins/codex-security/skills/publish-findings/references/wiz-import.md#finding-formats)
for required fields, repository mapping and normalized JSONL.
+5 -17
View File
@@ -80,8 +80,8 @@ CONTENT_SHA256 = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcd
id: string,
path: string,
marker: string,
cwes: string[],
consumerMarker?: string,
cwes = ["CWE-798", "CWE-312", "CWE-313", "CWE-522"],
endMarker = marker,
) => {
const lines = files[path].split("\n");
@@ -104,23 +104,16 @@ CONTENT_SHA256 = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcd
"active-source",
"src/client.py",
"SERVICE_TOKEN =",
["CWE-798", "CWE-312", "CWE-313", "CWE-522"],
'"Authorization": "Bearer " + SERVICE_TOKEN',
),
positive("unused-source", "src/retired.py", "LEGACY_SERVICE_TOKEN =", [
"CWE-798",
"CWE-312",
"CWE-313",
"CWE-522",
]),
positive("unused-source", "src/retired.py", "LEGACY_SERVICE_TOKEN ="),
positive(
"integration-source",
"tests/test_delivery.py",
"INTEGRATION_TOKEN =",
["CWE-798", "CWE-312", "CWE-313", "CWE-522"],
'"Authorization": "Bearer " + INTEGRATION_TOKEN',
),
positive("dotenv-url", "config/.env", "DATABASE_URL=", [
positive("dotenv-url", "config/.env", "DATABASE_URL=", undefined, [
"CWE-798",
"CWE-256",
"CWE-259",
@@ -129,18 +122,13 @@ CONTENT_SHA256 = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcd
"CWE-313",
"CWE-522",
]),
positive("account-config", "config/service.json", '"client_secret"', [
"CWE-798",
"CWE-312",
"CWE-313",
"CWE-522",
]),
positive("account-config", "config/service.json", '"client_secret"'),
positive(
"private-key",
"src/signing.mjs",
"const signingKey",
["CWE-321", "CWE-798", "CWE-312", "CWE-313"],
"return sign(",
["CWE-321", "CWE-798", "CWE-312", "CWE-313"],
privateKey.trim().split("\n").at(-2),
),
],
+9 -17
View File
@@ -832,23 +832,15 @@ test("stages production prompt unchanged and no labels; grades only the final SD
);
return {
events: (async function* () {
yield {
type: "item.completed",
item: {
type: "agent_message",
text: JSON.stringify(retainedResult(prepared.fixture)),
},
};
yield {
type: "item.completed",
item: {
type: "agent_message",
text: JSON.stringify({
findings: [],
coverage: {},
}),
},
};
for (const result of [
retainedResult(prepared.fixture),
{ findings: [], coverage: {} },
]) {
yield {
type: "item.completed",
item: { type: "agent_message", text: JSON.stringify(result) },
};
}
yield {
type: "turn.completed",
usage: { input_tokens: 1, output_tokens: 1 },
+73 -124
View File
@@ -21,7 +21,7 @@ import { tmpdir } from "node:os";
import { syncBuiltinESMExports } from "node:module";
import { delimiter, dirname, join, win32 } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import test from "node:test";
import test, { type TestContext } from "node:test";
import { Codex } from "../../sdk/typescript/node_modules/@openai/codex-sdk/dist/index.js";
import {
codexSettings,
@@ -153,6 +153,33 @@ test("an eval does not overwrite a later replacement login", async (t) => {
);
});
async function captureSdkLaunch(
t: TestContext,
settings: ReturnType<typeof codexSettings>,
) {
const intercepted = new Error("Synthetic launch intercepted");
const spawn = t.mock.method(childProcess, "spawn", () => {
throw intercepted;
});
syncBuiltinESMExports();
try {
await assert.rejects(
async () => {
const { events } = await new Codex(settings)
.startThread({ skipGitRepoCheck: true })
.runStreamed("Offline synthetic launch check");
for await (const event of events) void event;
},
(error) => error === intercepted,
);
assert.equal(spawn.mock.callCount(), 1);
return spawn.mock.calls[0].arguments;
} finally {
spawn.mock.restore();
syncBuiltinESMExports();
}
}
test("the SDK launches long Windows paths with the native namespace prefix", async (t) => {
const executable = win32.join(
"C:\\synthetic",
@@ -171,29 +198,8 @@ test("the SDK launches long Windows paths with the native namespace prefix", asy
}
assert.equal(settings.env.CODEX_CLI_PATH, executable);
const intercepted = new Error("Synthetic launch intercepted");
let launched;
const spawn = t.mock.method(childProcess, "spawn", (file: string) => {
launched = file;
throw intercepted;
});
syncBuiltinESMExports();
try {
await assert.rejects(
async () => {
const { events } = await new Codex(settings)
.startThread({ skipGitRepoCheck: true })
.runStreamed("Offline synthetic launch check");
for await (const event of events) void event;
},
(error) => error === intercepted,
);
assert.equal(spawn.mock.callCount(), 1);
assert.equal(launched, win32.toNamespacedPath(executable));
} finally {
spawn.mock.restore();
syncBuiltinESMExports();
}
const [launched] = await captureSdkLaunch(t, settings);
assert.equal(launched, win32.toNamespacedPath(executable));
});
test("the SDK executable override preserves bundled tools at the child boundary", async (t) => {
@@ -209,57 +215,31 @@ test("the SDK executable override preserves bundled tools at the child boundary"
PATH: [tools, join(directory, "unix tools"), tools].join(delimiter),
};
const original = { ...inherited };
const intercepted = new Error("Synthetic launch intercepted");
const environments: NodeJS.ProcessEnv[] = [];
const spawn = t.mock.method(
childProcess,
"spawn",
(
_file: string,
_args: string[],
options: import("node:child_process").SpawnOptions,
) => {
environments.push(options.env!);
throw intercepted;
},
);
syncBuiltinESMExports();
try {
for (const environment of [{}, inherited]) {
await assert.rejects(
async () => {
const settings = codexSettings(directory, executable, environment);
const { events } = await new Codex(settings)
.startThread({ skipGitRepoCheck: true })
.runStreamed("Offline synthetic launch check");
for await (const event of events) void event;
},
(error) => error === intercepted,
);
}
assert.deepEqual(
environments.map((environment) =>
Object.fromEntries(
Object.entries(environment).filter(
([key]) => key.toLowerCase() === "path",
),
const environments = [];
for (const environment of [{}, inherited]) {
const settings = codexSettings(directory, executable, environment);
const [, , options] = await captureSdkLaunch(t, settings);
environments.push(options!.env!);
}
assert.deepEqual(
environments.map((environment) =>
Object.fromEntries(
Object.entries(environment).filter(
([key]) => key.toLowerCase() === "path",
),
),
[
{ PATH: tools },
process.platform === "win32"
? { Path: [tools, join(directory, "other tools")].join(delimiter) }
: {
...inherited,
PATH: [tools, join(directory, "unix tools")].join(delimiter),
},
],
);
assert.deepEqual(inherited, original);
} finally {
spawn.mock.restore();
syncBuiltinESMExports();
}
),
[
{ PATH: tools },
process.platform === "win32"
? { Path: [tools, join(directory, "other tools")].join(delimiter) }
: {
...inherited,
PATH: [tools, join(directory, "unix tools")].join(delimiter),
},
],
);
assert.deepEqual(inherited, original);
});
async function waitForFile(path: string) {
@@ -276,7 +256,7 @@ async function waitForFile(path: string) {
}
async function nativeFixture(
t: import("node:test").TestContext,
t: TestContext,
mode = "complete",
account: { type: string } | null = null,
) {
@@ -398,24 +378,18 @@ if (kind === "preflight") {
OPENAI_API_KEY: "synthetic-env-key",
DATABASE_URL: "synthetic-unrelated-secret",
});
return { directory, prepared, settings, executable, result };
const preflight = (initial = settings) =>
preflightEval(prepared, initial, new AbortController().signal);
return { directory, prepared, settings, executable, result, preflight };
}
test(
"native preflight and SDK exec share effective settings and fallback auth",
unixOnly,
async (t) => {
const {
directory,
prepared,
settings: original,
result,
} = await nativeFixture(t);
const settings = await preflightEval(
prepared,
original,
new AbortController().signal,
);
const native = await nativeFixture(t);
const { directory, prepared, settings: original, result } = native;
const settings = await native.preflight();
const { report, semanticResult } = await runPreparedEval(
prepared,
new Codex(settings),
@@ -508,25 +482,21 @@ for (const {
} of [
{
name: "missing file login",
account: null,
expectedKey: "synthetic-env-key",
},
{
name: "empty auth file",
authFile: "",
account: null,
expectedKey: "synthetic-env-key",
},
{
name: "malformed auth file",
authFile: "{",
account: null,
expectedKey: "synthetic-env-key",
},
{
name: "auth file without an account",
authFile: "{}",
account: null,
expectedKey: "synthetic-env-key",
},
{
@@ -541,7 +511,6 @@ for (const {
},
{
name: "blank Codex key",
account: null,
codexApiKey: " \t ",
expectedKey: "synthetic-env-key",
},
@@ -552,14 +521,11 @@ for (const {
codexApiKey: "synthetic-codex-key",
expectedKey: "synthetic-codex-key",
},
{ name: "blank OpenAI key", account: null, openAiApiKey: " \t " },
{ name: "blank OpenAI key", openAiApiKey: " \t " },
]) {
test(`native auth precedence with ${name}`, unixOnly, async (t) => {
const {
directory,
prepared,
settings: original,
} = await nativeFixture(t, "complete", account);
const native = await nativeFixture(t, "complete", account);
const { directory, prepared, settings: original } = native;
const ambient = original.env.CODEX_HOME;
if (authFile !== undefined)
await writeFile(join(ambient, "auth.json"), authFile);
@@ -569,11 +535,7 @@ for (const {
CODEX_API_KEY: codexApiKey,
OPENAI_API_KEY: openAiApiKey,
});
const settings = await preflightEval(
prepared,
initialSettings,
new AbortController().signal,
);
const settings = await native.preflight(initialSettings);
const { report } = await runPreparedEval(prepared, new Codex(settings));
assert.equal(report.passed, true);
assert.equal(initialSettings.apiKey, undefined);
@@ -609,11 +571,8 @@ for (const codexApiKey of [undefined, "synthetic-explicit-key"]) {
`Windows mixed-case auth snapshot with ${codexApiKey ? "explicit" : "fallback"} key`,
unixOnly,
async (t) => {
const {
directory,
prepared,
settings: original,
} = await nativeFixture(t);
const native = await nativeFixture(t);
const { directory, prepared, settings: original } = native;
const {
OPENAI_API_KEY,
Path: ignoredPathAlias,
@@ -632,11 +591,7 @@ for (const codexApiKey of [undefined, "synthetic-explicit-key"]) {
);
assert.equal(snapshot.env.OPENAI_API_KEY, undefined);
assert.equal(snapshot.env.OpenAI_API_Key, environment.OpenAI_API_Key);
settings = await preflightEval(
prepared,
snapshot,
new AbortController().signal,
);
settings = await native.preflight(snapshot);
} finally {
Object.defineProperty(process, "platform", platform!);
}
@@ -661,13 +616,10 @@ for (const [mode, expectedError] of [
["account-error", /account\/read/],
] as const) {
test(`${mode} prevents starting the SDK exec turn`, unixOnly, async (t) => {
const { directory, prepared, settings } = await nativeFixture(t, mode);
const native = await nativeFixture(t, mode);
const { directory, prepared } = native;
await assert.rejects(async () => {
const resolved = await preflightEval(
prepared,
settings,
new AbortController().signal,
);
const resolved = await native.preflight();
await runPreparedEval(prepared, new Codex(resolved));
}, expectedError);
await assert.rejects(access(join(directory, "exec.json")), {
@@ -682,12 +634,9 @@ for (const mode of ["fallback-item", "fallback-error"]) {
`${mode} aborts the real SDK turn and discards its response`,
unixOnly,
async (t) => {
const { directory, prepared, settings } = await nativeFixture(t, mode);
const resolved = await preflightEval(
prepared,
settings,
new AbortController().signal,
);
const native = await nativeFixture(t, mode);
const { directory, prepared } = native;
const resolved = await native.preflight();
await assert.rejects(
runPreparedEval(prepared, new Codex(resolved)),
/results were discarded/,
@@ -1,4 +1,8 @@
import { outputText as textFor, hasTriageJson } from "./output.mts";
import {
gradeFailures,
outputText as textFor,
hasTriageJson,
} from "./output.mts";
import type { AssertionContext } from "../types.ts";
function repositoryName(value: string) {
@@ -259,12 +263,5 @@ export default (output: unknown, context: AssertionContext) => {
? check(text, context)
: [`unknown expected_github_rest_behavior: ${behavior}`];
return {
pass: failures.length === 0,
score: failures.length === 0 ? 1 : 0,
reason:
failures.length === 0
? "GitHub REST intake behavior matched."
: failures.join("; "),
};
return gradeFailures(failures, "GitHub REST intake behavior matched.");
};
@@ -1,4 +1,4 @@
import { outputText, hasTriageJson } from "./output.mts";
import { gradeFailures, outputText, hasTriageJson } from "./output.mts";
function matchedFormatNames(text: string) {
const supportedFormats: [string, RegExp][] = [
@@ -46,12 +46,8 @@ export default (output: unknown) => {
);
}
return {
pass: failures.length === 0,
score: failures.length === 0 ? 1 : 0,
reason:
failures.length === 0
? "Missing-input response asks for a finding and names supported formats without triage JSON."
: failures.join("; "),
};
return gradeFailures(
failures,
"Missing-input response asks for a finding and names supported formats without triage JSON.",
);
};
@@ -1,5 +1,14 @@
import type { TriageResult } from "../types.ts";
export function gradeFailures(failures: string[], successReason: string) {
const pass = failures.length === 0;
return {
pass,
score: pass ? 1 : 0,
reason: pass ? successReason : failures.join("; "),
};
}
export function outputText(output: unknown) {
return typeof output === "string" ? output : JSON.stringify(output);
}
@@ -1,4 +1,4 @@
import { outputText, hasTriageJson } from "./output.mts";
import { gradeFailures, outputText, hasTriageJson } from "./output.mts";
import type { AssertionContext } from "../types.ts";
const expectedPatterns: Record<string, RegExp[]> = {
@@ -52,33 +52,27 @@ export default (output: unknown, context: AssertionContext) => {
const subissueBehavior = String(context.vars.expected_linear_subissues || "");
const patterns = Object.hasOwn(expectedPatterns, behavior)
? expectedPatterns[behavior]
: [];
: undefined;
const subissuePatterns = Object.hasOwn(
expectedSubissuePatterns,
subissueBehavior,
)
? expectedSubissuePatterns[subissueBehavior]
: [];
: undefined;
const failures = [];
if (
(!behavior && !subissueBehavior) ||
(behavior && !Object.hasOwn(expectedPatterns, behavior))
) {
if ((!behavior && !subissueBehavior) || (behavior && !patterns)) {
failures.push(`unknown expected_ticket_failure: ${behavior}`);
}
if (
subissueBehavior &&
!Object.hasOwn(expectedSubissuePatterns, subissueBehavior)
) {
if (subissueBehavior && !subissuePatterns) {
failures.push(`unknown expected_linear_subissues: ${subissueBehavior}`);
}
for (const pattern of patterns) {
for (const pattern of patterns ?? []) {
if (!pattern.test(text))
failures.push(`missing recovery detail matching ${pattern}`);
}
for (const pattern of subissuePatterns) {
for (const pattern of subissuePatterns ?? []) {
if (!pattern.test(text))
failures.push(`missing Linear sub-issue detail matching ${pattern}`);
}
@@ -92,12 +86,8 @@ export default (output: unknown, context: AssertionContext) => {
failures.push("must stop before repository analysis or verdicting");
}
return {
pass: failures.length === 0,
score: failures.length === 0 ? 1 : 0,
reason:
failures.length === 0
? "Ticket connector failure produced recovery guidance without triage output."
: failures.join("; "),
};
return gradeFailures(
failures,
"Ticket connector failure produced recovery guidance without triage output.",
);
};
+27 -49
View File
@@ -1,26 +1,9 @@
import type { AssertionContext } from "../types.ts";
import { extractTriageResult, parseExpected } from "./output.mts";
function expectedScanbenchMapping(context: AssertionContext) {
const label = String(context.vars.expected_binary_label || "");
const mappings = [];
if (label === "positive") {
mappings.push({
expectedVerdict: "confirmed",
expectedBinaryLabel: "positive",
label: "positive scanbench label",
});
} else if (label === "negative") {
mappings.push({
expectedVerdict: "not_actionable",
expectedBinaryLabel: "negative",
label: "negative scanbench label",
});
}
return mappings;
}
import {
gradeFailures,
extractTriageResult,
parseExpected,
} from "./output.mts";
export default (output: unknown, context: AssertionContext) => {
const result = extractTriageResult(
@@ -32,21 +15,24 @@ export default (output: unknown, context: AssertionContext) => {
const expectedVerdicts = parseExpected(context.vars.expected_verdicts);
const failures = [];
for (const mapping of expectedScanbenchMapping(context)) {
const binaryLabel = String(context.vars.expected_binary_label || "");
if (binaryLabel === "positive" || binaryLabel === "negative") {
const expectedVerdict =
binaryLabel === "positive" ? "confirmed" : "not_actionable";
if (
expectedVerdicts.length === 1 &&
expectedVerdicts[0] !== mapping.expectedVerdict
expectedVerdicts[0] !== expectedVerdict
) {
failures.push(
`${mapping.label}: expected_verdicts must be ${mapping.expectedVerdict}, got ${expectedVerdicts[0]}`,
`${binaryLabel} scanbench label: expected_verdicts must be ${expectedVerdict}, got ${expectedVerdicts[0]}`,
);
}
if (
context.vars.expected_binary_label &&
context.vars.expected_binary_label !== mapping.expectedBinaryLabel
context.vars.expected_binary_label !== binaryLabel
) {
failures.push(
`${mapping.label}: expected_binary_label must be ${mapping.expectedBinaryLabel}, got ${context.vars.expected_binary_label}`,
`${binaryLabel} scanbench label: expected_binary_label must be ${binaryLabel}, got ${context.vars.expected_binary_label}`,
);
}
}
@@ -67,20 +53,16 @@ export default (output: unknown, context: AssertionContext) => {
findings.forEach((finding, index) => {
const label = expectedIds[index] || `index ${index}`;
if (finding.input_id !== expectedIds[index]) {
failures.push(
`${label}: expected input_id ${expectedIds[index]}, got ${finding.input_id}`,
);
}
if (finding.source_type !== expectedSourceTypes[index]) {
failures.push(
`${label}: expected source_type ${expectedSourceTypes[index]}, got ${finding.source_type}`,
);
}
if (finding.verdict !== expectedVerdicts[index]) {
failures.push(
`${label}: expected verdict ${expectedVerdicts[index]}, got ${finding.verdict}`,
);
for (const [field, expected] of [
["input_id", expectedIds[index]],
["source_type", expectedSourceTypes[index]],
["verdict", expectedVerdicts[index]],
] as const) {
if (finding[field] !== expected) {
failures.push(
`${label}: expected ${field} ${expected}, got ${finding[field]}`,
);
}
}
const rank = finding.exploitability_stack_rank?.rank;
@@ -146,12 +128,8 @@ export default (output: unknown, context: AssertionContext) => {
});
}
return {
pass: failures.length === 0,
score: failures.length === 0 ? 1 : 0,
reason:
failures.length === 0
? "Triage I/O matched expected source types, order, and verdicts."
: failures.join("; "),
};
return gradeFailures(
failures,
"Triage I/O matched expected source types, order, and verdicts.",
);
};
@@ -48,11 +48,7 @@ assert.throws(() => extractTriageResult(truncated), {
message: "Could not find a parseable triage-finding/v0 JSON result",
});
const truncatedMetrics = addSastBenchMetrics(
extensionContext({
caseId: "sastbench-000000",
expectedGroundTruth: "true_positive",
output: truncated,
}),
extensionContext("sastbench-000000", "true_positive", { output: truncated }),
).result;
assert.equal(truncatedMetrics.metadata.sastbench.status, "invalid_output");
assert.equal(truncatedMetrics.namedScores.invalid_output, 1);
@@ -71,11 +67,7 @@ for (const output of [
"confirmed",
);
const result = addSastBenchMetrics(
extensionContext({
caseId: "sastbench-000000",
expectedGroundTruth: "true_positive",
output,
}),
extensionContext("sastbench-000000", "true_positive", { output }),
).result;
assert.equal(result.metadata.sastbench.status, "ok");
assert.equal(result.namedScores.strict_tp, 1);
@@ -121,23 +113,16 @@ assert.equal(
false,
);
function extensionContext({
caseId,
expectedGroundTruth,
output,
error,
sampleWeight,
}: {
caseId: string;
expectedGroundTruth: string;
output?: string;
error?: string;
sampleWeight?: number;
}) {
function extensionContext(
caseId: string,
groundTruth: string,
{ output, error }: { output?: string; error?: string },
sampleWeight?: number,
) {
return {
test: {
metadata: {
ground_truth: expectedGroundTruth,
ground_truth: groundTruth,
...(sampleWeight === undefined ? {} : { sample_weight: sampleWeight }),
},
},
@@ -159,43 +144,16 @@ function extensionContext({
};
}
const outcomes = [
{
caseId: "tp-confirmed",
expectedGroundTruth: "true_positive",
verdict: "confirmed",
},
{
caseId: "tp-closed",
expectedGroundTruth: "true_positive",
verdict: "not_actionable",
},
{
caseId: "tp-review",
expectedGroundTruth: "true_positive",
verdict: "needs_review",
},
{
caseId: "fp-closed",
expectedGroundTruth: "false_positive",
verdict: "not_actionable",
},
{
caseId: "fp-confirmed",
expectedGroundTruth: "false_positive",
verdict: "confirmed",
},
{
caseId: "fp-review",
expectedGroundTruth: "false_positive",
verdict: "needs_review",
},
];
const nativeContexts = outcomes.map((outcome) =>
extensionContext({
caseId: outcome.caseId,
expectedGroundTruth: outcome.expectedGroundTruth,
output: JSON.stringify(triageResult(outcome.verdict, outcome.caseId)),
const nativeContexts = [
["tp-confirmed", "true_positive", "confirmed"],
["tp-closed", "true_positive", "not_actionable"],
["tp-review", "true_positive", "needs_review"],
["fp-closed", "false_positive", "not_actionable"],
["fp-confirmed", "false_positive", "confirmed"],
["fp-review", "false_positive", "needs_review"],
].map(([caseId, groundTruth, verdict]) =>
extensionContext(caseId, groundTruth, {
output: JSON.stringify(triageResult(verdict, caseId)),
}),
);
const nativeMetricRows = nativeContexts.map(addSastBenchMetrics);
@@ -239,54 +197,33 @@ assert.equal(totals.execution_or_parse_error, 0);
assert.equal(totals.existing_metric, 6);
const positiveProviderError = addSastBenchMetrics(
extensionContext({
caseId: "tp-error",
expectedGroundTruth: "true_positive",
error: "provider failed",
}),
);
assert.equal(positiveProviderError.result.namedScores.strict_fn, 1);
assert.equal(
positiveProviderError.result.namedScores.execution_or_parse_error,
1,
);
assert.equal(
positiveProviderError.result.namedScores.remaining_analyst_work,
1,
);
assert.equal(
positiveProviderError.result.metadata.sastbench.status,
"model_error",
);
extensionContext("tp-error", "true_positive", { error: "provider failed" }),
).result;
assert.equal(positiveProviderError.namedScores.strict_fn, 1);
assert.equal(positiveProviderError.namedScores.execution_or_parse_error, 1);
assert.equal(positiveProviderError.namedScores.remaining_analyst_work, 1);
assert.equal(positiveProviderError.metadata.sastbench.status, "model_error");
const negativeInvalidOutput = addSastBenchMetrics(
extensionContext({
caseId: "fp-invalid",
expectedGroundTruth: "false_positive",
extensionContext("fp-invalid", "false_positive", {
output: "not a triage result",
}),
);
assert.equal(negativeInvalidOutput.result.namedScores.strict_fp, 1);
assert.equal(
negativeInvalidOutput.result.namedScores.execution_or_parse_error,
1,
);
assert.equal(
negativeInvalidOutput.result.metadata.sastbench.status,
"invalid_output",
);
).result;
assert.equal(negativeInvalidOutput.namedScores.strict_fp, 1);
assert.equal(negativeInvalidOutput.namedScores.execution_or_parse_error, 1);
assert.equal(negativeInvalidOutput.metadata.sastbench.status, "invalid_output");
const weightedPositive = addSastBenchMetrics(
extensionContext({
caseId: "weighted-tp",
expectedGroundTruth: "true_positive",
output: JSON.stringify(triageResult("confirmed", "weighted-tp")),
sampleWeight: 2.5,
}),
);
assert.equal(weightedPositive.result.namedScores.strict_tp, 2.5);
assert.equal(weightedPositive.result.namedScores.positive_cases, 2.5);
assert.equal(weightedPositive.result.namedScores.existing_metric, 1);
extensionContext(
"weighted-tp",
"true_positive",
{ output: JSON.stringify(triageResult("confirmed", "weighted-tp")) },
2.5,
),
).result;
assert.equal(weightedPositive.namedScores.strict_tp, 2.5);
assert.equal(weightedPositive.namedScores.positive_cases, 2.5);
assert.equal(weightedPositive.namedScores.existing_metric, 1);
const firstResult = nativeMetricRows[0].result;
assert.equal(firstResult.metadata.sastbench.status, "ok");
@@ -295,12 +232,9 @@ assert.equal(firstResult.latencyMs, 1234);
assert.equal(firstResult.cost, 0.25);
assert.equal(firstResult.response, nativeContexts[0].result.response);
assert.match(
negativeInvalidOutput.result.metadata.sastbench.error!,
negativeInvalidOutput.metadata.sastbench.error!,
/triage-finding\/v0/,
);
assert.equal(
positiveProviderError.result.metadata.sastbench.error,
"provider failed",
);
assert.equal(positiveProviderError.metadata.sastbench.error, "provider failed");
console.log("sastbench result and native metric tests passed");
@@ -138,6 +138,10 @@ const githubContext = (behavior: string) => ({
target_repo: "https://github.com/example/project",
},
});
function expectGitHub(behavior: string, text: string, pass = true) {
expectPass(github, text, githubContext(behavior), pass);
}
for (const repository of ["{owner}/{repo}", "example/project"]) {
for (const sourceType of [
"source_type: advisory",
@@ -150,15 +154,13 @@ for (const repository of ["{owner}/{repo}", "example/project"]) {
"source_type: advisory.",
"source_type: advisory!",
]) {
expectPass(
github,
expectGitHub(
"dependabot_malware",
`GET /repos/${repository}/dependabot/alerts?classification=malware&state=open&per_page=100. ${sourceType}`,
githubContext("dependabot_malware"),
);
expectPass(
github,
expectGitHub(
"advisories_private_reports",
`GET /repos/${repository}/security-advisories?per_page=100, with separate state=triage, state=draft, state=published, state=closed requests. Triage is for private vulnerability reports. ${sourceType}`,
githubContext("advisories_private_reports"),
);
}
}
@@ -175,12 +177,7 @@ for (const repository of ["{owner}/{repo}", "example/project"]) {
"_wrong",
"Extra",
]) {
expectPass(
github,
output.replaceAll("?", `${suffix}?`),
githubContext(behavior),
false,
);
expectGitHub(behavior, output.replaceAll("?", `${suffix}?`), false);
}
for (const delimiter of [
"\n",
@@ -194,11 +191,7 @@ for (const repository of ["{owner}/{repo}", "example/project"]) {
": ",
"] ",
]) {
expectPass(
github,
output.replaceAll("?", `${delimiter}?`),
githubContext(behavior),
);
expectGitHub(behavior, output.replaceAll("?", `${delimiter}?`));
}
}
}
@@ -217,16 +210,15 @@ for (const repository of ["{owner}/{repo}", "example/project"]) {
const answer = JSON.parse(
JSON.stringify(codeScanning).replaceAll("example/project", repository),
);
expectPass(
github,
expectGitHub(
"code_scanning",
JSON.stringify(answer).replaceAll(":100", ':"100"'),
githubContext("code_scanning"),
);
for (const text of [
JSON.stringify(answer),
`\`\`\`json\n${JSON.stringify(answer)}\n\`\`\``,
]) {
expectPass(github, text, githubContext("code_scanning"));
expectGitHub("code_scanning", text);
}
}
for (const invalid of [
@@ -261,19 +253,13 @@ for (const invalid of [
alerts: { ...codeScanning.alerts, parameters: { state: "open" } },
},
]) {
expectPass(
github,
JSON.stringify(invalid),
githubContext("code_scanning"),
false,
);
expectGitHub("code_scanning", JSON.stringify(invalid), false);
}
expectPass(github, "not JSON", githubContext("code_scanning"), false);
expectGitHub("code_scanning", "not JSON", false);
expectPass(
github,
expectGitHub(
"explicit_issue",
'GitHub Issues require an explicit issue and are not included in all sources. source_type: "freeform"',
githubContext("explicit_issue"),
);
for (const text of [
'GET /repos/example/other/dependabot/alerts?classification=malware&state=open&per_page=100. source_type: "advisory"',
@@ -287,7 +273,7 @@ for (const text of [
'GET /repos/example/project/dependabot/alerts?classification=malware&state=open&per_page=100. {"source_type_suffix":"advisory"}',
"GET /repos/example/project/dependabot/alerts?classification=malware&state=open&per_page=100. source_type: advisory_other",
]) {
expectPass(github, text, githubContext("dependabot_malware"), false);
expectGitHub("dependabot_malware", text, false);
}
for (const emphasis of ["**", "*", "__", "_", "***"]) {
@@ -296,10 +282,9 @@ for (const emphasis of ["**", "*", "__", "_", "***"]) {
`Normalize as ${emphasis}advisory${emphasis}`,
`${emphasis}source_type${emphasis}: advisory`,
]) {
expectPass(
github,
expectGitHub(
"dependabot_malware",
`GET /repos/example/project/dependabot/alerts?classification=malware&state=open&per_page=100. ${normalization}.`,
githubContext("dependabot_malware"),
);
}
for (const normalization of [
@@ -314,16 +299,14 @@ for (const emphasis of ["**", "*", "__", "_", "***"]) {
"Normalize as advisory: preserve the identifier",
"Normalization: source_type: advisory",
]) {
expectPass(
github,
expectGitHub(
"dependabot_malware",
`GET /repos/example/project/dependabot/alerts?classification=malware&state=open&per_page=100. ${emphasis}${normalization}${emphasis}.`,
githubContext("dependabot_malware"),
);
}
expectPass(
github,
expectGitHub(
"dependabot_malware",
`GET /repos/example/project/dependabot/alerts?classification=malware&state=open&per_page=100. ${emphasis}source_type: advisory_other${emphasis}`,
githubContext("dependabot_malware"),
false,
);
}
@@ -338,7 +321,7 @@ const decision = {
};
const connectorJson = JSON.stringify(decision);
for (const text of [connectorJson, `\`\`\`json\n${connectorJson}\n\`\`\``]) {
expectPass(github, text, githubContext("explicit_connector"));
expectGitHub("explicit_connector", text);
}
for (const invalid of [
null,
@@ -361,22 +344,17 @@ for (const invalid of [
{ ...decision, explanation: "additional field" },
{ ...decision, scope: { ...decision.scope, extra: true } },
]) {
expectPass(
github,
JSON.stringify(invalid),
githubContext("explicit_connector"),
false,
);
expectGitHub("explicit_connector", JSON.stringify(invalid), false);
}
for (const text of [
"not JSON",
`\`\`\`json\n${connectorJson}\n\`\`\`\n\`\`\`json\n{}\n\`\`\``,
]) {
expectPass(github, text, githubContext("explicit_connector"), false);
expectGitHub("explicit_connector", text, false);
}
const restJson = JSON.stringify({ transport: "rest" });
for (const text of [restJson, `\`\`\`json\n${restJson}\n\`\`\``]) {
expectPass(github, text, githubContext("default_rest"));
expectGitHub("default_rest", text);
}
for (const invalid of [
null,
@@ -386,12 +364,7 @@ for (const invalid of [
{ transport: "other" },
{ transport: "rest", findings: [] },
]) {
expectPass(
github,
JSON.stringify(invalid),
githubContext("default_rest"),
false,
);
expectGitHub("default_rest", JSON.stringify(invalid), false);
}
for (const [behavior, answer] of [
["explicit_connector", connectorJson],
@@ -411,13 +384,13 @@ for (const [behavior, answer] of [
`${answer}\n${extra}`,
`\`\`\`json\n${answer}\n\`\`\`\n\`\`\`json\n${extra}\n\`\`\``,
]) {
expectPass(github, text, githubContext(behavior), false);
expectGitHub(behavior, text, false);
}
}
}
for (const behavior of ["", "code_scaning", "constructor"]) {
expectPass(github, "arbitrary text", githubContext(behavior), false);
expectGitHub(behavior, "arbitrary text", false);
}
for (const repository of [
+88 -138
View File
@@ -3,55 +3,50 @@ import assert from "assert";
import fs from "node:fs";
import path from "node:path";
import vm from "node:vm";
import { parse } from "yaml";
import triageIo from "../assertions/triage-io.mts";
import type { TriageFinding } from "../types.ts";
function outputFor({
inputId,
verdict,
sourceType = "cve",
}: {
inputId: string;
verdict: string;
sourceType?: string;
}) {
const stackRank = {
rank_queue: verdict === "not_actionable" ? null : verdict,
rank: verdict === "not_actionable" ? null : 1,
rationale:
verdict === "not_actionable" ? "not actionable" : "Example ranking",
drivers: [],
function findingFor(
inputId: string,
verdict: string,
rank: number | null = verdict === "not_actionable" ? null : 1,
rankQueue: string | null = verdict === "not_actionable" ? null : verdict,
) {
return {
triage_item_id: "triage-001",
input_id: inputId,
source_type: "cve",
title: "Example finding",
normalized_input: {},
verdict,
confidence: "high",
exploitability_stack_rank: {
rank,
rank_queue: rankQueue,
rationale:
verdict === "not_actionable" ? "not actionable" : "Example ranking",
drivers: [],
},
affected_locations: [],
reachable_path: [],
evidence: [],
counterevidence: [],
proof_gaps: [],
recommended_next_step: "No action",
fix_finding_handoff: verdict === "confirmed" ? "Fix handoff" : null,
};
return `\`\`\`json
{
"schema_version": "triage-finding/v0",
"repository": {
"path": "/tmp/repo",
"revision": "abc123"
},
"findings": [
{
"triage_item_id": "triage-001",
"input_id": "${inputId}",
"source_type": "${sourceType}",
"title": "Example finding",
"normalized_input": {},
"verdict": "${verdict}",
"confidence": "high",
"exploitability_stack_rank": ${JSON.stringify(stackRank)},
"affected_locations": [],
"reachable_path": [],
"evidence": [],
"counterevidence": [],
"proof_gaps": [],
"recommended_next_step": "No action",
"fix_finding_handoff": ${verdict === "confirmed" ? JSON.stringify("Fix handoff") : "null"}
}
]
}
\`\`\``;
}
const documentFor = (findings: TriageFinding[]) => ({
schema_version: "triage-finding/v0",
repository: { path: "/tmp/repo", revision: "abc123" },
findings,
});
const queueOutput = (findings: TriageFinding[]) =>
JSON.stringify({ schema_version: "triage-finding/v0", findings });
function assertPasses(
name: string,
output: unknown,
@@ -76,75 +71,42 @@ function assertFails(
);
}
const sourceType = "cve";
assertPasses(
"vulnerable scanbench cases map to confirmed/positive",
outputFor({
inputId: "input-001",
verdict: "confirmed",
}).replace('"evidence": []', '"evidence": ["Inline ``` fence in source."]'),
{
for (const [id, verdict, label, error] of [
["input-001", "confirmed", "positive", null],
["input-002", "not_actionable", "negative", null],
["input-002", "confirmed", "negative", /fixed.*not_actionable|negative/],
] as const) {
const finding = findingFor(id, verdict);
const output =
"```json\n" +
JSON.stringify(
documentFor([
{
...finding,
evidence: label === "positive" ? ["Inline ``` fence in source."] : [],
},
]),
null,
2,
) +
"\n```";
const context = {
vars: {
case_id: "case-001",
expected_ids: "input-001",
expected_source_types: sourceType,
expected_verdicts: "confirmed",
expected_binary_label: "positive",
case_id: label === "positive" ? "case-001" : "case-002",
expected_ids: id,
expected_source_types: "cve",
expected_verdicts: verdict,
expected_binary_label: label,
},
},
);
assertPasses(
"fixed scanbench cases map to not_actionable/negative",
outputFor({
inputId: "input-002",
verdict: "not_actionable",
}),
{
vars: {
case_id: "case-002",
expected_ids: "input-002",
expected_source_types: sourceType,
expected_verdicts: "not_actionable",
expected_binary_label: "negative",
},
},
);
assertFails(
"fixed scanbench cases cannot be labeled confirmed",
outputFor({
inputId: "input-002",
verdict: "confirmed",
}),
{
vars: {
case_id: "case-002",
expected_ids: "input-002",
expected_source_types: sourceType,
expected_verdicts: "confirmed",
expected_binary_label: "negative",
},
},
/fixed.*not_actionable|negative/,
);
function findingFor(
inputId: string,
verdict: string,
rank: number | null,
rankQueue: string | null = verdict,
) {
const finding: TriageFinding = JSON.parse(
outputFor({ inputId, verdict }).split("```json")[1].split("```")[0],
).findings[0];
finding.exploitability_stack_rank = {
...finding.exploitability_stack_rank,
rank,
rank_queue: rankQueue,
};
return finding;
if (error)
assertFails(
"fixed scanbench case cannot be confirmed",
output,
context,
error,
);
else assertPasses(`${verdict} maps to ${label}`, output, context);
}
const queueFindings = [
@@ -161,8 +123,6 @@ const contextFor = (findings: TriageFinding[]) => ({
},
});
const queueContext = contextFor(queueFindings);
const queueOutput = (findings: TriageFinding[]) =>
JSON.stringify({ schema_version: "triage-finding/v0", findings });
assertPasses(
"independent verdict queues",
queueOutput(queueFindings),
@@ -242,39 +202,29 @@ const inputCases = fs.readFileSync(
path.resolve(import.meta.dirname, "../tests/input-types.yaml"),
"utf8",
);
const scannerCase = inputCases.match(
/case_id: scanner-query[\s\S]*?(?=\n- description:|$)/,
)![0];
const scannerVars: Record<string, string> = { case_id: "scanner-query" };
const scannerContext = { vars: scannerVars };
for (const field of [
"expected_ids",
"expected_source_types",
"expected_verdicts",
]) {
scannerVars[field] = scannerCase.match(new RegExp(field + ": (.+)"))![1];
}
function queryVerdict(inputId: string, verdict: string) {
return JSON.parse(
outputFor({ inputId, sourceType: "scanner_ticket", verdict }).match(
/```json\n([\s\S]*?)\n```/,
)![1],
);
}
const queryOutput = queryVerdict("SCAN-SQL-001", "not_actionable");
queryOutput.findings.push(
queryVerdict("SCAN-SQL-TEST-ONLY", "not_actionable").findings[0],
);
queryOutput.findings[1].triage_item_id = "triage-002";
const scannerContext = (
parse(inputCases) as { vars: Record<string, string> }[]
).find((item) => item.vars.case_id === "scanner-query")!;
const scannerFinding = (id: string, verdict: string) => ({
...findingFor(id, verdict),
source_type: "scanner_ticket",
});
const queryFindings = [
scannerFinding("SCAN-SQL-001", "not_actionable"),
{
...scannerFinding("SCAN-SQL-TEST-ONLY", "not_actionable"),
triage_item_id: "triage-002",
},
];
assertPasses(
"a SQL text response is not confirmed SQL injection",
JSON.stringify(queryOutput),
JSON.stringify(documentFor(queryFindings)),
scannerContext,
);
queryOutput.findings[0] = queryVerdict("SCAN-SQL-001", "confirmed").findings[0];
queryFindings[0] = scannerFinding("SCAN-SQL-001", "confirmed");
assertFails(
"a missing SQL sink cannot earn a confirmed verdict",
JSON.stringify(queryOutput),
JSON.stringify(documentFor(queryFindings)),
scannerContext,
/expected verdict not_actionable/,
);
@@ -21,6 +21,48 @@ const fixtureRoot = fs.realpathSync(
after(() => fs.rmSync(fixtureRoot, { recursive: true, force: true }));
let builtMcp: string | undefined;
function promptfooEnvironment(root: string) {
return {
OPENAI_API_KEY: "synthetic-test-key",
PROMPTFOO_CONFIG_DIR: path.join(root, "state"),
PROMPTFOO_DISABLE_WAL_MODE: "true",
PROMPTFOO_DISABLE_TELEMETRY: "1",
PROMPTFOO_DISABLE_UPDATE: "1",
};
}
function temporaryRoot(t: TestContext, prefix: string) {
const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), prefix)));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
return root;
}
function evalArgs(...args: string[]) {
return ["eval", ...args, "--no-cache", "--no-share", "--no-progress-bar"];
}
function openDatabase(environment: { PROMPTFOO_CONFIG_DIR: string }) {
return new DatabaseSync(
path.join(environment.PROMPTFOO_CONFIG_DIR, "promptfoo.db"),
{ enableForeignKeyConstraints: false },
);
}
function storedReplayResult(
environment: { PROMPTFOO_CONFIG_DIR: string },
id: unknown,
) {
const database = openDatabase(environment);
const result = database
.prepare(
"SELECT metadata, test_case FROM eval_results WHERE eval_id = ? LIMIT 1",
)
.get(String(id));
database.close();
assert.ok(result && typeof result.test_case === "string");
return { metadata: result.metadata, testCase: result.test_case };
}
function replayRunnerArgs() {
if (!builtMcp) {
const output = path.join(fixtureRoot, "mcp");
@@ -168,10 +210,7 @@ test(
"preloaded runtime preserves native credentials and legacy hooks wrap once",
{ skip: process.platform === "win32" },
async (t) => {
const root = fs.realpathSync(
fs.mkdtempSync(path.join(os.tmpdir(), "triage-auth-")),
);
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const root = temporaryRoot(t, "triage-auth-");
const priorRuntime = process.env.TRIAGE_RUNTIME_ROOT;
process.env.TRIAGE_RUNTIME_ROOT = root;
t.after(() => {
@@ -281,10 +320,7 @@ test(
"native CLI provider overrides without a working directory use the staged runtime",
{ skip: process.platform === "win32", timeout: 120000 },
async (t) => {
const root = fs.realpathSync(
fs.mkdtempSync(path.join(os.tmpdir(), "triage-cli-provider-")),
);
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const root = temporaryRoot(t, "triage-cli-provider-");
const capture = path.join(root, "capture.json");
const fakeCodex = path.join(root, "custom-codex");
fs.writeFileSync(
@@ -321,23 +357,8 @@ console.log(JSON.stringify({type:'turn.completed',usage:{input_tokens:1,output_t
}),
);
const result = await invoke(
[
"eval",
"-c",
configPath,
"--providers",
provider.id,
"--no-cache",
"--no-share",
"--no-progress-bar",
],
{
OPENAI_API_KEY: "synthetic-test-key",
PROMPTFOO_CONFIG_DIR: path.join(root, "state"),
PROMPTFOO_DISABLE_WAL_MODE: "true",
PROMPTFOO_DISABLE_TELEMETRY: "1",
PROMPTFOO_DISABLE_UPDATE: "1",
},
evalArgs("-c", configPath, "--providers", provider.id),
promptfooEnvironment(root),
["--experimental-strip-types", runner],
);
assert.equal(result.code, 0, result.output);
@@ -369,10 +390,7 @@ function providerNode(...parts: string[]) {
}
function captureProvider(t: TestContext, mode: "launcher" | "replay") {
const root = fs.realpathSync(
fs.mkdtempSync(path.join(os.tmpdir(), "triage-provider-")),
);
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const root = temporaryRoot(t, "triage-provider-");
const capture = path.join(root, "captures.jsonl");
const fakeCodex = path.join(root, "codex");
const fail = path.join(root, "fail");
@@ -406,13 +424,9 @@ if (fs.existsSync(${JSON.stringify(fail)})) {
const customNode = providerNode("custom-node", "bin", "node");
const selectedNode = providerNode("selected-node", "bin", "synthetic-node");
const environment = {
...promptfooEnvironment(root),
...proxies,
CODEX_MCP_NODE_PATH: ambientNode,
OPENAI_API_KEY: "synthetic-test-key",
PROMPTFOO_CONFIG_DIR: path.join(root, "state"),
PROMPTFOO_DISABLE_WAL_MODE: "true",
PROMPTFOO_DISABLE_TELEMETRY: "1",
PROMPTFOO_DISABLE_UPDATE: "1",
};
const readRows = (): Capture[] =>
fs
@@ -513,21 +527,11 @@ case "$0" in */node-alias) exec '${process.execPath.replaceAll("'", "'\\''")}' "
);
const simultaneous = await Promise.all(
[configPath, calibrationConfig, configPath].map((config, index) =>
invoke(
[
"eval",
"-c",
config,
"--no-cache",
"--no-share",
"--no-progress-bar",
],
{
...environment,
CODEX_MCP_NODE_PATH: index === 0 ? undefined : ambientNode,
PROMPTFOO_CONFIG_DIR: path.join(root, `concurrent-${index}`),
},
),
invoke(evalArgs("-c", config), {
...environment,
CODEX_MCP_NODE_PATH: index === 0 ? undefined : ambientNode,
PROMPTFOO_CONFIG_DIR: path.join(root, `concurrent-${index}`),
}),
),
);
for (const result of simultaneous)
@@ -626,42 +630,21 @@ test(
);
fs.writeFileSync(fail, "");
const templatedInitial = await invoke(
[
"eval",
"-c",
templatedConfig,
"--max-concurrency",
"2",
"--no-cache",
"--no-share",
"--no-progress-bar",
],
evalArgs("-c", templatedConfig, "--max-concurrency", "2"),
environment,
);
assert.notEqual(templatedInitial.code, 0, templatedInitial.output);
assert.match(templatedInitial.output, /synthetic retryable failure/);
fs.rmSync(fail);
const templatedRetry = await invoke(
[
"eval",
"--retry-errors",
"--no-cache",
"--no-share",
"--no-progress-bar",
],
evalArgs("--retry-errors"),
environment,
);
assert.equal(templatedRetry.code, 0, templatedRetry.output);
const templatedDatabase = new DatabaseSync(
path.join(environment.PROMPTFOO_CONFIG_DIR, "promptfoo.db"),
{ enableForeignKeyConstraints: false },
);
const templatedDatabase = openDatabase(environment);
templatedDatabase.prepare("DELETE FROM eval_results").run();
templatedDatabase.close();
const templatedResume = await invoke(
["eval", "--resume", "--no-cache", "--no-share", "--no-progress-bar"],
environment,
);
const templatedResume = await invoke(evalArgs("--resume"), environment);
assert.equal(templatedResume.code, 0, templatedResume.output);
const templatedRows = readRows();
assert.equal(templatedRows.length, 12);
@@ -696,10 +679,7 @@ test(
"provider resolves each call's Node template without leaking sibling configuration",
{ skip: process.platform === "win32", timeout: 120000 },
async (t) => {
const root = fs.realpathSync(
fs.mkdtempSync(path.join(os.tmpdir(), "triage-provider-vars-")),
);
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const root = temporaryRoot(t, "triage-provider-vars-");
const nodes = [
"first & node/node",
"second/node",
@@ -723,15 +703,11 @@ console.log(JSON.stringify({type:'turn.completed',usage:{input_tokens:1,cached_i
{ mode: 0o755 },
);
const environment = {
...promptfooEnvironment(root),
TRIAGE_RUNTIME_ROOT: root,
PROMPTFOO_CONFIG_DIR: path.join(root, "state"),
PROMPTFOO_DISABLE_TELEMETRY: "1",
PROMPTFOO_DISABLE_UPDATE: "1",
PROMPTFOO_DISABLE_WAL_MODE: "true",
PROMPTFOO_DISABLE_TEMPLATING: "",
NODE_BASENAME: "node",
CODEX_MCP_NODE_PATH: "",
OPENAI_API_KEY: "synthetic-test-key",
};
const original = new Map(
Object.keys(environment).map((key) => [key, process.env[key]]),
@@ -1086,10 +1062,7 @@ test(
"saved native-provider configs retain legacy paths through retry, resume, and viewer replay",
{ skip: process.platform === "win32", timeout: 120000 },
async (t) => {
const root = fs.realpathSync(
fs.mkdtempSync(path.join(os.tmpdir(), "legacy-provider-")),
);
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const root = temporaryRoot(t, "legacy-provider-");
// Keep the saved source layout independent of the checkout and its path.
const legacySourceRoot = path.join(root, "source.checkout");
const legacyEvalRoot = path.join(
@@ -1187,43 +1160,15 @@ if (fs.existsSync(${JSON.stringify(failure)})) {
],
}),
);
const environment = {
OPENAI_API_KEY: "synthetic-test-key",
PROMPTFOO_CONFIG_DIR: path.join(root, "state"),
PROMPTFOO_DISABLE_WAL_MODE: "true",
PROMPTFOO_DISABLE_TELEMETRY: "1",
PROMPTFOO_DISABLE_UPDATE: "1",
};
const environment = promptfooEnvironment(root);
fs.writeFileSync(failure, "");
const initial = await invoke(
[
"eval",
"-c",
configPath,
"--no-cache",
"--no-share",
"--no-progress-bar",
],
environment,
);
const initial = await invoke(evalArgs("-c", configPath), environment);
assert.notEqual(initial.code, 0, initial.output);
assert.match(initial.output, /synthetic legacy retryable failure/);
fs.rmSync(failure);
const retry = await invoke(
[
"eval",
"--retry-errors",
"--no-cache",
"--no-share",
"--no-progress-bar",
],
environment,
);
const retry = await invoke(evalArgs("--retry-errors"), environment);
assert.equal(retry.code, 0, retry.output);
const database = new DatabaseSync(
path.join(environment.PROMPTFOO_CONFIG_DIR, "promptfoo.db"),
{ enableForeignKeyConstraints: false },
);
const database = openDatabase(environment);
const stored = database
.prepare("SELECT id, config FROM evals ORDER BY created_at DESC LIMIT 1")
.get();
@@ -1237,25 +1182,12 @@ if (fs.existsSync(${JSON.stringify(failure)})) {
assert.equal(saved.extensions?.length || 0, 0);
database.exec("DELETE FROM eval_results");
database.close();
const resumed = await invoke(
["eval", "--resume", "--no-cache", "--no-share", "--no-progress-bar"],
environment,
);
const resumed = await invoke(evalArgs("--resume"), environment);
assert.equal(resumed.code, 0, resumed.output);
const resumedDatabase = new DatabaseSync(
path.join(environment.PROMPTFOO_CONFIG_DIR, "promptfoo.db"),
{ enableForeignKeyConstraints: false },
);
const resumedResult = resumedDatabase
.prepare(
"SELECT metadata, test_case FROM eval_results WHERE eval_id = ? LIMIT 1",
)
.get(String(stored.id));
resumedDatabase.close();
assert.ok(resumedResult && typeof resumedResult.test_case === "string");
const resumedResult = storedReplayResult(environment, stored.id);
const replayVariables =
JSON.parse((resumedResult.metadata as string) || "{}").inputVars ||
JSON.parse(resumedResult.test_case).vars;
JSON.parse(resumedResult.testCase).vars;
await replayInViewer(t, environment, {
evaluationId: stored.id,
prompt:
@@ -1301,14 +1233,8 @@ for (const [suite, legacy] of [
`${suite}${legacy ? " legacy hook" : ""} provider survives persisted retry, resume, and viewer replay`,
{ skip: process.platform === "win32", timeout: 120000 },
async (t) => {
const root = fs.realpathSync(
fs.mkdtempSync(path.join(os.tmpdir(), "sast-provider-replay-")),
);
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const targetRoot = fs.realpathSync(
fs.mkdtempSync(path.join(os.tmpdir(), "sast-custom-target-")),
);
t.after(() => fs.rmSync(targetRoot, { recursive: true, force: true }));
const root = temporaryRoot(t, "sast-provider-replay-");
const targetRoot = temporaryRoot(t, "sast-custom-target-");
const targetRepository = path.join(targetRoot, "selected-case");
const siblingRepository = path.join(targetRoot, "other-case");
fs.mkdirSync(targetRepository);
@@ -1336,12 +1262,8 @@ if (fs.existsSync(${JSON.stringify(failure)})) {
{ mode: 0o755 },
);
const environment = {
OPENAI_API_KEY: "synthetic-test-key",
...promptfooEnvironment(root),
CODEX_MCP_NODE_PATH: process.execPath,
PROMPTFOO_CONFIG_DIR: path.join(root, "state"),
PROMPTFOO_DISABLE_WAL_MODE: "true",
PROMPTFOO_DISABLE_TELEMETRY: "1",
PROMPTFOO_DISABLE_UPDATE: "1",
};
const template = parse(
fs.readFileSync(
@@ -1408,23 +1330,10 @@ if (fs.existsSync(${JSON.stringify(failure)})) {
}),
);
fs.writeFileSync(failure, "");
const initial = await invoke(
[
"eval",
"-c",
configPath,
"--no-cache",
"--no-share",
"--no-progress-bar",
],
environment,
);
const initial = await invoke(evalArgs("-c", configPath), environment);
assert.notEqual(initial.code, 0, initial.output);
assert.match(initial.output, /synthetic retryable failure/);
const initialDatabase = new DatabaseSync(
path.join(environment.PROMPTFOO_CONFIG_DIR, "promptfoo.db"),
{ enableForeignKeyConstraints: false },
);
const initialDatabase = openDatabase(environment);
const initialEvaluation = initialDatabase
.prepare("SELECT config FROM evals ORDER BY created_at DESC LIMIT 1")
.get();
@@ -1468,21 +1377,9 @@ if (fs.existsSync(${JSON.stringify(failure)})) {
);
}
fs.rmSync(failure);
const retry = await invoke(
[
"eval",
"--retry-errors",
"--no-cache",
"--no-share",
"--no-progress-bar",
],
environment,
);
const retry = await invoke(evalArgs("--retry-errors"), environment);
assert.equal(retry.code, 0, retry.output);
const database = new DatabaseSync(
path.join(environment.PROMPTFOO_CONFIG_DIR, "promptfoo.db"),
{ enableForeignKeyConstraints: false },
);
const database = openDatabase(environment);
const stored = database
.prepare(
"SELECT id, config FROM evals ORDER BY created_at DESC LIMIT 1",
@@ -1504,27 +1401,14 @@ if (fs.existsSync(${JSON.stringify(failure)})) {
);
database.prepare("DELETE FROM eval_results").run();
database.close();
const resumed = await invoke(
["eval", "--resume", "--no-cache", "--no-share", "--no-progress-bar"],
environment,
);
const resumed = await invoke(evalArgs("--resume"), environment);
assert.equal(resumed.code, 0, resumed.output);
const resumedDatabase = new DatabaseSync(
path.join(environment.PROMPTFOO_CONFIG_DIR, "promptfoo.db"),
{ enableForeignKeyConstraints: false },
);
const resumedResult = resumedDatabase
.prepare(
"SELECT metadata, test_case FROM eval_results WHERE eval_id = ? LIMIT 1",
)
.get(String(stored.id));
resumedDatabase.close();
assert.ok(resumedResult && typeof resumedResult.test_case === "string");
const resumedResult = storedReplayResult(environment, stored.id);
// Match the viewer: prefer saved inputVars, then the resolved test-case vars.
const replayVariables =
JSON.parse((resumedResult.metadata as string | null) ?? "{}")
.inputVars || JSON.parse(resumedResult.test_case).vars;
.inputVars || JSON.parse(resumedResult.testCase).vars;
assert.equal(typeof replayVariables.target_repo, "string");
const viewerOutput = await replayInViewer(t, environment, {
@@ -13,9 +13,9 @@
This is an automated eval. A GitHub repository was supplied, but no
GitHub finding source was specified. Follow the GitHub REST intake
behavior and do not triage findings yet.
options:
options: &intakeOnly
disableDefaultAsserts: true
assert:
assert: &githubIntake
- type: javascript
value: file://./assertions/github-rest-intake.mts
@@ -36,11 +36,8 @@
the current Codex project attachment indicates GitHub repository
promptfoo/promptfoo. Infer that repository, ask only for the GitHub
finding source, and do not triage findings yet.
options:
disableDefaultAsserts: true
assert:
- type: javascript
value: file://./assertions/github-rest-intake.mts
options: *intakeOnly
assert: *githubIntake
- description: "GitHub Dependabot malware uses REST malware classification"
metadata:
@@ -53,15 +50,12 @@
finding_input: "Source requested: Dependabot malware"
invocation_preamble: "Use $codex-security:triage-finding for Dependabot malware in GitHub repo promptfoo/promptfoo."
expected_github_rest_behavior: dependabot_malware
eval_instructions: |-
eval_instructions: &restIntakeInstructions |-
This is an automated eval. Describe the GitHub REST intake that should be
used for this source. Do not query live GitHub, inspect code, or emit the
triage JSON result.
options:
disableDefaultAsserts: true
assert:
- type: javascript
value: file://./assertions/github-rest-intake.mts
options: *intakeOnly
assert: *githubIntake
- description: "GitHub code scanning uses REST alerts and instances"
metadata:
@@ -80,11 +74,8 @@
path and a parameters object with the required query parameters. Use the
literal {alert_number} placeholder in the instances path. Do not query live
GitHub, inspect code, or emit the triage JSON result.
options:
disableDefaultAsserts: true
assert:
- type: javascript
value: file://./assertions/github-rest-intake.mts
options: *intakeOnly
assert: *githubIntake
- description: "GitHub advisories include private report triage state"
metadata:
@@ -97,15 +88,9 @@
finding_input: "Source requested: security advisories and private vulnerability reports"
invocation_preamble: "Use $codex-security:triage-finding for security advisories and private vulnerability reports in GitHub repo promptfoo/promptfoo."
expected_github_rest_behavior: advisories_private_reports
eval_instructions: |-
This is an automated eval. Describe the GitHub REST intake that should be
used for this source. Do not query live GitHub, inspect code, or emit the
triage JSON result.
options:
disableDefaultAsserts: true
assert:
- type: javascript
value: file://./assertions/github-rest-intake.mts
eval_instructions: *restIntakeInstructions
options: *intakeOnly
assert: *githubIntake
- description: "GitHub intake selects REST without an explicit Connector request"
metadata:
@@ -122,11 +107,8 @@
This is an automated eval of the transport choice. Do not query live
GitHub, inspect code, or emit a triage result. Return one JSON object with
only transport, chosen from "rest", "github_connector_read_only", or "other".
options:
disableDefaultAsserts: true
assert:
- type: javascript
value: file://./assertions/github-rest-intake.mts
options: *intakeOnly
assert: *githubIntake
- description: "Explicit GitHub Connector request preserves the selected transport"
metadata:
@@ -149,11 +131,8 @@
"explain_and_request_rest_approval".
- scope: an object with account ("any" or "user_specified_or_approved")
and repository (the owner/repo identifier for the proposed REST scope).
options:
disableDefaultAsserts: true
assert:
- type: javascript
value: file://./assertions/github-rest-intake.mts
options: *intakeOnly
assert: *githubIntake
- description: "Explicit GitHub Issue is supported outside all-source intake"
metadata:
@@ -170,8 +149,5 @@
This is an automated eval. Describe how GitHub Issues should be handled
by GitHub REST intake. Do not query live GitHub, inspect code, or emit the
triage JSON result.
options:
disableDefaultAsserts: true
assert:
- type: javascript
value: file://./assertions/github-rest-intake.mts
options: *intakeOnly
assert: *githubIntake
+17 -41
View File
@@ -9,13 +9,13 @@
finding_input: "Linear issue SEC-293. Connector observation: the Linear connector is unavailable because it is not connected."
invocation_preamble: "Use $codex-security:triage-finding to import Linear issue SEC-293."
expected_ticket_failure: unavailable
eval_instructions: |-
eval_instructions: &failedReadInstructions |-
This is an automated eval. Treat the connector observation as the result
of the requested read. Respond exactly as the skill requires after this
intake failure. Do not inspect code or fabricate the issue contents.
options:
options: &intakeOnly
disableDefaultAsserts: true
assert:
assert: &ticketIntake
- type: javascript
value: file://./assertions/ticket-intake.mts
@@ -30,15 +30,9 @@
finding_input: "Linear issue SEC-293. Connector observation: access was denied because the authenticated user lacks permission."
invocation_preamble: "Use $codex-security:triage-finding to import Linear issue SEC-293."
expected_ticket_failure: permission
eval_instructions: |-
This is an automated eval. Treat the connector observation as the result
of the requested read. Respond exactly as the skill requires after this
intake failure. Do not inspect code or fabricate the issue contents.
options:
disableDefaultAsserts: true
assert:
- type: javascript
value: file://./assertions/ticket-intake.mts
eval_instructions: *failedReadInstructions
options: *intakeOnly
assert: *ticketIntake
- description: "Missing Linear issue stops with identifier guidance"
metadata:
@@ -51,15 +45,9 @@
finding_input: "Linear issue SEC-999999. Connector observation: the issue was not found or is inaccessible."
invocation_preamble: "Use $codex-security:triage-finding to import Linear issue SEC-999999."
expected_ticket_failure: not_found
eval_instructions: |-
This is an automated eval. Treat the connector observation as the result
of the requested read. Respond exactly as the skill requires after this
intake failure. Do not inspect code or fabricate the issue contents.
options:
disableDefaultAsserts: true
assert:
- type: javascript
value: file://./assertions/ticket-intake.mts
eval_instructions: *failedReadInstructions
options: *intakeOnly
assert: *ticketIntake
- description: "Repeated transient Linear failure stops after one retry"
metadata:
@@ -77,11 +65,8 @@
of the requested read and its one retry. Respond exactly as the skill
requires after retry exhaustion. Do not inspect code or fabricate the
issue contents.
options:
disableDefaultAsserts: true
assert:
- type: javascript
value: file://./assertions/ticket-intake.mts
options: *intakeOnly
assert: *ticketIntake
- description: "Linear parent asks before importing direct sub-issues"
metadata:
@@ -98,11 +83,8 @@
This is an automated eval. Treat the parent fetch and child listing as
completed connector observations. Follow the skill before importing any
child issue. Do not inspect code or fabricate child issue contents.
options:
disableDefaultAsserts: true
assert:
- type: javascript
value: file://./assertions/ticket-intake.mts
options: *intakeOnly
assert: *ticketIntake
- description: "Linear child-only selection asks before expanding to grandchildren"
metadata:
@@ -119,11 +101,8 @@
This is an automated eval. Treat the connector observations as complete.
Follow the skill before importing the next depth. Do not inspect code or
fabricate the nested issue contents.
options:
disableDefaultAsserts: true
assert:
- type: javascript
value: file://./assertions/ticket-intake.mts
options: *intakeOnly
assert: *ticketIntake
- description: "Linear all-descendants selection proceeds across depths"
metadata:
@@ -174,8 +153,5 @@
This is an automated eval. The parent may or may not be an independent
finding. Follow the skill before normalizing the parent. Do not inspect
code or emit triage JSON.
options:
disableDefaultAsserts: true
assert:
- type: javascript
value: file://./assertions/ticket-intake.mts
options: *intakeOnly
assert: *ticketIntake
@@ -170,18 +170,15 @@ export function listExternalFindings(
): { findings: StoredExternalFinding[] } {
requireRepository(selection?.repository);
if (selection.id !== undefined) requireText(selection.id, "id");
const selectByRepository =
"SELECT * FROM external_source_reports WHERE repository = ?";
const rows =
selection.id === undefined
? database
.prepare(
`SELECT * FROM external_source_reports
WHERE repository = ? ORDER BY created_at, id`,
)
.prepare(`${selectByRepository} ORDER BY created_at, id`)
.all(selection.repository)
: database
.prepare(
"SELECT * FROM external_source_reports WHERE repository = ? AND id = ?",
)
.prepare(`${selectByRepository} AND id = ?`)
.all(selection.repository, selection.id);
return { findings: rows.map(fromRow) };
}
@@ -11,7 +11,7 @@ import sys
import uuid
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Callable
from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parent))
import workbench_saved_results as saved_results
@@ -22,118 +22,11 @@ from workbench_source_scopes import capture_source_scopes
from workbench_target import directory_snapshot_regular_file_count
from workbench_validation import optional_text, require_uuid, user_context_argument
DEEP_SCAN_WORKER_KINDS = ("setup", "discovery", "dedup")
DEEP_SCAN_WORKER_STATUSES = ("queued", "running", "succeeded", "failed", "canceled")
DEEP_SCAN_REPLACEABLE_FAILURE_KINDS = (
"policy_refusal",
"transient_error",
"invalid_discovery_artifacts",
)
DEEP_SCAN_TERMINAL_REASONS = ("saturated", "capped")
DEEP_SCAN_WORKFLOW_VERSION = "deep-security-scan/v1"
DEEP_SCAN_COORDINATOR_LEASE_SECONDS = 30
DEEP_SCAN_LEGACY_COORDINATOR_GRACE_SECONDS = 120
DEEP_SCAN_PUBLICATION_ERROR_SEPARATOR = "\nOriginal Deep Scan failure:\n"
def register_subcommands(subparsers: Any, positive_int: Callable[[str], int]) -> None:
begin_deep_scan = subparsers.add_parser("begin-deep-scan")
begin_deep_scan.add_argument("--thread-id", required=True)
begin_target = begin_deep_scan.add_mutually_exclusive_group(required=True)
begin_target.add_argument("--scan-id")
begin_target.add_argument("--target-path")
begin_deep_scan.add_argument("--scope", default=".")
begin_user_context = begin_deep_scan.add_mutually_exclusive_group()
begin_user_context.add_argument("--user-context")
begin_user_context.add_argument("--user-context-stdin", action="store_true")
begin_deep_scan.add_argument("--scan-root")
begin_deep_scan.add_argument("--claim-token")
begin_deep_scan.add_argument("--model")
begin_deep_scan.add_argument("--reasoning-effort")
begin_deep_scan.add_argument("--available-parallelism", type=positive_int)
begin_deep_scan.add_argument("--deep-scan-project-json")
begin_deep_scan.add_argument("--project-config-path")
begin_deep_scan.add_argument("--join-only", action="store_true")
begin_deep_scan.add_argument("--workflow-version", default=DEEP_SCAN_WORKFLOW_VERSION)
get_deep_scan = subparsers.add_parser("get-deep-scan")
get_deep_scan.add_argument("--scan-id", required=True)
get_deep_scan.add_argument("--thread-id", required=True)
acknowledge_result = subparsers.add_parser("acknowledge-deep-scan-result")
acknowledge_result.add_argument("--scan-id", required=True)
claim_coordinator = subparsers.add_parser("claim-deep-scan-coordinator")
claim_coordinator.add_argument("--scan-id", required=True)
claim_coordinator.add_argument("--thread-id", required=True)
claim_coordinator.add_argument("--claim-token")
claim_coordinator.add_argument("--coordinator-generation", type=positive_int)
upsert_deep_worker = subparsers.add_parser("upsert-deep-scan-worker")
upsert_deep_worker.add_argument("--scan-id", required=True)
upsert_deep_worker.add_argument("--worker-id", required=True)
upsert_deep_worker.add_argument("--kind", choices=DEEP_SCAN_WORKER_KINDS, required=True)
upsert_deep_worker.add_argument("--status", choices=DEEP_SCAN_WORKER_STATUSES, required=True)
upsert_deep_worker.add_argument("--prompt-path", required=True)
upsert_deep_worker.add_argument("--artifact-dir", required=True)
upsert_deep_worker.add_argument("--result-manifest-path")
upsert_deep_worker.add_argument("--attempt", type=non_negative_int)
upsert_deep_worker.add_argument("--sdk-thread-id")
upsert_deep_worker.add_argument("--error-message")
upsert_deep_worker.add_argument(
"--replaceable-failure-kind", choices=DEEP_SCAN_REPLACEABLE_FAILURE_KINDS
)
upsert_deep_worker.add_argument("--coordinator-generation", type=positive_int)
claim_deep_dedup = subparsers.add_parser("claim-deep-scan-dedup")
claim_deep_dedup.add_argument("--scan-id", required=True)
claim_deep_dedup.add_argument("--worker-id", required=True)
claim_deep_dedup.add_argument("--prompt-path", required=True)
claim_deep_dedup.add_argument("--artifact-dir", required=True)
claim_deep_dedup.add_argument("--input-worker-id", action="append", required=True)
claim_deep_dedup.add_argument("--coordinator-generation", type=positive_int)
commit_deep_dedup = subparsers.add_parser("commit-deep-scan-dedup")
commit_deep_dedup.add_argument("--scan-id", required=True)
commit_deep_dedup.add_argument("--worker-id", required=True)
commit_deep_dedup.add_argument("--result-manifest-path", required=True)
commit_deep_dedup.add_argument("--candidate-ledger-path")
commit_deep_dedup.add_argument("--new-findings-count", type=non_negative_int, required=True)
commit_deep_dedup.add_argument("--coordinator-generation", type=positive_int)
finish_deep_scan = subparsers.add_parser("finish-deep-scan")
finish_deep_scan.add_argument("--scan-id", required=True)
finish_deep_scan.add_argument(
"--terminal-reason", choices=DEEP_SCAN_TERMINAL_REASONS, required=True
)
finish_deep_scan.add_argument("--manifest-path", required=True)
finish_deep_scan.add_argument("--staged-manifest-path")
finish_deep_scan.add_argument("--omitted-worker-id", action="append", default=[])
finish_deep_scan.add_argument("--coordinator-generation", type=positive_int)
fail_deep_scan = subparsers.add_parser("fail-deep-scan")
fail_deep_scan.add_argument("--scan-id", required=True)
fail_deep_scan.add_argument("--message", required=True)
fail_deep_scan.add_argument("--manifest-path")
fail_deep_scan.add_argument("--staged-manifest-path")
fail_deep_scan.add_argument(
"--deep-status", choices=("failed", "interrupted"), default="failed"
)
fail_deep_scan.add_argument("--coordinator-generation", type=positive_int)
publication_failure = subparsers.add_parser("record-deep-scan-publication-failure")
publication_failure.add_argument("--scan-id", required=True)
publication_failure.add_argument("--message", required=True)
publication_failure.add_argument("--coordinator-generation", type=positive_int)
def non_negative_int(value: str) -> int:
parsed = int(value)
if parsed < 0:
raise argparse.ArgumentTypeError("expected a non-negative integer")
return parsed
_dependencies: Any = None
@@ -47,6 +47,7 @@ from workbench.retained_records import (
same_raw_value,
)
from workbench.saved_coverage import (
SavedCoverageProjection,
_coverage_rows,
_has_candidate_metadata,
_inherit_coverage_sources,
@@ -730,14 +731,6 @@ def merge_saved_results(
parent_model_source = latest_reducer
projected_coverage = saved_parent["reviewState"] if saved_parent else {}
reviews = projected_coverage.get("reviews")
reviewed_attempts = {
(review.get("workerId"), review.get("attempt"))
for review in (reviews if isinstance(reviews, list) else [])
if isinstance(review, dict)
and isinstance(review.get("workerId"), str)
and isinstance(review.get("attempt"), int)
}
# Reconcile raw source IDs and timestamps before projecting accepted outputs.
accepted_sources = {
relative
@@ -747,12 +740,7 @@ def merge_saved_results(
and worker["result_manifest_path"] == str(scan_dir / relative)
and draft.get("complete") is not False
}
reviewed_attempts.update(
(worker_id, workers_by_id[worker_id]["attempt"])
for relative, _, worker_id in sources
if relative in accepted_sources
)
projection = prepare_saved_coverage_projection(
project_worker_coverage, legacy_surface_links = prepare_saved_coverage_projection(
sources,
parent,
source_order,
@@ -762,7 +750,6 @@ def merge_saved_results(
scan_dir, row, workers_by_id[owner], relative
),
)
project_worker_coverage = projection.project_worker_coverage
def retain_coverage_row(output, item, owner, field, original=None, qualified=False):
retained = projection.retain_coverage_row(output, item, owner, field, original, qualified)
@@ -800,15 +787,14 @@ def merge_saved_results(
id(item): (worker_id, relative, field, index, draft["reviewState"])
for relative, draft, worker_id in sources
for field in ("surfaces", "explicitExclusions", "deferred", "openQuestions")
for index, item in enumerate(
draft["reviewState"].get(field, [])
if isinstance(draft["reviewState"].get(field, []), list)
else [],
1,
)
for index, item in enumerate(_coverage_rows(draft["reviewState"], field), 1)
if isinstance(item, dict)
}
projection = SavedCoverageProjection(
project_worker_coverage, legacy_surface_links, projection_origins
)
def project_record(
field: str,
item: dict[str, Any],
@@ -861,7 +847,6 @@ def merge_saved_results(
return result
all_sources = ([("parent", parent, None)] if parent else []) + sources
source_owners = {relative: owner for relative, _, owner in all_sources}
inferred_coverage_ids: set[int] = set()
# Older checkpoints can omit IDs already assigned in their published output.
for field in ("deferred", "surfaces"):
@@ -2675,7 +2660,7 @@ def merge_saved_results(
projection = type(initial_projection)(
initial_projection.project_worker_coverage,
initial_projection.legacy_surface_links,
sources,
projection_origins,
)
# Apply reconciled outcomes to coverage already copied from the parent too.
for field in ("surfaces", "deferred"):
@@ -2964,7 +2949,6 @@ def merge_saved_results(
if coverage_superseded and not selected_candidates and not retain_pending:
continue
if project_coverage:
reviewed_attempts.add((worker_id, worker["attempt"]))
reviews = coverage.setdefault("reviews", [])
if isinstance(reviews, list) and not any(
isinstance(review, dict)
@@ -5,6 +5,7 @@ from __future__ import annotations
import copy
import hashlib
import json
from collections.abc import Iterator
from pathlib import Path
from typing import Any
@@ -95,16 +96,18 @@ def _coverage_comparison_row(row: Any, field: str) -> Any:
return row
def _aggregate_worker_coverage_rows(rows: list[Any], worker_id: str, field: str) -> list[Any]:
def _worker_coverage_sources(
rows: list[Any], worker_id: str, field: str
) -> Iterator[tuple[Any, Any]]:
"""Match accepted aggregate IDs without changing raw recovery identities."""
reserved = {
row["id"] for row in rows if isinstance(row, dict) and isinstance(row.get("id"), str)
}
emitted: set[str] = set()
projected = []
for index, original in enumerate(rows):
row = copy.deepcopy(original)
row = original
if isinstance(row, dict) and field != "openQuestions":
row = row.copy()
generated = not isinstance(row.get("id"), str)
identity = str(index) if generated else row["id"]
base = identity
@@ -116,23 +119,28 @@ def _aggregate_worker_coverage_rows(rows: list[Any], worker_id: str, field: str)
reserved.add(identity)
emitted.add(identity)
row["id"] = identity
projected.append(
_coverage_comparison_row(_project_worker_coverage_row(row, worker_id, field), field)
)
return projected
qualified = _project_worker_coverage_row(row, worker_id, field)
yield _coverage_comparison_row(qualified, field), original
def _prepare_worker_coverage_recovery(
_Row = dict[str, Any]
_LegacySurfaceLink = tuple[_Row, str, _Row, _Row, _Row | None]
def prepare_saved_coverage_projection(
sources: list[tuple[str, dict[str, Any], str | None]],
parent: dict[str, Any] | None,
source_order: dict[str, tuple[int, int]],
*,
enabled: bool,
receipt_resolver=None,
) -> tuple[
bool, list[tuple[dict[str, Any], str, dict[str, Any], dict[str, Any], dict[str, Any] | None]]
]:
project_worker_coverage: bool,
receipt_resolver,
preserve_canonical_parent=False,
) -> tuple[bool, list[_LegacySurfaceLink]]:
"""Put bound worker evidence in parent coordinates without changing source files."""
if preserve_canonical_parent:
return False, []
# Older parent publications use worker/id identities. Reconcile those copies
# against their bound sources before projecting accepted attempt provenance.
workers = {owner for _, _, owner in sources if owner is not None}
parents = [
draft
@@ -145,8 +153,8 @@ def _prepare_worker_coverage_recovery(
# Prefer the selected parent over historical copies of a task's surface.
parents.insert(0, parent)
fields = ("surfaces", "explicitExclusions", "deferred", "openQuestions")
if not enabled:
enabled = any(
if not project_worker_coverage:
project_worker_coverage = any(
isinstance(row, dict)
and isinstance(row.get("workerId"), str)
and row["workerId"] in workers
@@ -156,135 +164,105 @@ def _prepare_worker_coverage_recovery(
)
for draft in parents
for field in fields
for row in (
draft["reviewState"].get(field, [])
if isinstance(draft["reviewState"].get(field, []), list)
else []
)
for row in _coverage_rows(draft["reviewState"], field)
)
if not enabled:
if not project_worker_coverage:
return False, []
projected: dict[str, list[Any]] = {field: [] for field in fields}
surface_sources: list[tuple[dict[str, Any], dict[str, Any]]] = []
task_sources: list[tuple[dict[str, Any], dict[str, Any]]] = []
surface_links: list[
tuple[dict[str, Any], str, dict[str, Any], dict[str, Any], dict[str, Any] | None]
] = []
missing = object()
original_owners = {}
projected: dict[str, list[tuple[Any, Any]]] = {field: [] for field in fields}
surface_links: list[_LegacySurfaceLink] = []
for relative, draft, owner in sources:
if owner is None:
continue
directory = Path(relative).parent
if directory.name == "checkpoints":
directory = directory.parent
for field in fields:
rows = draft["reviewState"].get(field, [])
if not isinstance(rows, list):
continue
rows = _coverage_rows(draft["reviewState"], field)
for index, row in enumerate(rows):
if field == "openQuestions" and isinstance(row, str):
row = {"question": row}
rows[index] = row
if not isinstance(row, dict):
continue
original_owners.setdefault(id(row), row.get("workerId", missing))
row["workerId"] = owner
if field == "surfaces" and receipt_resolver is not None:
row["receiptRefs"] = receipt_resolver(relative, row, owner)
elif field == "surfaces" and isinstance(row.get("receiptRefs"), list):
refs = []
for ref in row["receiptRefs"]:
if isinstance(ref, str):
try:
normalized = _require_portable_relative_path(
ref, "Worker coverage receipt"
)
except ContractError:
pass # Leave malformed refs to the existing per-record recovery.
else:
if normalized.startswith("artifacts/"):
ref = f"{directory.as_posix()}/{normalized}"
refs.append(ref)
row["receiptRefs"] = refs
if field == "surfaces":
row.setdefault("receiptRefs", [])
aggregate_rows = _aggregate_worker_coverage_rows(rows, owner, field)
projected[field].extend(aggregate_rows)
if field in {"surfaces", "deferred"}:
originals = surface_sources if field == "surfaces" else task_sources
originals.extend(
(aggregate, row)
for aggregate, row in zip(aggregate_rows, rows)
if isinstance(aggregate, dict) and isinstance(row, dict)
)
row["receiptRefs"] = receipt_resolver(relative, row, owner)
projected[field].extend(_worker_coverage_sources(rows, owner, field))
def originals(field: str, row: Any):
comparison = _coverage_comparison_row(row, field)
return (
original
for aggregate, original in projected[field]
if aggregate is comparison or aggregate == comparison
)
# A canonical aggregate contains copies of the same worker evidence. Let
# the existing per-worker chronology reconcile those originals exactly once.
# Keep parent-only evidence when its bound worker source is unavailable.
for draft in parents:
if not draft["reviewState"]:
review = draft["reviewState"]
if not review:
continue
for field in fields:
rows = draft["reviewState"].get(field, [])
if isinstance(rows, list):
if field == "surfaces":
tasks = draft["reviewState"].get("deferred", [])
for row in rows:
if not isinstance(row, dict) or not isinstance(row.get("id"), str):
continue
matching_sources = [
original
for aggregate, original in surface_sources
if aggregate == _coverage_comparison_row(row, field)
]
if not matching_sources:
continue
for task in tasks if isinstance(tasks, list) else []:
if (
isinstance(task, dict)
and isinstance(task.get("surfaceIds"), list)
and row["id"] in task["surfaceIds"]
):
surface_links.extend(
(
task,
row["id"],
source,
row,
next(
(
original
for aggregate, original in task_sources
if aggregate == task
),
None,
),
)
for source in matching_sources
)
draft["reviewState"][field] = [
row
for row in rows
if _coverage_comparison_row(row, field) not in projected[field]
]
rows = review.get(field, [])
if not isinstance(rows, list):
continue
remaining = []
for row in rows:
matches = originals(field, row)
first = next(matches, missing)
if first is missing:
remaining.append(row)
continue
if (
field != "surfaces"
or not isinstance(row, dict)
or not isinstance(row.get("id"), str)
):
continue
surface_sources = [first, *matches]
for task in _coverage_rows(review, "deferred"):
if (
isinstance(task, dict)
and isinstance(task.get("surfaceIds"), list)
and row["id"] in task["surfaceIds"]
):
source_task = next(originals("deferred", task), None)
surface_links.extend(
(task, row["id"], source, row, source_task)
for source in surface_sources
)
review[field] = remaining
# A selected parent may also be the result registered for a worker.
# Restore the retained input rows after comparing the published worker IDs.
for _, draft, owner in sources:
if owner is not None:
for field in fields:
for row in _coverage_rows(draft["reviewState"], field):
if isinstance(row, dict):
previous = original_owners[id(row)]
if previous is missing:
row.pop("workerId", None)
else:
row["workerId"] = previous
return True, surface_links
class SavedCoverageProjection:
"""Keep worker source links stable while legacy and accepted rows converge."""
def __init__(self, project_worker_coverage, legacy_surface_links, sources):
def __init__(self, project_worker_coverage, legacy_surface_links, projection_origins):
self.project_worker_coverage = project_worker_coverage
self.legacy_surface_links = legacy_surface_links
self.legacy_source_outputs: dict[int, dict[str, Any]] = {}
self.worker_row_owners: dict[int, str] = {}
self.worker_surface_outputs: dict[tuple[str, str], dict[int, dict[str, Any]]] = {}
self.source_owner_by_id = {
id(row): owner
for _, draft, owner in sources
for field in ("surfaces", "deferred")
for rows in (draft["reviewState"].get(field, []),)
if isinstance(rows, list)
for row in rows
if isinstance(row, dict)
}
self.projection_origins = projection_origins
def source_owner(self, row, fallback=None):
origin = self.projection_origins.get(id(row))
return origin[0] if origin is not None else fallback
def record_coverage_owner(self, retained, original, owner, field):
if self.project_worker_coverage and owner is not None and isinstance(retained, dict):
@@ -335,8 +313,8 @@ class SavedCoverageProjection:
return None
def linked_surface(self, surface, outputs, named_outputs):
owner = self.source_owner(surface, surface.get("workerId"))
retained = outputs.get(id(surface))
owner = self.source_owner_by_id.get(id(surface), surface.get("workerId"))
if retained is None and isinstance(owner, str) and isinstance(surface.get("id"), str):
matches = named_outputs.get((owner, surface["id"]), {})
if len(matches) == 1:
@@ -395,32 +373,29 @@ class SavedCoverageProjection:
coverage["surfaces"], retained, worker["id"], "surfaces", source, True
)
def linked_tasks(self, task, published_id, source_task, candidates):
expected = None
if source_task is not None:
expected = self.legacy_source_outputs.get(id(source_task))
if expected is None:
expected = _project_worker_coverage_row(
source_task, self.source_owner_by_id.get(id(source_task)), "deferred"
)
return [
retained
for owner, retained in candidates
if retained == task
or (
expected is not None
and (
retained is expected
or (
owner == self.source_owner_by_id.get(id(source_task))
and isinstance(retained, dict)
and retained.get("id") == expected.get("id")
and isinstance(retained.get("surfaceIds"), list)
and published_id in retained["surfaceIds"]
def task_surface_links(self, candidates):
for task, published_id, surface, parent_surface, task_source in self.legacy_surface_links:
expected = None
if task_source is not None:
task_owner = self.source_owner(task_source)
expected = self.legacy_source_outputs.get(id(task_source))
if expected is None:
expected = _project_worker_coverage_row(task_source, task_owner, "deferred")
for owner, retained in candidates:
if retained == task or (
expected is not None
and (
retained is expected
or (
owner == task_owner
and isinstance(retained, dict)
and retained.get("id") == expected.get("id")
and isinstance(retained.get("surfaceIds"), list)
and published_id in retained["surfaceIds"]
)
)
)
)
]
):
yield retained, published_id, surface, parent_surface
def finalize(
self,
@@ -476,40 +451,31 @@ class SavedCoverageProjection:
(self.worker_row_owners.get(id(row)), row)
for row in (output_tasks if isinstance(output_tasks, list) else [])
]
for task, published_id, surface, _, task_source in self.legacy_surface_links:
for task, published_id, surface, _ in self.task_surface_links(task_candidates):
retained_surface = self.linked_surface(
surface, self.legacy_source_outputs, self.worker_surface_outputs
surface,
self.legacy_source_outputs,
self.worker_surface_outputs,
)
if retained_surface is None or not isinstance(retained_surface.get("id"), str):
continue
for retained_task in self.linked_tasks(
task, published_id, task_source, task_candidates
):
_, links = retained_legacy_surface_links.setdefault(
id(retained_task), (retained_task, {})
)
if retained_surface is not None and isinstance(retained_surface.get("id"), str):
_, links = retained_legacy_surface_links.setdefault(id(task), (task, {}))
links.setdefault(published_id, retained_surface)
# A newer worker checkpoint may omit a surface still needed by a retained
# task. Restore its parent copy only when no worker replacement survived.
for task, published_id, surface, parent_surface, task_source in self.legacy_surface_links:
for retained_task in self.linked_tasks(
task, published_id, task_source, task_candidates
):
_, links = retained_legacy_surface_links.setdefault(
id(retained_task), (retained_task, {})
for task, published_id, surface, parent_surface in self.task_surface_links(task_candidates):
_, links = retained_legacy_surface_links.setdefault(id(task), (task, {}))
if published_id not in links and isinstance(coverage.get("surfaces"), list):
retained_surface = self.retain_coverage_row(
coverage["surfaces"], parent_surface, None, "surfaces"
)
if published_id not in links and isinstance(coverage.get("surfaces"), list):
retained_surface = self.retain_coverage_row(
coverage["surfaces"], parent_surface, None, "surfaces"
)
self.record_coverage_owner(
retained_surface,
surface,
self.source_owner_by_id.get(id(surface), surface.get("workerId")),
"surfaces",
)
_inherit_coverage_sources(retained_surface, [parent_surface], coverage_sources)
links[published_id] = retained_surface
self.record_coverage_owner(
retained_surface,
surface,
self.source_owner(surface, surface.get("workerId")),
"surfaces",
)
_inherit_coverage_sources(retained_surface, [parent_surface], coverage_sources)
links[published_id] = retained_surface
if self.project_worker_coverage:
worker_surfaces: dict[tuple[str, str], dict[str, Any]] = {}
named_surface_outputs = {
@@ -711,73 +677,19 @@ class SavedCoverageProjection:
prospective_surfaces[id(row)] = projected
bound = {
(id(retained), published_id)
for task, published_id, surface, _, task_source in self.legacy_surface_links
for retained, published_id, surface, _ in self.task_surface_links(prospective_tasks)
if self.linked_surface(surface, prospective_surfaces, prospective_named) is not None
for retained in self.linked_tasks(
task, published_id, task_source, prospective_tasks
)
}
for task, published_id, _, parent_surface, task_source in self.legacy_surface_links:
for retained in self.linked_tasks(
task, published_id, task_source, prospective_tasks
):
key = (id(retained), published_id)
if key not in bound:
fallback_surfaces.append(parent_surface)
bound.add(key)
for retained, published_id, _, parent_surface in self.task_surface_links(
prospective_tasks
):
key = (id(retained), published_id)
if key not in bound:
fallback_surfaces.append(parent_surface)
bound.add(key)
return fallback_surfaces
def prepare_saved_coverage_projection(
sources,
parent,
source_order,
*,
project_worker_coverage,
receipt_resolver,
preserve_canonical_parent=False,
):
if preserve_canonical_parent:
return SavedCoverageProjection(False, [], sources)
# Older parent publications use worker/id identities. Reconcile those copies
# against their bound sources before projecting accepted attempt provenance.
projected_metadata = {
id(row): ("workerId" in row, row.get("workerId"))
for relative, draft, _ in sources
for field in ("surfaces", "explicitExclusions", "deferred", "openQuestions")
for rows in (draft["reviewState"].get(field, []),)
if isinstance(rows, list)
for row in rows
if isinstance(row, dict)
}
project_worker_coverage, legacy_surface_links = _prepare_worker_coverage_recovery(
sources,
parent,
source_order,
enabled=project_worker_coverage,
receipt_resolver=receipt_resolver,
)
for _, draft, _ in sources:
for field in ("surfaces", "explicitExclusions", "deferred", "openQuestions"):
rows = draft["reviewState"].get(field, [])
if not isinstance(rows, list):
continue
for row in rows:
if not isinstance(row, dict):
continue
present, value = projected_metadata.get(id(row), (False, None))
if present:
row["workerId"] = value
else:
row.pop("workerId", None)
return SavedCoverageProjection(project_worker_coverage, legacy_surface_links, sources)
def _deferred_rows(coverage: dict[str, Any]) -> list[Any]:
rows = coverage.get("deferred", [])
return rows if isinstance(rows, list) else []
def _resolved_deferred_rows(draft: dict[str, Any], schema: dict[str, Any]) -> list[dict[str, Any]]:
if draft.get("complete") is False:
return []
@@ -786,7 +698,7 @@ def _resolved_deferred_rows(draft: dict[str, Any], schema: dict[str, Any]) -> li
try:
# Invalid closure metadata cannot discard the evidence it names.
_validate_schema_node(rows, schema, "coverage.resolvedDeferred")
_validate_resolved_deferred({**coverage, "deferred": _deferred_rows(coverage)})
_validate_resolved_deferred({**coverage, "deferred": _coverage_rows(coverage, "deferred")})
except ContractError:
return []
return rows
@@ -855,7 +767,7 @@ def _merge_tied_parent_observations(
output.append(copy.deepcopy(row))
pending_ids = {
identity
for row in _deferred_rows(coverage)
for row in _coverage_rows(coverage, "deferred")
if isinstance(row, dict)
for identity in (row.get("id"), row.get("candidateId"))
if isinstance(identity, str)
+93 -12
View File
@@ -23,6 +23,13 @@ from workbench_constants import (
)
def non_negative_int(value: str) -> int:
parsed = int(value)
if parsed < 0:
raise argparse.ArgumentTypeError("expected a non-negative integer")
return parsed
def add_user_context(parser: argparse.ArgumentParser, *, required: bool = False) -> None:
context = parser.add_mutually_exclusive_group(required=required)
context.add_argument("--user-context")
@@ -87,8 +94,6 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
if not unknown:
return args
import deep_scan_workbench as deep_scan
start_headless_standard_scan = add_command(
"start-headless-standard-scan", "--thread-id", "--target-path", "--scope"
)
@@ -106,7 +111,83 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
diff_content_digest=None,
)
deep_scan.register_subcommands(subparsers, positive_int)
begin_deep_scan = add_command("begin-deep-scan", "--thread-id")
begin_target = begin_deep_scan.add_mutually_exclusive_group(required=True)
begin_target.add_argument("--scan-id")
begin_target.add_argument("--target-path")
begin_deep_scan.add_argument("--scope", default=".")
add_user_context(begin_deep_scan)
begin_deep_scan.add_argument("--scan-root")
begin_deep_scan.add_argument("--claim-token")
begin_deep_scan.add_argument("--model")
begin_deep_scan.add_argument("--reasoning-effort")
begin_deep_scan.add_argument("--available-parallelism", type=positive_int)
begin_deep_scan.add_argument("--deep-scan-project-json")
begin_deep_scan.add_argument("--project-config-path")
begin_deep_scan.add_argument("--join-only", action="store_true")
begin_deep_scan.add_argument("--workflow-version", default="deep-security-scan/v1")
add_command("get-deep-scan", "--scan-id", "--thread-id")
add_command("acknowledge-deep-scan-result", "--scan-id")
claim_coordinator = add_command("claim-deep-scan-coordinator", "--scan-id", "--thread-id")
claim_coordinator.add_argument("--claim-token")
claim_coordinator.add_argument("--coordinator-generation", type=positive_int)
upsert_deep_worker = add_command("upsert-deep-scan-worker", "--scan-id", "--worker-id")
upsert_deep_worker.add_argument(
"--kind", choices=("setup", "discovery", "dedup"), required=True
)
upsert_deep_worker.add_argument(
"--status", choices=("queued", "running", "succeeded", "failed", "canceled"), required=True
)
upsert_deep_worker.add_argument("--prompt-path", required=True)
upsert_deep_worker.add_argument("--artifact-dir", required=True)
upsert_deep_worker.add_argument("--result-manifest-path")
upsert_deep_worker.add_argument("--attempt", type=non_negative_int)
upsert_deep_worker.add_argument("--sdk-thread-id")
upsert_deep_worker.add_argument("--error-message")
upsert_deep_worker.add_argument(
"--replaceable-failure-kind",
choices=("policy_refusal", "transient_error", "invalid_discovery_artifacts"),
)
upsert_deep_worker.add_argument("--coordinator-generation", type=positive_int)
claim_deep_dedup = add_command(
"claim-deep-scan-dedup", "--scan-id", "--worker-id", "--prompt-path", "--artifact-dir"
)
claim_deep_dedup.add_argument("--input-worker-id", action="append", required=True)
claim_deep_dedup.add_argument("--coordinator-generation", type=positive_int)
commit_deep_dedup = add_command(
"commit-deep-scan-dedup", "--scan-id", "--worker-id", "--result-manifest-path"
)
commit_deep_dedup.add_argument("--candidate-ledger-path")
commit_deep_dedup.add_argument("--new-findings-count", type=non_negative_int, required=True)
commit_deep_dedup.add_argument("--coordinator-generation", type=positive_int)
finish_deep_scan = add_command("finish-deep-scan", "--scan-id")
finish_deep_scan.add_argument(
"--terminal-reason", choices=("saturated", "capped"), required=True
)
finish_deep_scan.add_argument("--manifest-path", required=True)
finish_deep_scan.add_argument("--staged-manifest-path")
finish_deep_scan.add_argument("--omitted-worker-id", action="append", default=[])
finish_deep_scan.add_argument("--coordinator-generation", type=positive_int)
fail_deep_scan = add_command("fail-deep-scan", "--scan-id", "--message")
fail_deep_scan.add_argument("--manifest-path")
fail_deep_scan.add_argument("--staged-manifest-path")
fail_deep_scan.add_argument(
"--deep-status", choices=("failed", "interrupted"), default="failed"
)
fail_deep_scan.add_argument("--coordinator-generation", type=positive_int)
publication_failure = add_command(
"record-deep-scan-publication-failure", "--scan-id", "--message"
)
publication_failure.add_argument("--coordinator-generation", type=positive_int)
get_scan = add_command("get-scan", "--scan-id")
get_scan.add_argument("--occurrence-id")
@@ -130,7 +211,7 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
list_scans.add_argument("--mode", choices=MODES)
list_scans.add_argument("--repository")
list_scans.add_argument("--scan-root")
list_scans.add_argument("--offset", type=deep_scan.non_negative_int, default=0)
list_scans.add_argument("--offset", type=non_negative_int, default=0)
list_scans.add_argument("--limit", type=positive_int)
list_unmatched_scan_pairs = add_command("list-unmatched-scan-pairs", "--repository")
@@ -178,30 +259,30 @@ def parse_args(description: str, *, inspection_only: bool = False) -> argparse.N
list_global_findings.add_argument("--severity", choices=FINDING_SEVERITIES)
list_global_findings.add_argument("--status", choices=FINDING_STATUSES)
list_global_findings.add_argument("--target-id")
list_global_findings.add_argument("--offset", type=deep_scan.non_negative_int, default=0)
list_global_findings.add_argument("--offset", type=non_negative_int, default=0)
list_global_findings.add_argument("--limit", type=positive_int, default=FINDINGS_PAGE_MAX)
list_repositories = subparsers.add_parser("list-repositories")
list_repositories.add_argument("--query")
list_repositories.add_argument("--target-id")
list_repositories.add_argument("--status", choices=("scanned", "not_scanned", "open_findings"))
list_repositories.add_argument("--offset", type=deep_scan.non_negative_int, default=0)
list_repositories.add_argument("--offset", type=non_negative_int, default=0)
list_repositories.add_argument("--limit", type=positive_int)
list_findings = add_command("list-findings", "--scan-id")
list_findings.add_argument("--query")
list_findings.add_argument("--severity", choices=FINDING_SEVERITIES)
list_findings.add_argument("--status", choices=FINDING_STATUSES)
list_findings.add_argument("--offset", type=deep_scan.non_negative_int, default=0)
list_findings.add_argument("--offset", type=non_negative_int, default=0)
list_findings.add_argument("--limit", type=positive_int, default=FINDINGS_PAGE_MAX)
update_progress = add_command("update-progress", "--scan-id")
update_progress.add_argument("--phase", choices=PHASES)
update_progress.add_argument("--phase-items-total", type=deep_scan.non_negative_int)
update_progress.add_argument("--phase-items-completed", type=deep_scan.non_negative_int)
update_progress.add_argument("--phase-items-total", type=non_negative_int)
update_progress.add_argument("--phase-items-completed", type=non_negative_int)
update_progress.add_argument("--phase-progress-unit", choices=PHASE_PROGRESS_UNITS)
update_progress.add_argument("--review-items-total", type=deep_scan.non_negative_int)
update_progress.add_argument("--review-items-completed", type=deep_scan.non_negative_int)
update_progress.add_argument("--reportable-findings-count", type=deep_scan.non_negative_int)
update_progress.add_argument("--review-items-total", type=non_negative_int)
update_progress.add_argument("--review-items-completed", type=non_negative_int)
update_progress.add_argument("--reportable-findings-count", type=non_negative_int)
update_progress.add_argument("--deep-review-pass", type=positive_int)
update_progress.add_argument("--claim-token")
update_progress.add_argument("--coordinator-generation", type=positive_int)
@@ -4,7 +4,6 @@ import argparse
import os
import sqlite3
import sys
from collections import Counter
from collections.abc import Iterator
from itertools import islice
from pathlib import Path
@@ -204,8 +203,7 @@ def list_repositories(
connection: sqlite3.Connection,
args: argparse.Namespace | None = None,
) -> dict[str, Any]:
scan_count_by_target = Counter()
latest_by_target: dict[str, tuple[sqlite3.Row, dict[str, Any] | None]] = {}
by_target: dict[str, dict[str, Any]] = {}
for row in connection.execute(
f"""
SELECT targets.id AS repository_id, targets.display_name, targets.current_path,
@@ -219,26 +217,24 @@ def list_repositories(
).fetchall():
scan = scan_history.scan_summary(row) if row["id"] is not None else None
target_id = row["repository_id"]
if target_id not in by_target:
by_target[target_id] = {
"displayName": row["display_name"],
"latestScan": scan,
"openFindingsCount": 0,
"scanCount": 0,
"targetId": target_id,
"targetPath": row["current_path"],
}
if scan is not None:
scan_count_by_target[target_id] += 1
latest_by_target.setdefault(target_id, (row, scan))
by_target[target_id]["scanCount"] += 1
open_findings_by_target = Counter(
row["target_id"] for row in _indexed_findings(connection) if row["status"] == "open"
)
repositories = [
{
"displayName": target["display_name"],
"latestScan": latest_scan,
"openFindingsCount": open_findings_by_target[target_id]
if latest_scan is not None
else 0,
"scanCount": scan_count_by_target[target_id],
"targetId": target_id,
"targetPath": target["current_path"],
}
for target_id, (target, latest_scan) in latest_by_target.items()
]
# A writer can publish a target or its first scan after the repository query.
for finding in _indexed_findings(connection):
repository = by_target.get(finding["target_id"])
if finding["status"] == "open" and repository is not None and repository["scanCount"]:
repository["openFindingsCount"] += 1
repositories = list(by_target.values())
pagination = {}
if args is not None:
query = args.query.strip().casefold() if args.query else ""
@@ -127,7 +127,6 @@ def collect_scan_usage(
rate_limits: dict[str, dict[str, Any]] = {}
tokens_updated_at = None
accepted_thread_ids: set[str] = set()
measured_thread_ids: set[str] = set()
excluded_thread_ids: set[str] = set()
for session in sessions:
if session.parent_thread_id in excluded_thread_ids:
@@ -171,7 +170,6 @@ def collect_scan_usage(
if "token_usage_unavailable" in usage.warnings:
missing_thread_ids.add(session.thread_id)
continue
measured_thread_ids.add(session.thread_id)
role = by_role["parent" if session.thread_id in parent_ids else "workers"]
_add_token_usage(role, usage.tokens)
role["threadCount"] += 1
@@ -182,7 +180,8 @@ def collect_scan_usage(
if not accepted_thread_ids:
return _unavailable_usage("scan_thread_unavailable", warnings=warnings)
if not measured_thread_ids:
thread_count = sum(role["threadCount"] for role in by_role.values())
if not thread_count:
return _unavailable_usage(
"token_usage_unavailable", warnings=warnings, rate_limits=rate_limits
)
@@ -202,7 +201,7 @@ def collect_scan_usage(
"coverage": "partial" if missing_thread_ids or warnings else "complete",
"source": "codex_rollout",
**{key: sum(role[key] for role in by_role.values()) for key in TOKEN_FIELDS.values()},
"threadCount": len(measured_thread_ids),
"threadCount": thread_count,
"byRole": by_role,
"window": {"startedAt": started_at.isoformat(), "endedAt": stopped_at.isoformat()},
"observedAt": observed_at.isoformat(),
@@ -506,6 +505,14 @@ def _read_rollout_usage(
closed_turns: set[str] = set()
measured_turns: set[str] = set()
def past_scan_end(timestamp: datetime, turn_id: object) -> bool:
# The requested completion turn may finish after the scan was marked complete.
return (
completed_at is not None
and timestamp > completed_at
and (completed_turn_id is None or turn_id != completed_turn_id)
)
with session.path.open("rb") as source:
for line_number, raw_line in enumerate(source, start=1):
if not raw_line.endswith(b"\n"):
@@ -559,10 +566,8 @@ def _read_rollout_usage(
if task_started_at is None:
warnings.add("thread_ownership_unavailable")
return result
if task_started_at < started_at or (
completed_at is not None
and task_started_at > completed_at
and payload.get("turn_id") != completed_turn_id
if task_started_at < started_at or past_scan_end(
task_started_at, payload.get("turn_id")
):
warnings.add("thread_outside_scan_window")
return result
@@ -576,16 +581,8 @@ def _read_rollout_usage(
if event.get("type") == "event_msg" and payload.get("type") == "task_started":
# The same owner can resume as a model-backed coordinator. Only
# a provably post-scan turn leaves the original control zero intact.
task_started_at = _timestamp(event.get("timestamp"))
if (
completed_at is None
or task_started_at is None
or task_started_at <= completed_at
or (
completed_turn_id is not None
and payload.get("turn_id") == completed_turn_id
)
):
timestamp = _timestamp(event.get("timestamp"))
if timestamp is None or not past_scan_end(timestamp, payload.get("turn_id")):
direct_control_session = False
if (
completed_turn_id is not None
@@ -601,14 +598,9 @@ def _read_rollout_usage(
if payload.get("turn_id") != current_turn_id:
observed_response_usage = _empty_token_usage()
current_turn_id = payload.get("turn_id")
timestamp = _timestamp(event.get("timestamp"))
if not isinstance(current_turn_id, str) or not current_turn_id or timestamp is None:
warnings.add("turn_record_invalid")
elif (
completed_at is None
or timestamp <= completed_at
or current_turn_id == completed_turn_id
):
elif not past_scan_end(timestamp, current_turn_id):
started_turns.add(current_turn_id)
open_turns.add(current_turn_id)
continue
@@ -624,11 +616,7 @@ def _read_rollout_usage(
or timestamp is None
):
warnings.add("turn_record_invalid")
elif (
completed_at is None
or timestamp <= completed_at
or terminal_turn_id == completed_turn_id
):
elif not past_scan_end(timestamp, terminal_turn_id):
open_turns.discard(terminal_turn_id)
if timestamp >= started_at:
if terminal_turn_id in started_turns:
@@ -648,11 +636,7 @@ def _read_rollout_usage(
if (
timestamp is not None
and timestamp >= started_at
and (
completed_at is None
or timestamp <= completed_at
or (completed_turn_id is not None and current_turn_id == completed_turn_id)
)
and not past_scan_end(timestamp, current_turn_id)
and "compaction_response_id" not in payload
and response_usage is None
):
@@ -675,15 +659,13 @@ def _read_rollout_usage(
):
warnings.add("token_record_invalid")
continue
is_completion_turn = (
completed_turn_id is not None and payload.get("turn_id") == completed_turn_id
)
if completed_at is not None and timestamp > completed_at and not is_completion_turn:
receipt_turn_id = payload.get("turn_id")
if past_scan_end(timestamp, receipt_turn_id):
continue
if response_usage is None:
response_usage = _empty_token_usage()
if current_turn_id is None:
current_turn_id = payload.get("turn_id")
current_turn_id = receipt_turn_id
if isinstance(current_turn_id, str):
open_turns.add(current_turn_id)
if response_id in response_ids:
@@ -691,14 +673,13 @@ def _read_rollout_usage(
response_ids.add(response_id)
_add_token_usage(observed_response_usage, usage)
turn_usage = _usage_counts(payload.get("turn_token_usage"))
receipt_turn_id = payload.get("turn_id")
if isinstance(receipt_turn_id, str):
measured_turns.add(receipt_turn_id)
if timestamp < started_at:
if turn_usage is not None:
observed_response_usage = turn_usage
continue
if is_completion_turn:
if completed_turn_id is not None and receipt_turn_id == completed_turn_id:
completed_turn_measured = True
if turn_usage is not None and any(
turn_usage[key] > observed_response_usage[key] for key in TOKEN_FIELDS.values()
@@ -713,11 +694,7 @@ def _read_rollout_usage(
in_window = (
timestamp is not None
and timestamp >= started_at
and (
completed_at is None
or timestamp <= completed_at
or (completed_turn_id is not None and current_turn_id == completed_turn_id)
)
and not past_scan_end(timestamp, current_turn_id)
)
if in_window:
rate_limits = _rate_limit_snapshot(payload.get("rate_limits"), timestamp)
@@ -730,7 +707,6 @@ def _read_rollout_usage(
result.rate_limits[key] = rate_limits
if "info" in payload and payload["info"] is None:
continue
timestamp = _timestamp(event.get("timestamp"))
snapshot = _token_snapshot(payload)
if timestamp is None or snapshot is None:
warnings.add("token_record_invalid")
@@ -740,16 +716,13 @@ def _read_rollout_usage(
for key, value in snapshot.items()
}
previous = snapshot
is_completion_turn = (
completed_turn_id is not None and current_turn_id == completed_turn_id
)
if completed_at is not None and timestamp > completed_at and not is_completion_turn:
if past_scan_end(timestamp, current_turn_id):
continue
if isinstance(current_turn_id, str):
measured_turns.add(current_turn_id)
if timestamp < started_at:
continue
if is_completion_turn:
if completed_turn_id is not None and current_turn_id == completed_turn_id:
completed_turn_measured = True
result.tokens_updated_at = max(result.tokens_updated_at or timestamp, timestamp)
if delta["totalTokens"] <= 0:
@@ -24,6 +24,8 @@ For a finding link, accept the selected Cloud `webOrigin` with the path `/codex/
## List and inspect findings
When the findings list or detail tool offers `api_version`, select `v2` for requests that include imported scanner findings. The default `v1` view covers native findings. For an imported-only list, also set `source` to `imported` if exposed. Use only provider values advertised by the selected tool. If you filter returned evidence locally, follow every page in the requested scope and say how you filtered it.
Use `defense_factory_findings_list` with the discovered repository URL in `repo` and the user's filters; `repo` accepts comma-separated URLs, not repository IDs. Workflow tools use the returned repository ID in `repo_id`. Filters may include severity (`criticality`), lifecycle `status`, `source`, `q`, `path_prefix`, `start_at`, `end_at`, `scan_id`, `review_run_id`, `validated`, `has_patch`, `author`, and `assignee`; use the tool's current schema for available filters and their accepted values. `assignee` accepts comma-separated recorded user emails and is separate from commit authorship. Do not invent an assigned-team filter.
Follow returned cursors with the same filters and sort order when a complete list or count is requested. Reset the cursor if the filters change. State when only a page or a subset was read. For repository-run findings, use `source: repository_scan` and `scan_id` equal to the run ID. Inspect selected finding IDs with `defense_factory_findings_get` before describing their evidence, assignment, patches, or verification.
@@ -11,7 +11,7 @@ Use `codex-security import sonar` for [live SonarQube Cloud issues](#sonarqube-c
## Select the evidence
Prefer the provider's supported native JSON from its authenticated CLI, plugin, or API. Keep the original records and complete the requested pagination. A JSON summary or a different product's API response is not interchangeable with the documented report. Use SARIF or CSV only when the installed provider reader supports that profile and native JSON is unavailable or the user supplies that format. Do not convert a richer JSON report to SARIF for import.
Use a supplied report, connected tool or signed-in CLI that provides the requested native records for the selected account, repository and ref. Follow the [scanner import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md) to narrow broader reports and verify the selection in the JSON preview. Use a direct API only when the provider guide supports its response for the selected destination. Otherwise ask for a supported report. A fresh scan produces new findings. Keep the original records and complete the requested pagination. A JSON summary or a different product's API response is not interchangeable with the documented report. Use SARIF or CSV only when the installed provider reader supports that profile and native JSON is unavailable or the user supplies that format. Do not convert a richer JSON report to SARIF for import.
Use the same acquisition format for repeated imports. Check the provider's identity rules before switching formats: another format can create a separate record or replace a richer snapshot with less detail. Importing findings does not reconcile equivalent vulnerabilities across formats. `--format json` controls command output, not the input report format; readers detect their supported inputs.
@@ -86,7 +86,7 @@ Prefer native Code/SAST CLI or CI JSON for this reader; use self-contained SARIF
For a user-requested new scan, use the installed Semgrep CLI from the source repository root with the selected SAST rules: `semgrep scan --config /path/to/sast-rules.yaml --json-output /path/to/semgrep.json .`. Existing CI jobs can produce the same artifact using `--json-output`; authenticated `semgrep ci --code` follows the job's policy and baseline scope. Explain that this generates fresh scan findings, and do not substitute it for a request to retrieve existing Platform findings.
For existing findings, the official [Semgrep Guardian Codex plugin](https://docs.semgrep.dev/semgrep-guardian/ide-setup/codex) can help select and inspect them. Importing its output needs a separate qualified response mapping and complete pagination for the selected repository/ref. The local `semgrep_findings` MCP tool and Platform REST API also use contracts distinct from CLI reports. Do not reshape a summary into a scan report or claim that a limited tool response is a complete export.
For selected Semgrep Platform SAST findings, follow the [local SDK example](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#import-selected-semgrep-platform-sast-findings-with-the-sdk). It takes the original Web API project response, SAST findings pages and selected IDs. The [Semgrep Guardian Codex plugin](https://docs.semgrep.dev/semgrep-guardian/ide-setup/codex) can help select and inspect findings. Guardian and the `semgrep_findings` MCP tool return different records from the SDK inputs.
Import the native report with `--provider semgrep`, a stable organization/project/branch `--source-key`, and `--source-repository-url` identifying the actual source repository. Use `--to local --repository /path/to/project` for local storage or `--to cloud --repository URL_OR_ID` for Cloud. The source URL is checked against configured local Git remotes or the Cloud destination. Preview with `--dry-run --format json` before confirming the import.
@@ -146,7 +146,7 @@ Use a separate stable source key for each GitHub finding family. Code-scanning i
Resolve the user's destination to a connected GitHub or GitHub Enterprise repository URL or Cloud repository ID, including custom Enterprise hosts. Confirm the intended Cloud account and an authorized repository environment. Use the existing file-backed ChatGPT login; explain a missing or incompatible login rather than changing credential storage automatically.
For another Cloud deployment, read [Deployment settings](references/wiz-import.md#deployment-settings) before previewing. Keep the selected deployment and login throughout the upload.
For staging or another Cloud deployment, configure the [deployment settings](#deployment-settings) before previewing. Keep the selected deployment and login throughout the upload.
### Preview and approve
@@ -162,6 +162,25 @@ Obtain explicit confirmation for this concrete upload, including skipped records
### Upload and report
Read [Results and recovery](references/wiz-import.md#results-and-recovery), including when the process exits nonzero. After a lost response or retryable failure, repeat the command with unchanged input and destination so the publisher resumes saved requests. A lost response does not mean nothing reached Cloud. A repository reset requires fresh discovery and confirmation before a new publication.
Read the structured result even when the process exits nonzero. Progress appears on stderr.
Report verified, unacknowledged, excluded, and failed records distinctly, retaining source IDs and recovery details. Receipts and source-record readback confirm stored vendor evidence; they do not establish a Codex assessment or visibility in the shared Cloud Findings view. Include the returned `cloudUrl` as a clickable repository link when available; do not invent a UI link from the API endpoint.
| Status | Exit code | Meaning |
| ------------- | --------- | ------------------------------------------------------- |
| `complete` | 0 | All selected records were acknowledged and read back. |
| `partial` | 1 | Some records were excluded or have final item failures. |
| `interrupted` | 2 | Upload, verification, or receipt persistence stopped. |
| `failed` | 2 | Preparation failed before upload. |
Cancellation uses the normal signal exit code. Report verified, unacknowledged, excluded, and failed records separately. Include source IDs from `failures`, any `savedSubmission` path, and recovery errors. Receipts and readback confirm stored vendor evidence. Assessment and visibility in the shared Cloud Findings view require separate verification. Link to the returned `cloudUrl` when available.
### Resume an interrupted upload
After a lost response or retryable failure, repeat the command with the same input and destination. Cloud may already have accepted some records. The publisher reuses saved request IDs and bodies, resends only requests without a saved receipt, and verifies the acknowledged records. Existing findings keep their original Cloud environment when the repository default changes.
If the repository was reset, stop and report the error. Rediscover the repository and get fresh confirmation before starting a new publication.
### Deployment settings
Set `CODEX_SECURITY_CLOUD_BASE_URL` to the deployment's API root for preview and upload. Use its login and an isolated state directory for tests. If the user or Cloud page supplies an app URL, set `CODEX_SECURITY_CLOUD_WEB_URL` to that full URL. This setting controls the returned UI link. The API root and login still determine routing and authentication.
Check the preview's `cloudApiUrl` and any `cloudUrl` against the intended API endpoint and app. Saved retries are scoped to the deployment. `CODEX_SECURITY_CLOUD_PUBLISH_URL` applies only to native scan publication. If staging is unavailable, stop before uploading.
@@ -6,6 +6,8 @@ The importer reads JSON, normalized JSONL, and the repository package-vulnerabil
Keep raw source records unchanged in `source_data`. Use the vendor occurrence ID, not a rule, CVE, title, or location. Missing IDs, severity, revisions, and locations must not be invented.
For Cloud preview, approval, upload, and recovery, follow the [Cloud publication workflow](../SKILL.md#publish-to-cloud).
### Package vulnerabilities
Supported inputs include a vulnerability finding, an array, `data.vulnerabilityFindings.nodes`, a downloaded vulnerability report, and JSONL package records. Keep `id`, `name`, `detailedName`, `vendorSeverity` (or `severity`), and `vulnerableAsset.id`, with available package and source metadata. Existing package occurrence IDs are unchanged.
@@ -41,24 +43,3 @@ SAST, repository-secret, and IaC CSV reports still require a reviewed mapping of
| IaC | Rule IDs/name, source range and matched content, platform, expected/actual content, file link, remediation instructions |
Select source paths and line numbers explicitly for secret reports; the standard metadata query lacks them. Preserve empty IaC comparison strings. Vendor status, AI verdicts, and secret validation remain vendor evidence, not Codex assessments. An introduced commit is not a scanned revision, and a logical IaC resource does not prove runtime deployment.
## Deployment settings
For staging or another Cloud deployment, set `CODEX_SECURITY_CLOUD_BASE_URL` to its API root before preview and upload. Use that deployment's login and an isolated state directory for tests. If the user or Cloud page supplies an app URL, also set `CODEX_SECURITY_CLOUD_WEB_URL` to that full URL. This setting controls the returned UI link, not API routing or authentication.
Verify preview `cloudApiUrl` and any `cloudUrl` against the intended deployment: the former is the API endpoint, the latter the UI link. Saved retries are separated by deployment. `CODEX_SECURITY_CLOUD_PUBLISH_URL` routes native scan publication only, not vendor imports. Never fall back to production when staging is unavailable.
## Results and recovery
For Cloud publication, read the structured result even when the process exits nonzero; stderr progress does not replace it.
| Status | Exit code | Meaning |
| ------------- | --------- | ------------------------------------------------------------------------------------ |
| `complete` | 0 | All selected records were acknowledged and read back. |
| `partial` | 1 | Local exclusions or final item failures remain. |
| `interrupted` | 2 | Upload, verification, or receipt persistence stopped; acknowledged work is retained. |
| `failed` | 2 | Preparation failed before upload. |
Cancellation retains the normal signal exit code. Report `failures` by vendor source ID, distinguish `verified` from `unacknowledged`, and retain `savedSubmission` and recovery errors.
Retry with unchanged input and destination. The publisher resends only unacknowledged requests using saved IDs and bodies. Existing findings retain their original Cloud environment even if the repository default changes. After a repository reset, stop and show the error; fresh discovery and confirmation are required before a new publication.
@@ -3,6 +3,7 @@
import os
import runpy
import sqlite3
import subprocess
import sys
from pathlib import Path
from types import SimpleNamespace
@@ -15,6 +16,23 @@ class CrashBeforeCommit(sqlite3.Connection):
os._exit(COMMIT_EXIT)
def interrupt_finish_before_commit(database, scan, hash_seed):
result = subprocess.run(
[
sys.executable,
"-B",
__file__,
str(database),
scan.scan_id,
str(scan.scan_dir),
],
env={**os.environ, "PYTHONHASHSEED": str(hash_seed)},
capture_output=True,
text=True,
)
assert result.returncode == COMMIT_EXIT, result.stdout + result.stderr
def finish_until_commit(deep_scan, database, scan_id, scan_dir):
with sqlite3.connect(database, factory=CrashBeforeCommit) as connection:
connection.row_factory = sqlite3.Row
File diff suppressed because it is too large Load Diff
@@ -7,18 +7,14 @@ from argparse import Namespace
from pathlib import Path
import pytest
from test_deep_scan_successful_publication import (
add_worker,
fail_scan,
preserve_scan_results,
recover_scan_results,
)
from test_deep_scan_successful_publication import publication_scan as publication_scan
from workbench_test_support import (
interrupt_publication,
read_review_state,
saved_draft,
select_checkpoint,
write_checkpoint,
write_result_draft,
)
@@ -35,17 +31,11 @@ def test_published_raw_head_compatibility_converts_before_later_selection(
(scan.scan_dir / "findings.json").write_text(json.dumps({"findings": []}))
for name in ("scan-manifest.json", "coverage.json", "findings.json"):
os.utime(scan.scan_dir / name, ns=(0, 0))
directory = (
scan.scan_dir
if owner == "root"
else add_worker(workbench_db, scan, status="canceled").parent
)
directory = scan.scan_dir if owner == "root" else scan.add_worker(status="canceled").parent
initial = saved_draft(scan.scan_id, complete=True)
initial["coverage"] = {**scan.coverage, **initial["coverage"]}
checkpoint = write_checkpoint(directory / "checkpoints", initial)
head = directory / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(100, 100))
head = select_checkpoint(directory, checkpoint, mtime_ns=100)
capture = saved._capture_saved_source
def legacy_capture(root, relative, scan_id, *, checkpoint_heads=None, **kwargs):
@@ -55,7 +45,7 @@ def test_published_raw_head_compatibility_converts_before_later_selection(
with monkeypatch.context() as patch:
patch.setattr("workbench.retained_coverage._capture_saved_source", legacy_capture)
fail_scan(workbench_api, workbench_db, scan)
scan.fail()
original = (scan.scan_dir / "scan-manifest.json").read_bytes()
assert (
head.relative_to(scan.scan_dir).as_posix()
@@ -78,9 +68,8 @@ def test_published_raw_head_compatibility_converts_before_later_selection(
Path(path).name == "checkpoint-head.json" for path in normalized["preservedSources"]
)
later = write_checkpoint(directory / "checkpoints", {**initial, "findings": scan.findings})
head.write_text(json.dumps({"checkpoint": later.name}))
os.utime(head, ns=(200, 200))
recovered = recover_scan_results(workbench_api, workbench_db, scan)
select_checkpoint(directory, later, mtime_ns=200)
recovered = scan.recover()
assert recovered["findingCount"] == 1
assert not recovered["resultsRecoveryNeeded"]
@@ -92,8 +81,8 @@ def test_early_head_error_keeps_captured_records_during_sibling_capture(
saved = workbench_api["saved_results"]
context = workbench_api["_WORKBENCH_DB_CONTEXT"]
(scan.scan_dir / "findings.json").write_text(json.dumps({"findings": []}))
first = add_worker(workbench_db, scan, status="canceled").parent
second = add_worker(workbench_db, scan, status="canceled").parent
first = scan.add_worker(status="canceled").parent
second = scan.add_worker(status="canceled").parent
with workbench_db:
for directory, created_at in [
(first, "2026-01-01T00:00:00Z"),
@@ -110,9 +99,7 @@ def test_early_head_error_keeps_captured_records_during_sibling_capture(
checkpoint = write_checkpoint(
directory / "checkpoints", saved_draft(scan.scan_id, complete=True, findings=[finding])
)
head = directory / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(100, 100))
head = select_checkpoint(directory, checkpoint, mtime_ns=100)
if directory == first:
original = head.read_bytes()
write = saved.write_scan_local_bytes
@@ -136,7 +123,7 @@ def test_early_head_error_keeps_captured_records_during_sibling_capture(
with monkeypatch.context() as patch:
patch.setattr("workbench.saved_sources.write_scan_local_bytes", capture_sibling)
fail_scan(workbench_api, workbench_db, scan)
scan.fail()
assert changed
args = Namespace(
scan_id=scan.scan_id, claim_token=None, thread_id=None, coordinator_generation=None
@@ -154,7 +141,7 @@ def test_early_head_error_keeps_captured_records_during_sibling_capture(
assert {row["identity"]["anchor"] for row in findings["findings"]} == {"before", "second"}
head.write_bytes(later)
os.utime(head, ns=(200, 200))
recover_scan_results(workbench_api, workbench_db, scan)
scan.recover()
_, findings, _ = saved.finalize_scan(scan.scan_dir)
assert "after" in {row["identity"]["anchor"] for row in findings["findings"]}
@@ -171,13 +158,12 @@ def test_frozen_model_capture_keeps_earlier_worker_finding(
manifest["scan"]["threatModel"] = model
manifest_path.write_text(json.dumps(manifest))
(scan.scan_dir / "findings.json").unlink()
result = add_worker(workbench_db, scan, status="succeeded")
result = scan.add_worker(status="succeeded")
worker_draft = saved_draft(scan.scan_id, findings=scan.findings, complete=True)
result.write_text(json.dumps(worker_draft))
partial = saved_draft(scan.scan_id, complete=False)
checkpoint = write_checkpoint(scan.scan_dir / "checkpoints", partial)
head = scan.scan_dir / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
head = select_checkpoint(scan.scan_dir, checkpoint)
for path, timestamp in ((result, 100_000), (manifest_path, 150_000), (head, 200_000)):
os.utime(path, ns=(timestamp, timestamp))
model_draft = saved._parent_scan_draft(
@@ -201,7 +187,7 @@ def test_frozen_model_capture_keeps_earlier_worker_finding(
patch.setattr("workbench.retained_coverage.write_scan_local_bytes", interrupt_capture)
else:
patch.setattr(saved, "_write_prepared_scan_finalization", interrupt)
fail_scan(workbench_api, workbench_db, scan)
scan.fail()
if not restore_capture:
assert len(initial) == len(initial[0]) == 1
retained = json.loads(
@@ -212,7 +198,7 @@ def test_frozen_model_capture_keeps_earlier_worker_finding(
capture = scan.scan_dir / retained["threatModelSource"]
assert retained["threatModelSource"] == model_path
assert capture.exists() is not restore_capture
preserve_scan_results(workbench_api, workbench_db, scan)
scan.preserve()
final_manifest, findings, _ = saved.finalize_scan(scan.scan_dir)
assert final_manifest["scan"]["threatModel"] == model
assert len(findings["findings"]) == 1
@@ -240,12 +226,11 @@ def test_frozen_model_ignores_unselected_live_manifest_changes(
os.utime(scan.scan_dir / name, ns=(150, 150))
_, canonical = saved._read_saved_parent_result(scan.scan_dir, scan.scan_id)
selected = write_checkpoint(
scan.scan_dir / "checkpoints", {k: v for k, v in canonical.items() if k != "threatModel"}
scan.scan_dir / "checkpoints",
{k: v for k, v in canonical.items() if k != "threatModel"},
mtime_ns=50,
)
os.utime(selected, ns=(50, 50))
head = scan.scan_dir / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
os.utime(head, ns=(200, 200))
select_checkpoint(scan.scan_dir, selected, mtime_ns=200)
write = saved.write_scan_local_bytes
def fail_order(root, relative, contents):
@@ -273,7 +258,7 @@ def test_frozen_model_ignores_unselected_live_manifest_changes(
if late_model:
manifest["scan"]["threatModel"] = {"summary": "Late unselected model"}
manifest_path.write_text(json.dumps(manifest))
replayed = preserve_scan_results(workbench_api, workbench_db, scan)
replayed = scan.preserve()
published, findings, _ = saved.finalize_scan(scan.scan_dir)
assert published["scan"]["threatModel"] == model
assert len(findings["findings"]) == replayed["findingCount"] == 1
@@ -304,16 +289,11 @@ def test_resumed_head_snapshot_allows_later_recovery(
(scan.scan_dir / "findings.json").write_text(json.dumps({"findings": []}))
for name in ("scan-manifest.json", "coverage.json", "findings.json"):
os.utime(scan.scan_dir / name, ns=(0, 0))
directory = (
scan.scan_dir
if owner == "root"
else add_worker(workbench_db, scan, status="canceled").parent
)
directory = scan.scan_dir if owner == "root" else scan.add_worker(status="canceled").parent
relative = directory.relative_to(scan.scan_dir)
initial = saved_draft(scan.scan_id, complete=True)
initial["coverage"] = {**scan.coverage, **initial["coverage"]}
checkpoint = write_checkpoint(directory / "checkpoints", initial)
os.utime(checkpoint, ns=(50, 50))
checkpoint = write_checkpoint(directory / "checkpoints", initial, mtime_ns=50)
head = directory / "checkpoint-head.json"
original_head = json.dumps({"checkpoint": checkpoint.name})
head.write_text(original_head)
@@ -328,7 +308,7 @@ def test_resumed_head_snapshot_allows_later_recovery(
with monkeypatch.context() as patch:
if snapshot_failure:
patch.setattr("workbench.saved_sources.write_scan_local_bytes", fail_head)
fail_scan(workbench_api, workbench_db, scan)
scan.fail()
args = Namespace(
scan_id=scan.scan_id, claim_token=None, thread_id=None, coordinator_generation=None
)
@@ -352,11 +332,11 @@ def test_resumed_head_snapshot_allows_later_recovery(
"observedAtNs": "100",
}
assert head.read_text() == original_head
later = write_checkpoint(directory / "checkpoints", {**initial, "findings": scan.findings})
os.utime(later, ns=(50, 50))
head.write_text(json.dumps({"checkpoint": later.name}))
os.utime(head, ns=(200, 200))
result = recover_scan_results(workbench_api, workbench_db, scan)
later = write_checkpoint(
directory / "checkpoints", {**initial, "findings": scan.findings}, mtime_ns=50
)
select_checkpoint(directory, later, mtime_ns=200)
result = scan.recover()
assert result["findingCount"] == 1
assert not result["resultsRecoveryNeeded"]
published, findings, _ = saved.finalize_scan(scan.scan_dir)
@@ -378,7 +358,6 @@ def test_resumed_head_snapshot_allows_later_recovery(
@pytest.mark.parametrize("live_change", ["coverage", "model"])
def test_early_head_failure_keeps_frozen_model_choice(
workbench_api,
workbench_db,
publication_scan,
monkeypatch,
mode,
@@ -396,26 +375,21 @@ def test_early_head_failure_keeps_frozen_model_choice(
os.utime(scan.scan_dir / name, ns=(150, 150))
draft = saved_draft(scan.scan_id, complete=True, findings=scan.findings)
draft["coverage"] = {**scan.coverage, **draft["coverage"]}
head = scan.scan_dir / "checkpoint-head.json"
for label, observed in [
("Accepted model", 180 if model_choice == "accepted" else 100),
("Selected model" if model_choice == "selected" else None, 200),
]:
payload = {**draft, **({"threatModel": {"summary": label}} if label else {})}
checkpoint = write_checkpoint(scan.scan_dir / "checkpoints", payload)
os.utime(checkpoint, ns=(50, 50))
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(observed, observed))
checkpoint = write_checkpoint(scan.scan_dir / "checkpoints", payload, mtime_ns=50)
select_checkpoint(scan.scan_dir, checkpoint, mtime_ns=observed)
if label == "Accepted model":
saved._capture_saved_source(scan.scan_dir, "checkpoint-head.json", scan.scan_id)
if failure == "worker-head":
directory = add_worker(workbench_db, scan, status="canceled").parent
directory = scan.add_worker(status="canceled").parent
worker_checkpoint = write_checkpoint(
directory / "checkpoints", saved_draft(scan.scan_id, complete=True)
)
worker_head = directory / "checkpoint-head.json"
worker_head.write_text(json.dumps({"checkpoint": worker_checkpoint.name}))
os.utime(worker_head, ns=(200, 200))
select_checkpoint(directory, worker_checkpoint, mtime_ns=200)
write = saved.write_scan_local_bytes
def fail_snapshot(root, relative, contents):
@@ -434,7 +408,7 @@ def test_early_head_failure_keeps_frozen_model_choice(
with monkeypatch.context() as patch:
patch.setattr("workbench.saved_sources.write_scan_local_bytes", fail_snapshot)
fail_scan(workbench_api, workbench_db, scan)
scan.fail()
if failure != "none":
if live_change == "coverage":
coverage_path = scan.scan_dir / "coverage.json"
@@ -444,7 +418,7 @@ def test_early_head_failure_keeps_frozen_model_choice(
else:
manifest["scan"]["threatModel"] = {"summary": "Late unselected model"}
manifest_path.write_text(json.dumps(manifest))
result = preserve_scan_results(workbench_api, workbench_db, scan)
result = scan.preserve()
published, findings, _ = saved.finalize_scan(scan.scan_dir)
expected = {
"canonical": "Canonical model",
@@ -470,20 +444,14 @@ def test_failed_head_fallback_rejects_changes_before_resume(
(scan.scan_dir / "findings.json").write_text(json.dumps({"findings": []}))
for name in ("scan-manifest.json", "coverage.json", "findings.json"):
os.utime(scan.scan_dir / name, ns=(0, 0))
directory = (
scan.scan_dir
if owner == "root"
else add_worker(workbench_db, scan, status="canceled").parent
)
directory = scan.scan_dir if owner == "root" else scan.add_worker(status="canceled").parent
relative = directory.relative_to(scan.scan_dir)
initial = saved_draft(scan.scan_id, complete=True)
initial["coverage"] = {**scan.coverage, **initial["coverage"]}
checkpoint = write_checkpoint(directory / "checkpoints", initial)
original_checkpoint = checkpoint.read_bytes()
os.utime(checkpoint, ns=(50, 50))
head = directory / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(100, 100))
head = select_checkpoint(directory, checkpoint, mtime_ns=100)
original_head = head.read_bytes()
original_outputs = {
name: (scan.scan_dir / name).read_bytes()
@@ -499,11 +467,10 @@ def test_failed_head_fallback_rejects_changes_before_resume(
with monkeypatch.context() as patch:
patch.setattr("workbench.saved_sources.write_scan_local_bytes", fail_head)
fail_scan(workbench_api, workbench_db, scan)
scan.fail()
if change == "head":
later = write_checkpoint(directory / "checkpoints", {**initial, "findings": scan.findings})
head.write_text(json.dumps({"checkpoint": later.name}))
os.utime(head, ns=(100, 100))
select_checkpoint(directory, later, mtime_ns=100)
elif change == "timestamp":
os.utime(head, ns=(200, 200))
else:
@@ -562,11 +529,8 @@ def test_rejected_historical_model_does_not_poison_recovery(
draft.update(findings=scan.findings, coverage={**scan.coverage, **draft["coverage"]})
def select(value, observed):
path = write_checkpoint(scan.scan_dir / "checkpoints", value)
os.utime(path, ns=(50, 50))
head = scan.scan_dir / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": path.name}))
os.utime(head, ns=(observed, observed))
path = write_checkpoint(scan.scan_dir / "checkpoints", value, mtime_ns=50)
select_checkpoint(scan.scan_dir, path, mtime_ns=observed)
return path.relative_to(scan.scan_dir).as_posix()
_, canonical = saved._read_saved_parent_result(scan.scan_dir, scan.scan_id)
@@ -574,7 +538,7 @@ def test_rejected_historical_model_does_not_poison_recovery(
select({**draft, "threatModel": {"summary": "Older accepted model"}}, 100)
saved._capture_saved_source(scan.scan_dir, "checkpoint-head.json", scan.scan_id)
invalid_source = select({**draft, "threatModel": invalid}, 200)
stopped = fail_scan(workbench_api, workbench_db, scan)
stopped = scan.fail()
assert stopped["findingCount"] == 1
assert any("Skipped malformed saved threat model" in warning for warning in stopped["warnings"])
assert json.loads(manifest_path.read_text())["scan"]["threatModel"] == model
@@ -598,7 +562,7 @@ def test_rejected_historical_model_does_not_poison_recovery(
saved.recover_scan_results(context, workbench_db, args)
else:
saved.recover_scan_results(context, workbench_db, args)
replayed = preserve_scan_results(workbench_api, workbench_db, scan)
replayed = scan.preserve()
published, findings, _ = saved.finalize_scan(scan.scan_dir)
assert published["scan"]["threatModel"] == (
{"summary": "Replacement model"} if replacement == "valid" else model
@@ -650,11 +614,7 @@ def test_partial_head_retains_previous_terminal_coverage_boundary(
(scan.scan_dir / "coverage.json").write_text(json.dumps(coverage))
for name in ("findings.json", "coverage.json", "scan-manifest.json"):
os.utime(scan.scan_dir / name, ns=(0, 0))
directory = (
scan.scan_dir
if owner == "root"
else add_worker(workbench_db, scan, status="canceled").parent
)
directory = scan.scan_dir if owner == "root" else scan.add_worker(status="canceled").parent
saved = workbench_api["saved_results"]
for label, observed in [("Obsolete", 100), ("Replacement", 200), ("Partial", partial_time)]:
draft = saved_draft(scan.scan_id, complete=label != "Partial")
@@ -672,11 +632,8 @@ def test_partial_head_retains_previous_terminal_coverage_boundary(
explicitExclusions=[{"pattern": label + "/**", "reason": label}],
openQuestions=[{"question": label}],
)
checkpoint = write_checkpoint(directory / "checkpoints", draft)
os.utime(checkpoint, ns=(50, 50))
head = directory / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(observed, observed))
checkpoint = write_checkpoint(directory / "checkpoints", draft, mtime_ns=50)
head = select_checkpoint(directory, checkpoint, mtime_ns=observed)
if label == "Replacement" and registered:
with workbench_db:
workbench_db.execute(
@@ -684,9 +641,9 @@ def test_partial_head_retains_previous_terminal_coverage_boundary(
(str(checkpoint), directory.name),
)
if label == "Obsolete":
fail_scan(workbench_api, workbench_db, scan)
scan.fail()
elif label == "Replacement":
recover_scan_results(workbench_api, workbench_db, scan)
scan.recover()
if repeated_terminal:
os.utime(head, ns=(400, 400))
saved._capture_saved_source(
@@ -697,10 +654,10 @@ def test_partial_head_retains_previous_terminal_coverage_boundary(
if interrupted:
patch.setattr(saved, "_write_prepared_scan_finalization", interrupt_publication)
with pytest.raises(OSError, match="Synthetic publication interruption"):
recover_scan_results(workbench_api, workbench_db, scan)
scan.recover()
else:
recover_scan_results(workbench_api, workbench_db, scan)
replayed = preserve_scan_results(workbench_api, workbench_db, scan)
scan.recover()
replayed = scan.preserve()
saved.finalize_scan(scan.scan_dir)
coverage = read_review_state(workbench_db, scan.scan_dir)
expected = {"Replacement"} if partial_time == 300 or registered else {"Obsolete", "Replacement"}
@@ -714,7 +671,7 @@ def test_partial_head_retains_previous_terminal_coverage_boundary(
@pytest.mark.parametrize("head_time", [100_000, 200_000], ids=["older", "tied"])
def test_retry_keeps_canonical_finding_when_its_checkpoint_copy_is_unreadable(
workbench_api, workbench_db, publication_scan, monkeypatch, head_time
workbench_api, publication_scan, monkeypatch, head_time
):
scan = publication_scan(mode="standard")
saved = workbench_api["saved_results"]
@@ -730,9 +687,7 @@ def test_retry_keeps_canonical_finding_when_its_checkpoint_copy_is_unreadable(
checkpoint = write_checkpoint(scan.scan_dir / "checkpoints", {**empty, "findings": []})
broken = checkpoint.parent / f"{saved._digest(canonical)}.json"
broken.write_bytes(b"{")
head = scan.scan_dir / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(head_time, head_time))
select_checkpoint(scan.scan_dir, checkpoint, mtime_ns=head_time)
attempted = []
@@ -744,12 +699,12 @@ def test_retry_keeps_canonical_finding_when_its_checkpoint_copy_is_unreadable(
with monkeypatch.context() as patch:
patch.setattr(saved, "_write_prepared_scan_finalization", interrupt)
fail_scan(workbench_api, workbench_db, scan)
scan.fail()
assert attempted == [(scan.findings[0]["title"], model)]
with pytest.raises(
saved.ContractError, match="Frozen stopped-scan checkpoint set is incomplete"
):
preserve_scan_results(workbench_api, workbench_db, scan)
scan.preserve()
assert broken.read_bytes() == b"{"
assert "sealedAt" not in json.loads(manifest_path.read_text())["scan"]
@@ -780,14 +735,13 @@ def test_inherited_model_capture_is_bound_before_publication_retry(
os.utime(scan.scan_dir / name, ns=(150, 150))
_, canonical = saved._read_saved_parent_result(scan.scan_dir, scan.scan_id)
selected = write_checkpoint(
scan.scan_dir / "checkpoints", {k: v for k, v in canonical.items() if k != "threatModel"}
scan.scan_dir / "checkpoints",
{k: v for k, v in canonical.items() if k != "threatModel"},
mtime_ns=50,
)
os.utime(selected, ns=(50, 50))
broken = scan.scan_dir / f"checkpoints/{saved._digest(canonical)}.json"
broken.write_text("{")
head = scan.scan_dir / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
os.utime(head, ns=(200, 200))
select_checkpoint(scan.scan_dir, selected, mtime_ns=200)
model_draft = saved._parent_scan_draft(
scan.scan_id, {"threatModel": model}, {"findings": []}, {}
)
@@ -804,7 +758,7 @@ def test_inherited_model_capture_is_bound_before_publication_retry(
patch.setattr("workbench.retained_coverage.write_scan_local_bytes", fail_capture)
else:
patch.setattr(saved, "_write_prepared_scan_finalization", interrupt_publication)
fail_scan(workbench_api, workbench_db, scan)
scan.fail()
row = workbench_db.execute(
"SELECT retained_source_digests_json, completion_warnings_json FROM scans WHERE id = ?",
(scan.scan_id,),
@@ -862,11 +816,7 @@ def test_restored_terminal_keeps_surfaces_for_surviving_deferred_work(
(scan.scan_dir / "coverage.json").write_text(json.dumps(coverage))
for name in ("findings.json", "coverage.json", "scan-manifest.json"):
os.utime(scan.scan_dir / name, ns=(0, 0))
directory = (
scan.scan_dir
if owner == "root"
else add_worker(workbench_db, scan, status="canceled").parent
)
directory = scan.scan_dir if owner == "root" else scan.add_worker(status="canceled").parent
saved = workbench_api["saved_results"]
terminal = saved_draft(scan.scan_id, complete=True)
terminal["coverage"] = {**coverage, **terminal["coverage"]}
@@ -888,22 +838,19 @@ def test_restored_terminal_keeps_surfaces_for_surviving_deferred_work(
sequence.append((closed, 300))
sequence.append((terminal, 100))
for index, (draft, observed) in enumerate(sequence):
checkpoint = write_checkpoint(directory / "checkpoints", draft)
os.utime(checkpoint, ns=(50, 50))
head = directory / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(observed, observed))
checkpoint = write_checkpoint(directory / "checkpoints", draft, mtime_ns=50)
select_checkpoint(directory, checkpoint, mtime_ns=observed)
if index == 0:
fail_scan(workbench_api, workbench_db, scan)
scan.fail()
else:
with monkeypatch.context() as patch:
if interrupted and index == len(sequence) - 1:
patch.setattr(saved, "_write_prepared_scan_finalization", interrupt_publication)
with pytest.raises(OSError, match="Synthetic publication interruption"):
recover_scan_results(workbench_api, workbench_db, scan)
scan.recover()
else:
recover_scan_results(workbench_api, workbench_db, scan)
replayed = preserve_scan_results(workbench_api, workbench_db, scan)
scan.recover()
replayed = scan.preserve()
saved.finalize_scan(scan.scan_dir)
coverage = read_review_state(workbench_db, scan.scan_dir)
if owner == "worker":
@@ -918,7 +865,7 @@ def test_restored_terminal_keeps_surfaces_for_surviving_deferred_work(
def test_source_order_failure_retains_accepted_parent_input(
workbench_api, workbench_db, publication_scan, monkeypatch
workbench_api, publication_scan, monkeypatch
):
from workbench import saved_sources
@@ -965,18 +912,16 @@ def test_source_order_failure_retains_accepted_parent_input(
with monkeypatch.context() as patch:
patch.setattr(saved_sources, "write_scan_local_bytes", fail_order)
fail_scan(workbench_api, workbench_db, scan)
scan.fail()
assert "sealedAt" not in json.loads(manifest.read_text())["scan"]
head.write_text(json.dumps({"checkpoint": abandoned.name, "inputCheckpoint": abandoned.name}))
os.utime(head, ns=(400, 400))
preserve_scan_results(workbench_api, workbench_db, scan)
scan.preserve()
_, findings, _ = saved.finalize_scan(scan_dir)
assert [finding["title"] for finding in findings["findings"]] == [scan.findings[0]["title"]]
def test_headless_canonical_snapshot_failure(
workbench_api, workbench_db, publication_scan, monkeypatch
):
def test_headless_canonical_snapshot_failure(workbench_api, publication_scan, monkeypatch):
from workbench import saved_sources
scan = publication_scan()
@@ -993,7 +938,7 @@ def test_headless_canonical_snapshot_failure(
with monkeypatch.context() as patch:
patch.setattr(saved_sources, "write_scan_local_bytes", fail_snapshot)
fail_scan(workbench_api, workbench_db, scan)
scan.fail()
assert not head.exists()
assert "sealedAt" not in json.loads((scan.scan_dir / "scan-manifest.json").read_text())["scan"]
raw = write_checkpoint(
@@ -1005,7 +950,7 @@ def test_headless_canonical_snapshot_failure(
)
head.write_text(json.dumps({"checkpoint": raw.name, "inputCheckpoint": raw.name}))
(scan.scan_dir / "findings.json").write_text(json.dumps({"findings": []}))
preserve_scan_results(workbench_api, workbench_db, scan)
scan.preserve()
manifest, findings, _ = saved.finalize_scan(scan.scan_dir)
assert [f["title"] for f in findings["findings"]] == [original]
assert "." not in manifest["scan"]["preservedCheckpointHeads"]
@@ -1034,12 +979,10 @@ def test_interrupted_recovery_keeps_frozen_parent_reconciliation(
"UPDATE scans SET status = 'failed', completed_at = started_at WHERE id = ?",
(scan.scan_id,),
)
worker = add_worker(workbench_db, scan, status="canceled")
worker = scan.add_worker(status="canceled")
draft = saved_draft(scan.scan_id, complete=True)
worker.write_text(json.dumps({**draft, "findings": scan.findings}))
os.utime(worker, ns=(100_000, 100_000))
checkpoint = write_checkpoint(scan.scan_dir / "checkpoints", draft)
os.utime(checkpoint, ns=(250_000, 250_000))
write_result_draft(worker, {**draft, "findings": scan.findings}, mtime_ns=100_000)
write_checkpoint(scan.scan_dir / "checkpoints", draft, mtime_ns=250_000)
manifest = scan.scan_dir / "scan-manifest.json"
contents = json.loads(manifest.read_text())
contents["scan"]["complete"] = True
@@ -13,8 +13,10 @@ from workbench_test_support import (
saved_binding,
saved_discovery_worker,
saved_draft,
select_checkpoint,
write_checkpoint,
write_completed_contract,
write_result_draft,
)
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
@@ -26,9 +28,7 @@ def worker(root: Path, name: str, draft: dict):
output = root / "artifacts" / "deep_discovery" / "workers" / name / "output"
(output / "artifacts").mkdir(parents=True)
(output / "artifacts/review.md").write_text(f"{name} source review\n")
result = output / "result.json"
result.write_text(json.dumps(draft))
os.utime(result, ns=(100, 100))
write_result_draft(output / "result.json", draft, mtime_ns=100)
return saved_discovery_worker(output, name, 1)
@@ -104,7 +104,6 @@ def test_partial_root_rejections_close_worker_local_candidates_independently(tmp
)
workers.append(source)
head = tmp_path / "checkpoint-head.json"
for name, observed, pending in [("first", 200, ["Review second."]), ("second", 300, [])]:
rejection = {
"id": name,
@@ -116,8 +115,7 @@ def test_partial_root_rejections_close_worker_local_candidates_independently(tmp
checkpoint = write_checkpoint(
tmp_path / "checkpoints", saved_draft("coverage-scan", surfaces=[rejection])
)
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(observed, observed))
select_checkpoint(tmp_path, checkpoint, mtime_ns=observed)
documents = recover(tmp_path, workers, project=True)
assert [
row["reason"] for row in documents[2]["deferred"] if row["id"] != "scan-stopped"
@@ -196,11 +194,8 @@ def test_partial_parent_without_arrays_retains_closed_worker_surface_and_frozen_
source = worker(tmp_path, "first", closed)
output = Path(source["artifact_dir"])
for modified, draft in [(100, pending), (200, closed)]:
checkpoint = write_checkpoint(output / "checkpoints", draft)
os.utime(checkpoint, ns=(modified, modified))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(200, 200))
checkpoint = write_checkpoint(output / "checkpoints", draft, mtime_ns=modified)
select_checkpoint(output, checkpoint, mtime_ns=200)
os.utime(output / "result.json", ns=(200, 200))
parent = saved_draft("coverage-scan")
parent["coverage"] = {
@@ -233,11 +228,9 @@ def test_finding_only_reducer_preserves_earlier_partial_root_coverage(tmp_path):
question = {"question": "Which routes are public?"}
earlier = saved_draft(scan_id, surfaces=[surface])
earlier["coverage"]["openQuestions"] = [question]
head = tmp_path / "checkpoint-head.json"
for observed, draft in [(100_000, earlier), (200_000, saved_draft(scan_id))]:
checkpoint = write_checkpoint(tmp_path / "checkpoints", draft)
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(observed, observed))
select_checkpoint(tmp_path, checkpoint, mtime_ns=observed)
saved._capture_saved_source(tmp_path, "checkpoint-head.json", scan_id)
finding_path = (
@@ -337,11 +330,8 @@ def test_aggregate_copies_reconcile_once_and_later_worker_closure_removes_pendin
surfaces=[{**surface, "disposition": "no_issue_found"}],
closures=[{"id": "review", "reason": "Review completed."}],
)
checkpoint = write_checkpoint(output / "checkpoints", closed)
os.utime(checkpoint, ns=(300, 300))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(400, 400))
checkpoint = write_checkpoint(output / "checkpoints", closed, mtime_ns=300)
select_checkpoint(output, checkpoint, mtime_ns=400)
originals = {path: path.read_bytes() for path in tmp_path.rglob("*.json")}
documents = recover(tmp_path, [source])
replay = recover(tmp_path, [source], frozen=documents[0]["scan"]["preservedSources"])
@@ -383,8 +373,7 @@ def test_parent_surface_fallback_uses_current_snapshot(
older["coverage"]["surfaces"][0].update(label=old_label, receiptRefs=["artifacts/old.md"])
for name, draft, modified in [("old", older, 50), ("new", current, 100)]:
(output / "artifacts" / f"{name}.md").write_text(f"{name} evidence\n")
checkpoint = write_checkpoint(output / "checkpoints", draft)
os.utime(checkpoint, ns=(modified, modified))
write_checkpoint(output / "checkpoints", draft, mtime_ns=modified)
parent = copy.deepcopy(draft)
parent["coverage"]["surfaces"][0].update(
id="first/api",
@@ -394,12 +383,9 @@ def test_parent_surface_fallback_uses_current_snapshot(
parent["coverage"]["deferred"] = [
{"id": "parent-review", "reason": "Review remains.", "surfaceIds": ["first/api"]}
]
parent_path = write_checkpoint(tmp_path / "checkpoints", parent)
os.utime(parent_path, ns=(modified + 100, modified + 100))
parent_path = write_checkpoint(tmp_path / "checkpoints", parent, mtime_ns=modified + 100)
if selected_parent:
head = tmp_path / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": parent_path.name}))
os.utime(head, ns=(250, 250))
select_checkpoint(tmp_path, parent_path, mtime_ns=250)
else:
write_saved_parent(tmp_path, parent, 200)
template = tmp_path / "template"
@@ -410,11 +396,9 @@ def test_parent_surface_fallback_uses_current_snapshot(
selected = write_checkpoint(
output / "checkpoints",
saved_draft("coverage-scan", complete=complete_worker, findings=[finding]),
mtime_ns=300,
)
os.utime(selected, ns=(300, 300))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
os.utime(head, ns=(400, 400))
select_checkpoint(output, selected, mtime_ns=400)
originals = {path: path.read_bytes() for path in tmp_path.rglob("*") if path.is_file()}
result = recover(tmp_path, [source])
@@ -462,8 +446,7 @@ def test_fallback_receipts_take_precedence_over_historical_repairs(tmp_path, mod
{**writer, "receiptRefs": [f"artifacts/{historical_name}", "artifacts/missing.md"]}
],
)
checkpoint = write_checkpoint(output / "checkpoints", older)
os.utime(checkpoint, ns=(50, 50))
write_checkpoint(output / "checkpoints", older, mtime_ns=50)
parent = copy.deepcopy(draft)
for row in parent["coverage"]["surfaces"]:
row.update(
@@ -483,11 +466,9 @@ def test_fallback_receipts_take_precedence_over_historical_repairs(tmp_path, mod
selected = write_checkpoint(
output / "checkpoints",
saved_draft("coverage-scan", complete=True, surfaces=selected_surfaces),
mtime_ns=300,
)
os.utime(selected, ns=(300, 300))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
os.utime(head, ns=(400, 400))
select_checkpoint(output, selected, mtime_ns=400)
originals = {path: path.read_bytes() for path in tmp_path.rglob("*") if path.is_file()}
warnings = []
result = recover(tmp_path, [source], warnings=warnings)
@@ -526,15 +507,13 @@ def test_parent_only_task_keeps_link_to_recovered_anonymous_surface(
if earlier_identity is not None:
older = copy.deepcopy(draft)
older["coverage"]["surfaces"][-1]["id"] = earlier_identity
checkpoint = write_checkpoint(Path(source["artifact_dir"]) / "checkpoints", older)
os.utime(checkpoint, ns=(50, 50))
checkpoint = write_checkpoint(
Path(source["artifact_dir"]) / "checkpoints", older, mtime_ns=50
)
if selected_checkpoint:
output = Path(source["artifact_dir"])
checkpoint = write_checkpoint(output / "checkpoints", draft)
os.utime(checkpoint, ns=(300, 300))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(400, 400))
checkpoint = write_checkpoint(output / "checkpoints", draft, mtime_ns=300)
select_checkpoint(output, checkpoint, mtime_ns=400)
parent = copy.deepcopy(draft)
parent["coverage"]["surfaces"][-1].update(id=published_id, workerId="first")
if colliding_candidate:
@@ -590,11 +569,8 @@ def test_parent_only_task_keeps_link_to_explicit_worker_surface(
"label"
] = expected_label
output = Path(source["artifact_dir"])
selected_path = write_checkpoint(output / "checkpoints", selected)
os.utime(selected_path, ns=(300, 300))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected_path.name}))
os.utime(head, ns=(400, 400))
selected_path = write_checkpoint(output / "checkpoints", selected, mtime_ns=300)
select_checkpoint(output, selected_path, mtime_ns=400)
originals = {path: path.read_bytes() for path in tmp_path.rglob("*.json")}
result = recover(tmp_path, [source])
@@ -683,11 +659,9 @@ def test_parent_task_retains_surface_omitted_by_selected_worker_checkpoint(
selected = write_checkpoint(
output / "checkpoints",
saved_draft("coverage-scan", complete=True, deferred=selected_tasks),
mtime_ns=300,
)
os.utime(selected, ns=(300, 300))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
os.utime(head, ns=(400, 400))
select_checkpoint(output, selected, mtime_ns=400)
originals = {path: path.read_bytes() for path in tmp_path.rglob("*") if path.is_file()}
result = recover(tmp_path, [source])
@@ -719,15 +693,11 @@ def test_parent_link_follows_updated_terminal_checkpoint(tmp_path, colliding_par
output = Path(source["artifact_dir"])
older = copy.deepcopy(draft)
older["coverage"]["surfaces"][0]["id"] = "restored"
checkpoint = write_checkpoint(output / "checkpoints", older)
os.utime(checkpoint, ns=(50, 50))
checkpoint = write_checkpoint(output / "checkpoints", older, mtime_ns=50)
selected = copy.deepcopy(older)
selected["coverage"]["surfaces"][0]["notes"] = "Updated review."
checkpoint = write_checkpoint(output / "checkpoints", selected)
os.utime(checkpoint, ns=(300, 300))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(400, 400))
checkpoint = write_checkpoint(output / "checkpoints", selected, mtime_ns=300)
select_checkpoint(output, checkpoint, mtime_ns=400)
parent = copy.deepcopy(draft)
parent["coverage"]["surfaces"][0].update(id="first/0", workerId="first")
parent["coverage"]["deferred"] = [
@@ -775,16 +745,14 @@ def test_parent_link_recovery_leaves_malformed_collection_for_existing_finalizer
parent["coverage"]["deferred"] = [
{"id": "parent-review", "reason": "Review remains.", "surfaceIds": ["first/api"]}
]
checkpoint = write_checkpoint(tmp_path / "checkpoints", parent)
os.utime(checkpoint, ns=(150, 150))
write_checkpoint(tmp_path / "checkpoints", parent, mtime_ns=150)
parent["coverage"]["surfaces"] = {"malformed": True}
write_saved_parent(tmp_path, parent, 200)
output = Path(source["artifact_dir"])
selected = write_checkpoint(output / "checkpoints", saved_draft("coverage-scan", complete=True))
os.utime(selected, ns=(300, 300))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
os.utime(head, ns=(400, 400))
selected = write_checkpoint(
output / "checkpoints", saved_draft("coverage-scan", complete=True), mtime_ns=300
)
select_checkpoint(output, selected, mtime_ns=400)
result = saved.merge_saved_results(
tmp_path,
@@ -847,8 +815,7 @@ def test_parent_link_follows_replaced_anonymous_surface(tmp_path, repair_only):
output = Path(source["artifact_dir"])
older = copy.deepcopy(draft)
older["coverage"]["surfaces"][0]["id"] = "restored"
checkpoint = write_checkpoint(output / "checkpoints", older)
os.utime(checkpoint, ns=(50, 50))
checkpoint = write_checkpoint(output / "checkpoints", older, mtime_ns=50)
parent = copy.deepcopy(draft)
parent["coverage"]["surfaces"][0].update(
id="first/0",
@@ -874,11 +841,8 @@ def test_parent_link_follows_replaced_anonymous_surface(tmp_path, repair_only):
],
closures=[] if repair_only else [{"id": "review", "reason": "Worker review completed."}],
)
checkpoint = write_checkpoint(output / "checkpoints", replacement)
os.utime(checkpoint, ns=(300, 300))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(400, 400))
checkpoint = write_checkpoint(output / "checkpoints", replacement, mtime_ns=300)
select_checkpoint(output, checkpoint, mtime_ns=400)
originals = {path: path.read_bytes() for path in tmp_path.rglob("*") if path.is_file()}
frozen = None
for _ in range(2):
@@ -993,11 +957,9 @@ def test_distinct_anonymous_checkpoint_tasks_survive_reconciliation_before_proje
checkpoint = write_checkpoint(
output / "checkpoints",
saved_draft("coverage-scan", deferred=[{"reason": reason}], complete=False),
mtime_ns=index * 100,
)
os.utime(checkpoint, ns=(index * 100, index * 100))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(250, 250))
select_checkpoint(output, checkpoint, mtime_ns=250)
source = saved_discovery_worker(output, "first", 1)
result = recover(tmp_path, [source], project=True)
replay = recover(tmp_path, [source], project=True, frozen=result[0]["scan"]["preservedSources"])
@@ -1122,9 +1084,7 @@ def test_anonymous_worker_receipt_precedes_another_workers_rejection(tmp_path, e
checkpoint = write_checkpoint(
output / "checkpoints", saved_draft("coverage-scan", complete=True, surfaces=[rejection])
)
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(200, 200))
select_checkpoint(output, checkpoint, mtime_ns=200)
_, findings, coverage = recover(tmp_path, [first, second], project=True, warnings=[])
collision = earlier_ref != ref
@@ -1348,8 +1308,7 @@ def test_missing_historical_receipt_does_not_hide_valid_case_variant(tmp_path, r
complete=True,
surfaces=[{**surface, "receiptRefs": ["artifacts/replacement.md"]}],
)
checkpoint = write_checkpoint(output / "checkpoints", current)
os.utime(checkpoint, ns=(300, 300))
write_checkpoint(output / "checkpoints", current, mtime_ns=300)
warnings = []
documents = saved.merge_saved_results(
tmp_path,
@@ -1411,8 +1370,7 @@ def test_superseded_surface_cannot_reserve_historical_receipt(tmp_path, projecte
],
closures=[{"id": "review-reader", "reason": "Reader review complete."}],
)
(output / "result.json").write_text(json.dumps(current))
os.utime(output / "result.json", ns=(300, 300))
write_result_draft(output / "result.json", current, mtime_ns=300)
prefix = archive.relative_to(tmp_path).as_posix() + "/"
if projected_parent:
parent = copy.deepcopy(old)
@@ -1487,17 +1445,19 @@ def test_receipt_repair_preserves_selected_surface_metadata(tmp_path, scenario,
),
]:
checkpoint = write_checkpoint(
output / "checkpoints", saved_draft("coverage-scan", surfaces=[row])
output / "checkpoints",
saved_draft("coverage-scan", surfaces=[row]),
mtime_ns=modified,
)
os.utime(checkpoint, ns=(modified, modified))
missing_path = output / "artifacts/missing.md"
else:
archive = output.parent / "attempts/attempt-01"
(archive / "artifacts").mkdir(parents=True)
(archive / "result.json").write_text(
json.dumps(saved_draft("coverage-scan", complete=True, surfaces=[surface]))
write_result_draft(
archive / "result.json",
saved_draft("coverage-scan", complete=True, surfaces=[surface]),
mtime_ns=100,
)
os.utime(archive / "result.json", ns=(100, 100))
missing_path = archive / "artifacts/missing.md"
accepted = saved_draft(
"coverage-scan",
@@ -1511,10 +1471,8 @@ def test_receipt_repair_preserves_selected_surface_metadata(tmp_path, scenario,
}
],
)
checkpoint = write_checkpoint(output / "checkpoints", accepted)
os.utime(checkpoint, ns=(200, 200))
(output / "checkpoint-head.json").write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(output / "checkpoint-head.json", ns=(250, 250))
checkpoint = write_checkpoint(output / "checkpoints", accepted, mtime_ns=200)
select_checkpoint(output, checkpoint, mtime_ns=250)
(output / "result.json").write_text(json.dumps(accepted))
pending = saved_draft(
"coverage-scan",
@@ -1527,8 +1485,7 @@ def test_receipt_repair_preserves_selected_surface_metadata(tmp_path, scenario,
}
],
)
checkpoint = write_checkpoint(output / "checkpoints", pending)
os.utime(checkpoint, ns=(400, 400))
checkpoint = write_checkpoint(output / "checkpoints", pending, mtime_ns=400)
source["attempt"] = 2
os.utime(output / "result.json", ns=(300, 300))
if not missing:
@@ -1575,30 +1532,28 @@ def test_receipt_repair_does_not_promote_unselected_checkpoint_evidence(
output = Path(source["artifact_dir"])
if accepted_receipt_exists:
(output / "artifacts/accepted.md").write_text("Accepted receipt.\n")
historical = write_checkpoint(
write_checkpoint(
output / "checkpoints",
saved_draft(
"coverage-scan",
complete=True,
surfaces=[{**surface, "receiptRefs": ["artifacts/missing.md"]}],
),
mtime_ns=100,
)
os.utime(historical, ns=(100, 100))
selected = write_checkpoint(output / "checkpoints", accepted)
os.utime(selected, ns=(200, 200))
(output / "checkpoint-head.json").write_text(json.dumps({"checkpoint": selected.name}))
os.utime(output / "checkpoint-head.json", ns=(250, 250))
selected = write_checkpoint(output / "checkpoints", accepted, mtime_ns=200)
select_checkpoint(output, selected, mtime_ns=250)
os.utime(output / "result.json", ns=(300, 300))
(output / "artifacts/unselected.md").write_text("Unselected interrupted observation.\n")
pending = write_checkpoint(
write_checkpoint(
output / "checkpoints",
saved_draft(
"coverage-scan",
complete=False,
surfaces=[{**surface, "receiptRefs": ["artifacts/unselected.md"]}],
),
mtime_ns=400,
)
os.utime(pending, ns=(400, 400))
originals = {path: path.read_bytes() for path in output.rglob("*") if path.is_file()}
frozen = None
for _ in range(2):
@@ -1659,10 +1614,8 @@ def test_unselected_receipt_spelling_cannot_replace_accepted_evidence(
("distinct.md", "Independent receipt bytes."),
):
(output / "artifacts" / name).write_text(text)
selected = write_checkpoint(output / "checkpoints", accepted)
os.utime(selected, ns=(200, 200))
(output / "checkpoint-head.json").write_text(json.dumps({"checkpoint": selected.name}))
os.utime(output / "checkpoint-head.json", ns=(250, 250))
selected = write_checkpoint(output / "checkpoints", accepted, mtime_ns=200)
select_checkpoint(output, selected, mtime_ns=250)
os.utime(output / "result.json", ns=(300, 300))
if checkpoint != "absent":
name = {
@@ -1670,14 +1623,14 @@ def test_unselected_receipt_spelling_cannot_replace_accepted_evidence(
"conflicting": unselected_name,
"distinct": "distinct.md",
}[checkpoint]
pending = write_checkpoint(
write_checkpoint(
output / "checkpoints",
saved_draft(
"coverage-scan",
surfaces=[{**surface, "receiptRefs": [f"artifacts/{name}"]}],
),
mtime_ns=400,
)
os.utime(pending, ns=(400, 400))
originals = {path: path.read_bytes() for path in tmp_path.rglob("*") if path.is_file()}
documents = recover(tmp_path, [source], project=True)
replay = recover(
@@ -1720,17 +1673,15 @@ def test_non_emitted_repair_cannot_reserve_another_surfaces_receipt(tmp_path, un
"coverage-scan", complete=True, surfaces=[surface("writer", ["Review.md", "missing.md"])]
)
for modified, draft in [(100, history), (200, accepted)]:
checkpoint = write_checkpoint(output / "checkpoints", draft)
os.utime(checkpoint, ns=(modified, modified))
(output / "checkpoint-head.json").write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(output / "checkpoint-head.json", ns=(250, 250))
checkpoint = write_checkpoint(output / "checkpoints", draft, mtime_ns=modified)
select_checkpoint(output, checkpoint, mtime_ns=250)
os.utime(output / "result.json", ns=(300, 300))
if unselected:
checkpoint = write_checkpoint(
output / "checkpoints",
saved_draft("coverage-scan", surfaces=[surface("reader", ["review.md"])]),
mtime_ns=400,
)
os.utime(checkpoint, ns=(400, 400))
originals = {path: path.read_bytes() for path in tmp_path.rglob("*") if path.is_file()}
warnings = []
documents = saved.merge_saved_results(
@@ -1823,10 +1774,8 @@ def test_only_recoverable_surface_metadata_reserves_receipt_spelling(tmp_path, r
],
)
for modified, draft in [(100, history), (200, accepted)]:
checkpoint = write_checkpoint(output / "checkpoints", draft)
os.utime(checkpoint, ns=(modified, modified))
(output / "checkpoint-head.json").write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(output / "checkpoint-head.json", ns=(250, 250))
checkpoint = write_checkpoint(output / "checkpoints", draft, mtime_ns=modified)
select_checkpoint(output, checkpoint, mtime_ns=250)
os.utime(output / "result.json", ns=(300, 300))
originals = {p: p.read_bytes() for p in output.rglob("*") if p.is_file()}
warnings = []
@@ -1883,3 +1832,32 @@ def test_only_recoverable_surface_metadata_reserves_receipt_spelling(tmp_path, r
)
assert replay[2] == documents[2]
assert all(path.read_bytes() == content for path, content in originals.items())
def test_reducer_relinks_its_deferred_task_when_reusing_a_worker_result(tmp_path):
upstream = {"id": "route", "label": "Upstream", "disposition": "no_issue_found"}
previous = {**upstream, "id": "upstream/route", "workerId": "upstream"}
published = {**previous, "id": "local/upstream/route", "workerId": "local"}
task = {"id": "review", "reason": "Pending review", "surfaceIds": [published["id"]]}
first = worker(tmp_path, "upstream", saved_draft("coverage-scan", surfaces=[upstream]))
local = worker(
tmp_path,
"local",
saved_draft(
"coverage-scan", complete=True, surfaces=[previous, published], deferred=[task]
),
)
result = str(Path(local["artifact_dir"]) / "result.json")
local.update(status="succeeded", result_manifest_path=result)
reducer = worker(tmp_path, "reducer", saved_draft("coverage-scan"))
reducer.update(kind="dedup", status="succeeded", completed_at="", result_manifest_path=result)
workers = [first, local, reducer]
docs = recover(tmp_path, workers, project=True)
replay = recover(tmp_path, workers, project=True, frozen=docs[0]["scan"]["preservedSources"])
for coverage in (docs[2], replay[2]):
reducer_task = next(row for row in coverage["deferred"] if row["id"] == task["id"])
(surface_id,) = reducer_task["surfaceIds"]
surface = next(row for row in coverage["surfaces"] if row["id"] == surface_id)
assert surface["workerId"] == previous["workerId"]
assert surface["provenance"]["workerId"] == local["id"]
assert surface["provenance"]["sourceId"] == previous["id"]
@@ -21,6 +21,7 @@ from workbench_test_support import (
read_review_state,
run_workbench,
saved_draft,
select_checkpoint,
worker_paths,
write_checkpoint,
)
@@ -71,7 +72,7 @@ def deadline_fixture(
)
draft["threatModel"] = {"summary": "Synthetic worker model."}
checkpoint = write_checkpoint(output / "checkpoints", draft)
(output / "checkpoint-head.json").write_text(json.dumps({"checkpoint": checkpoint.name}))
select_checkpoint(output, checkpoint)
run_workbench(state, *args, "--status", "canceled", environment=environment)
artifacts = directory / "artifacts/02_discovery"
artifacts.mkdir(parents=True, exist_ok=True)
@@ -11,7 +11,7 @@ from types import SimpleNamespace
import pytest
from test_deep_coverage_recovery import worker
from test_workbench_standard_deep_results import write_saved_parent
from workbench_test_support import saved_binding, saved_draft, write_checkpoint
from workbench_test_support import saved_binding, saved_draft, select_checkpoint, write_checkpoint
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
import finalize_scan_contract as finalizer
@@ -94,8 +94,7 @@ def test_deadline_rollback_does_not_reintroduce_a_later_rejected_worker_finding(
worker_bytes = worker_checkpoint.read_bytes()
previous = write_checkpoint(tmp_path / "checkpoints", saved_draft(scan_id))
previous_bytes = previous.read_bytes()
head = tmp_path / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": previous.name}))
head = select_checkpoint(tmp_path, previous)
original_head = head.read_bytes()
binding, db, scan = publication_context(tmp_path, scan_id)
@@ -161,11 +160,8 @@ def test_deadline_rollback_preserves_parent_observation_order(
older, newer = (pending, closed) if newer_source == "canonical" else (closed, pending)
older["threatModel"] = {"summary": "The earlier model."}
newer["threatModel"] = {"summary": "The current model."}
selected = write_checkpoint(tmp_path / "checkpoints", older)
os.utime(selected, ns=(100, 100))
head = tmp_path / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
os.utime(head, ns=(100, 100))
selected = write_checkpoint(tmp_path / "checkpoints", older, mtime_ns=100)
head = select_checkpoint(tmp_path, selected, mtime_ns=100)
canonical = newer if newer_source == "canonical" else older
modified = 200 if newer_source == "canonical" else 100
write_saved_parent(tmp_path, canonical, modified)
@@ -176,8 +172,7 @@ def test_deadline_rollback_preserves_parent_observation_order(
for name in ("scan-manifest.json", "findings.json", "coverage.json"):
os.utime(tmp_path / name, ns=(modified, modified))
if newer_source == "unselected-checkpoint":
unselected = write_checkpoint(tmp_path / "checkpoints", newer)
os.utime(unselected, ns=(200, 200))
write_checkpoint(tmp_path / "checkpoints", newer, mtime_ns=200)
binding, db, scan = publication_context(tmp_path, scan_id)
class Connection:
@@ -6,11 +6,16 @@ import os
import pytest
from test_deep_scan_deadline_recovery import worker_finding
from test_deep_scan_stop_conditions import canceled_discovery_output, complete, finish
from test_deep_scan_stop_conditions import canceled_discovery_output, finish
from test_deep_scan_stop_conditions import deadline_scan as deadline_scan
from test_deep_scan_stop_conditions import publication_scan as publication_scan
from test_deep_scan_stop_conditions import saturated_scan as saturated_scan
from workbench_test_support import read_review_state, saved_draft, write_checkpoint
from workbench_test_support import (
read_review_state,
saved_draft,
select_checkpoint,
write_checkpoint,
)
@pytest.mark.parametrize("source", ["result", "checkpoint", "archived-checkpoint"])
@@ -43,8 +48,8 @@ def test_deadline_requires_boolean_completion_before_superseding_worker_history(
findings=[earlier, rejected],
deferred=[{"id": "review", "reason": "Review remains."}],
),
mtime_ns=100,
)
os.utime(checkpoint, ns=(100, 100))
sibling = worker_finding(scan, "latest-valid-sibling")
latest = saved_draft(
scan.scan_id,
@@ -68,14 +73,12 @@ def test_deadline_requires_boolean_completion_before_superseding_worker_history(
result.write_text(json.dumps(latest))
else:
result = write_checkpoint(output / "checkpoints", latest)
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": result.name}))
os.utime(head, ns=(300, 300))
select_checkpoint(output, result, mtime_ns=300)
os.utime(result, ns=(200, 200))
original = {path: path.read_bytes() for path in (checkpoint, result)}
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
terminal = marker is True or marker == "omitted"
invalid = not isinstance(marker, bool) and marker != "omitted"
@@ -131,8 +134,8 @@ def test_deadline_validates_each_recovered_finding_against_the_completed_contrac
{"id": "finished", "reason": "Separate review remains."},
],
),
mtime_ns=100,
)
os.utime(checkpoint, ns=(100, 100))
sibling = worker_finding(scan, "valid-worker-sibling")
malformed = worker_finding(scan, "malformed-worker-finding")
malformed["provenance"]["candidateId"] = "malformed-worker-finding"
@@ -166,24 +169,19 @@ def test_deadline_validates_each_recovered_finding_against_the_completed_contrac
)
if source == "checkpoint":
result = write_checkpoint(output / "checkpoints", latest)
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": result.name}))
os.utime(head, ns=(300, 300))
select_checkpoint(output, result, mtime_ns=300)
else:
result = output / "result.json"
result.write_text(json.dumps(latest))
os.utime(result, ns=(200, 200))
original = {path: path.read_bytes() for path in (checkpoint, result)}
if source == "archived-result":
selected = write_checkpoint(output / "checkpoints", latest)
os.utime(selected, ns=(200, 200))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
os.utime(head, ns=(300, 300))
selected = write_checkpoint(output / "checkpoints", latest, mtime_ns=200)
select_checkpoint(output, selected, mtime_ns=300)
original[selected] = selected.read_bytes()
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
findings = json.loads((scan.scan_dir / "findings.json").read_text())["findings"]
assert {finding["title"] for finding in findings} == {
@@ -228,7 +226,7 @@ def test_deadline_recovers_optional_worker_model_without_losing_findings(
original = checkpoint.read_bytes()
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
assert len(json.loads((scan.scan_dir / "findings.json").read_text())["findings"]) == 2
manifest = json.loads((scan.scan_dir / "scan-manifest.json").read_text())["scan"]
@@ -302,7 +300,7 @@ def test_deadline_applies_existing_nonblank_surface_label_contract(
original = checkpoint.read_bytes()
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
assert len(json.loads((scan.scan_dir / "findings.json").read_text())["findings"]) == 2
coverage = read_review_state(workbench_db, scan.scan_dir)
@@ -345,19 +343,18 @@ def test_deadline_applies_existing_unicode_contract_per_worker_record(
draft["coverage"][field] = [{"id": "review", "reason": text}]
if field == "resolvedDeferred":
draft["complete"] = True
previous = write_checkpoint(
write_checkpoint(
output / "checkpoints",
saved_draft(scan.scan_id, deferred=[{"id": "review", "reason": "Review pending."}]),
mtime_ns=100,
)
os.utime(previous, ns=(100, 100))
checkpoint = write_checkpoint(output / "checkpoints", draft)
os.utime(checkpoint, ns=(200, 200))
checkpoint = write_checkpoint(output / "checkpoints", draft, mtime_ns=200)
if field == "resolvedDeferred":
(output / "checkpoint-head.json").write_text(json.dumps({"checkpoint": checkpoint.name}))
select_checkpoint(output, checkpoint)
original = checkpoint.read_bytes()
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
findings = json.loads((scan.scan_dir / "findings.json").read_text())["findings"]
assert len(findings) == (1 if malformed and field == "finding" else 2)
@@ -391,8 +388,8 @@ def test_deadline_recovers_historical_closure_text_without_losing_a_valid_siblin
{"id": "sibling", "reason": "Valid sibling review pending."},
],
),
mtime_ns=100,
)
os.utime(previous, ns=(100, 100))
draft = saved_draft(
scan.scan_id,
complete=True,
@@ -404,14 +401,13 @@ def test_deadline_recovers_historical_closure_text_without_losing_a_valid_siblin
checkpoint = write_checkpoint(output / "checkpoints", draft)
result = output / "result.json"
result.write_text(json.dumps(draft))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
head = select_checkpoint(output, checkpoint)
for path in (checkpoint, result, head):
os.utime(path, ns=(200, 200))
original = {path: path.read_bytes() for path in (previous, checkpoint, result)}
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
invalid = not reason.strip()
assert completed["progress"]["status"] == "complete"
@@ -492,8 +488,8 @@ def test_malformed_terminal_coverage_preserves_only_earlier_coverage(
{"id": "finished", "reason": "Separate review remains."},
],
),
mtime_ns=100,
)
os.utime(checkpoint, ns=(100, 100))
invalid_surface = copy.deepcopy(surface)
if malformed == "surface":
invalid_surface.pop("label")
@@ -526,7 +522,7 @@ def test_malformed_terminal_coverage_preserves_only_earlier_coverage(
)
if selected_head:
result = write_checkpoint(output / "checkpoints", terminal)
(output / "checkpoint-head.json").write_text(json.dumps({"checkpoint": result.name}))
select_checkpoint(output, result)
else:
result = output / "result.json"
result.write_text(json.dumps(terminal))
@@ -534,7 +530,7 @@ def test_malformed_terminal_coverage_preserves_only_earlier_coverage(
original = {path: path.read_bytes() for path in (checkpoint, result)}
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
complete(workbench_api, workbench_db, scan)
scan.complete()
findings = json.loads((scan.scan_dir / "findings.json").read_text())["findings"]
assert any(row["title"] == finding["title"] for row in findings) == terminal_findings
@@ -579,7 +575,7 @@ def test_optional_export_failure_does_not_block_deadline(
)
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
assert completed["progress"]["status"] == "complete"
assert "automatic SARIF export failed" in capsys.readouterr().err
@@ -588,14 +584,14 @@ def test_optional_export_failure_does_not_block_deadline(
def test_standard_parent_closure_preserves_unrelated_task_without_id(
workbench_api, workbench_db, publication_scan
workbench_db, publication_scan
):
scan = publication_scan(mode="standard")
scan.coverage["resolvedDeferred"] = [{"id": "finished", "reason": "Review completed."}]
scan.coverage["deferred"] = [{"reason": "Unrelated pending review."}]
(scan.scan_dir / "coverage.json").write_text(json.dumps(scan.coverage))
complete(workbench_api, workbench_db, scan)
scan.complete()
coverage = read_review_state(workbench_db, scan.scan_dir)
assert len(coverage["deferred"]) == 1
@@ -5,13 +5,11 @@ import hashlib
import json
import os
import sqlite3
import traceback
import pytest
from deep_deadline_crash import COMMIT_EXIT, finish_until_commit
from deep_deadline_crash import interrupt_finish_before_commit
from test_deep_scan_stop_conditions import (
canceled_discovery_output,
complete,
finish,
)
from test_deep_scan_stop_conditions import (
@@ -23,7 +21,13 @@ from test_deep_scan_stop_conditions import (
from test_deep_scan_stop_conditions import (
saturated_scan as saturated_scan,
)
from workbench_test_support import read_review_state, saved_draft, write_checkpoint
from workbench_test_support import (
read_review_state,
saved_draft,
select_checkpoint,
write_checkpoint,
write_result_draft,
)
def worker_finding(scan, anchor):
@@ -62,7 +66,7 @@ def test_deadline_completion_preserves_existing_tasks_and_recovered_findings(
original_checkpoint = checkpoint.read_bytes()
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
assert completed["progress"]["status"] == "complete"
assert (
@@ -100,16 +104,33 @@ def test_deadline_completion_preserves_existing_tasks_and_recovered_findings(
assert checkpoint.read_bytes() == original_checkpoint
def interrupt_finish_before_commit(workbench_api, database, scan):
child = os.fork()
if child == 0:
try:
finish_until_commit(workbench_api["deep_scan"], database, scan.scan_id, scan.scan_dir)
except BaseException:
traceback.print_exc()
os._exit(1)
_, status = os.waitpid(child, 0)
assert os.waitstatus_to_exitcode(status) == COMMIT_EXIT
@pytest.fixture
def finish_after_crashes(workbench_api, workbench_db, deadline_scan, tmp_path):
def run():
scan = deadline_scan
database = tmp_path / "crash-recovery.db"
with sqlite3.connect(database) as connection:
workbench_db.backup(connection)
publications = []
for hash_seed in (1, 17, 83):
interrupt_finish_before_commit(database, scan, hash_seed)
publications.append(read_review_state(workbench_db, scan.scan_dir))
with sqlite3.connect(database) as connection:
status = connection.execute(
"SELECT status FROM deep_scan_runs WHERE scan_id = ?", (scan.scan_id,)
).fetchone()[0]
assert status == "running"
with sqlite3.connect(database) as connection:
connection.row_factory = sqlite3.Row
finish(workbench_api, connection, scan, terminal_reason="capped")
completed = scan.complete(connection)
coverage = read_review_state(workbench_db, scan.scan_dir)
assert completed["progress"]["status"] == "complete"
assert all(publication == coverage for publication in publications)
return completed, coverage
return run
def test_discarded_worker_finding_leaves_its_review_pending(
@@ -145,7 +166,7 @@ def test_discarded_worker_finding_leaves_its_review_pending(
original = checkpoint.read_bytes()
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
coverage = read_review_state(workbench_db, scan.scan_dir)
assert canonical in coverage["surfaces"]
@@ -176,8 +197,8 @@ def test_terminal_worker_authority_requires_valid_findings(
findings=[previous],
deferred=[{"id": "review", "reason": "Review pending."}],
),
mtime_ns=100,
)
os.utime(checkpoint, ns=(100, 100))
sibling = worker_finding(scan, "valid-terminal-sibling")
terminal_findings = [sibling]
if invalid_terminal:
@@ -185,21 +206,20 @@ def test_terminal_worker_authority_requires_valid_findings(
invalid.pop("remediation")
terminal_findings.append(invalid)
result = output / "result.json"
result.write_text(
json.dumps(
saved_draft(
scan.scan_id,
complete=True,
findings=terminal_findings,
closures=[{"id": "review", "reason": "Review completed."}],
)
)
write_result_draft(
result,
saved_draft(
scan.scan_id,
complete=True,
findings=terminal_findings,
closures=[{"id": "review", "reason": "Review completed."}],
),
mtime_ns=200,
)
os.utime(result, ns=(200, 200))
original = {path: path.read_bytes() for path in (checkpoint, result)}
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
complete(workbench_api, workbench_db, scan)
scan.complete()
findings = json.loads((scan.scan_dir / "findings.json").read_text())["findings"]
assert any(row["title"] == previous["title"] for row in findings) == invalid_terminal
@@ -216,10 +236,11 @@ def test_malformed_worker_finding_preserves_a_valid_sibling_outcome(
worker_id, output = canceled_discovery_output(workbench_db, scan)
earlier = worker_finding(scan, "rejected-candidate")
earlier["provenance"]["candidateId"] = "candidate"
checkpoint = write_checkpoint(
output / "checkpoints", saved_draft(scan.scan_id, findings=[earlier])
write_checkpoint(
output / "checkpoints",
saved_draft(scan.scan_id, findings=[earlier]),
mtime_ns=100,
)
os.utime(checkpoint, ns=(100, 100))
invalid = worker_finding(scan, "malformed-sibling")
invalid.pop("remediation")
outcome = {
@@ -229,14 +250,14 @@ def test_malformed_worker_finding_preserves_a_valid_sibling_outcome(
"disposition": "rejected",
"receiptRefs": [],
}
result = output / "result.json"
result.write_text(
json.dumps(saved_draft(scan.scan_id, complete=True, findings=[invalid], surfaces=[outcome]))
write_result_draft(
output / "result.json",
saved_draft(scan.scan_id, complete=True, findings=[invalid], surfaces=[outcome]),
mtime_ns=200,
)
os.utime(result, ns=(200, 200))
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
complete(workbench_api, workbench_db, scan)
scan.complete()
findings = json.loads((scan.scan_dir / "findings.json").read_text())["findings"]
assert all(row["title"] != earlier["title"] for row in findings)
@@ -314,7 +335,7 @@ def test_worker_writeups_remain_bound_to_their_source_directory(
originals[checkpoint] = checkpoint.read_bytes()
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
findings = json.loads((scan.scan_dir / "findings.json").read_text())["findings"]
assert len(findings) == 3
@@ -336,9 +357,6 @@ def test_worker_writeups_remain_bound_to_their_source_directory(
assert {path: path.read_bytes() for path in originals} == originals
@pytest.mark.skipif(
not hasattr(os, "fork"), reason="Crash boundary uses a forked workbench process."
)
@pytest.mark.parametrize(
("colliding_ids", "parent_closure", "reviewed", "worker_like_id"),
[
@@ -404,7 +422,7 @@ def test_deadline_recovery_is_idempotent_after_crash_before_commit(
),
)
connection.close()
interrupt_finish_before_commit(workbench_api, database, scan)
interrupt_finish_before_commit(database, scan, 1)
before = read_review_state(workbench_db, scan.scan_dir)
findings_before = json.loads((scan.scan_dir / "findings.json").read_text())
assert len([row for row in before["surfaces"] if row.get("workerId") == worker_id]) == len(
@@ -422,7 +440,7 @@ def test_deadline_recovery_is_idempotent_after_crash_before_commit(
== "running"
)
finish(workbench_api, connection, scan, terminal_reason="capped")
complete(workbench_api, connection, scan)
scan.complete(connection)
after = read_review_state(workbench_db, scan.scan_dir)
findings_after = json.loads((scan.scan_dir / "findings.json").read_text())
@@ -435,13 +453,10 @@ def test_deadline_recovery_is_idempotent_after_crash_before_commit(
assert after == before
@pytest.mark.skipif(
not hasattr(os, "fork"), reason="Crash boundary uses a forked workbench process."
)
@pytest.mark.parametrize("earlier_checkpoint_first", [False, True])
@pytest.mark.parametrize("colliding_ids", [False, True])
def test_deadline_rejection_history_is_stable_across_repeated_crashes(
workbench_api, workbench_db, deadline_scan, tmp_path, earlier_checkpoint_first, colliding_ids
workbench_db, deadline_scan, finish_after_crashes, earlier_checkpoint_first, colliding_ids
):
scan = deadline_scan
worker_id, output = canceled_discovery_output(workbench_db, scan)
@@ -475,31 +490,10 @@ def test_deadline_rejection_history_is_stable_across_repeated_crashes(
assert (old_checkpoint.name < checkpoint.name) == earlier_checkpoint_first
os.utime(old_checkpoint, ns=(100, 100))
os.utime(checkpoint, ns=(200, 200))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
head = select_checkpoint(output, checkpoint)
(output / "result.json").unlink(missing_ok=True)
originals = {path: path.read_bytes() for path in (old_checkpoint, checkpoint, head)}
database = tmp_path / "repeated-crash.db"
with sqlite3.connect(database) as connection:
workbench_db.backup(connection)
publications = []
for _ in range(3):
interrupt_finish_before_commit(workbench_api, database, scan)
publications.append(read_review_state(workbench_db, scan.scan_dir))
with sqlite3.connect(database) as connection:
assert (
connection.execute(
"SELECT status FROM deep_scan_runs WHERE scan_id = ?", (scan.scan_id,)
).fetchone()[0]
== "running"
)
with sqlite3.connect(database) as connection:
connection.row_factory = sqlite3.Row
finish(workbench_api, connection, scan, terminal_reason="capped")
complete(workbench_api, connection, scan)
coverage = read_review_state(workbench_db, scan.scan_dir)
assert all(publication == coverage for publication in publications)
_, coverage = finish_after_crashes()
surfaces = [row for row in coverage["surfaces"] if row.get("workerId") == worker_id]
assert {row["label"] for row in surfaces} == {row["label"] for row in outcomes}
assert len(surfaces) == len({row["id"] for row in surfaces}) == len(outcomes)
@@ -2,13 +2,10 @@ from __future__ import annotations
import json
import os
import sqlite3
import subprocess
import sys
import deep_deadline_crash
import pytest
from test_deep_scan_stop_conditions import canceled_discovery_output, complete, finish
from test_deep_scan_deadline_recovery import finish_after_crashes as finish_after_crashes
from test_deep_scan_stop_conditions import canceled_discovery_output, finish
from test_deep_scan_stop_conditions import deadline_scan as deadline_scan
from test_deep_scan_stop_conditions import publication_scan as publication_scan
from test_deep_scan_stop_conditions import saturated_scan as saturated_scan
@@ -18,6 +15,7 @@ from workbench_test_support import (
saved_binding,
saved_discovery_worker,
saved_draft,
select_checkpoint,
write_checkpoint,
)
@@ -30,28 +28,11 @@ def pending(identity, reason, surface_id="entry"):
return {"id": identity, "reason": reason, "surfaceIds": [surface_id]}
def interrupt_in_fresh_python(database, scan, hash_seed):
result = subprocess.run(
[
sys.executable,
"-B",
deep_deadline_crash.__file__,
str(database),
scan.scan_id,
str(scan.scan_dir),
],
env={**os.environ, "PYTHONHASHSEED": str(hash_seed)},
capture_output=True,
text=True,
)
assert result.returncode == deep_deadline_crash.COMMIT_EXIT, result.stdout + result.stderr
@pytest.mark.parametrize(
"parent_collision", [pytest.param(False, marks=pytest.mark.cross_platform), True]
)
def test_deadline_surface_links_follow_sources_across_repeated_crashes(
workbench_api, workbench_db, deadline_scan, tmp_path, parent_collision
workbench_db, deadline_scan, finish_after_crashes, parent_collision
):
scan = deadline_scan
worker_id, output = canceled_discovery_output(workbench_db, scan, attempt=2)
@@ -69,8 +50,8 @@ def test_deadline_surface_links_follow_sources_across_repeated_crashes(
surfaces=[surface(label)],
deferred=[pending(f"{label}-review", f"Review {label}."), shared],
),
mtime_ns=index * 100,
)
os.utime(checkpoint, ns=(index * 100, index * 100))
checkpoints.append(checkpoint)
canonical_id = f"{worker_id}/entry" if parent_collision else "parent-entry"
canonical_surface = surface("Canonical parent", canonical_id)
@@ -78,29 +59,7 @@ def test_deadline_surface_links_follow_sources_across_repeated_crashes(
scan.coverage.update(surfaces=[canonical_surface], deferred=[canonical_pending])
(scan.scan_dir / "coverage.json").write_text(json.dumps(scan.coverage))
originals = {path: path.read_bytes() for path in checkpoints}
database = tmp_path / "surface-links.db"
with sqlite3.connect(database) as connection:
workbench_db.backup(connection)
publications = []
for hash_seed in (1, 17, 83):
interrupt_in_fresh_python(database, scan, hash_seed)
publications.append(read_review_state(workbench_db, scan.scan_dir))
with sqlite3.connect(database) as connection:
assert (
connection.execute(
"SELECT status FROM deep_scan_runs WHERE scan_id = ?", (scan.scan_id,)
).fetchone()[0]
== "running"
)
with sqlite3.connect(database) as connection:
connection.row_factory = sqlite3.Row
finish(workbench_api, connection, scan, terminal_reason="capped")
completed = complete(workbench_api, connection, scan)
coverage = read_review_state(workbench_db, scan.scan_dir)
assert completed["progress"]["status"] == "complete"
assert all(publication == coverage for publication in publications)
_, coverage = finish_after_crashes()
assert canonical_surface in coverage["surfaces"]
assert canonical_pending in coverage["deferred"]
surfaces = [row for row in coverage["surfaces"] if row.get("workerId") == worker_id]
@@ -141,7 +100,7 @@ def test_deadline_retains_all_targets_of_one_legacy_surface_id(
original = checkpoint.read_bytes()
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
complete(workbench_api, workbench_db, scan)
scan.complete()
coverage = read_review_state(workbench_db, scan.scan_dir)
surfaces = [row for row in coverage["surfaces"] if row["label"] in {"download", "upload"}]
@@ -171,7 +130,7 @@ def test_deadline_deferred_only_checkpoint_keeps_prior_surface_link(
originals = {path: path.read_bytes() for path in (earlier, current)}
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
complete(workbench_api, workbench_db, scan)
scan.complete()
coverage = read_review_state(workbench_db, scan.scan_dir)
retained = next(row for row in coverage["surfaces"] if row["label"] == "Earlier review")
@@ -208,15 +167,13 @@ def test_deadline_reopened_generic_surface_copy_retains_its_link(
]
originals = {}
for index, draft in enumerate(drafts, start=1):
checkpoint = write_checkpoint(output / "checkpoints", draft)
os.utime(checkpoint, ns=(index * 100, index * 100))
checkpoint = write_checkpoint(output / "checkpoints", draft, mtime_ns=index * 100)
originals[checkpoint] = checkpoint.read_bytes()
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
head = select_checkpoint(output, checkpoint)
originals[head] = head.read_bytes()
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
complete(workbench_api, workbench_db, scan)
scan.complete()
coverage = read_review_state(workbench_db, scan.scan_dir)
retained = [row for row in coverage["surfaces"] if row.get("workerId") == worker_id]
@@ -260,7 +217,7 @@ def test_stopped_recovery_preserves_source_link_union(workbench_api, tmp_path):
@pytest.mark.parametrize("changed_task", [False, True], ids=["copied-task", "updated-task"])
def test_deadline_retains_equal_task_origins_from_selected_worker_result(
workbench_api, workbench_db, deadline_scan, tmp_path, changed_task
workbench_db, deadline_scan, finish_after_crashes, changed_task
):
scan = deadline_scan
worker_id, output = canceled_discovery_output(workbench_db, scan, attempt=2)
@@ -269,11 +226,8 @@ def test_deadline_retains_equal_task_origins_from_selected_worker_result(
archived_draft = saved_draft(
scan.scan_id, surfaces=[surface("download")], deferred=[previous_task]
)
checkpoint = write_checkpoint(archived / "checkpoints", archived_draft)
os.utime(checkpoint, ns=(100, 100))
archived_head = archived / "checkpoint-head.json"
archived_head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(archived_head, ns=(110, 110))
checkpoint = write_checkpoint(archived / "checkpoints", archived_draft, mtime_ns=100)
select_checkpoint(archived, checkpoint, mtime_ns=110)
archived_result = archived / "result.json"
archived_result.write_bytes(checkpoint.read_bytes())
os.utime(archived_result, ns=(120, 120))
@@ -286,36 +240,18 @@ def test_deadline_retains_equal_task_origins_from_selected_worker_result(
surfaces=[surface("upload")],
deferred=[current_task, retained_task] if changed_task else [current_task],
)
raw_checkpoint = write_checkpoint(output / "checkpoints", incoming)
os.utime(raw_checkpoint, ns=(200, 200))
write_checkpoint(output / "checkpoints", incoming, mtime_ns=200)
# The writer preserves the old pending task while publishing its latest surface.
merged = saved_draft(
scan.scan_id, surfaces=[surface("upload")], deferred=[current_task, retained_task]
)
selected = write_checkpoint(output / "checkpoints", merged)
os.utime(selected, ns=(210, 210))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
os.utime(head, ns=(220, 220))
selected = write_checkpoint(output / "checkpoints", merged, mtime_ns=210)
select_checkpoint(output, selected, mtime_ns=220)
result = output / "result.json"
result.write_bytes(selected.read_bytes())
os.utime(result, ns=(230, 230))
originals = {path: path.read_bytes() for path in output.parent.rglob("*") if path.is_file()}
database = tmp_path / "selected-result.db"
with sqlite3.connect(database) as connection:
workbench_db.backup(connection)
publications = []
for hash_seed in (1, 17, 83):
interrupt_in_fresh_python(database, scan, hash_seed)
publications.append(read_review_state(workbench_db, scan.scan_dir))
with sqlite3.connect(database) as connection:
connection.row_factory = sqlite3.Row
finish(workbench_api, connection, scan, terminal_reason="capped")
complete(workbench_api, connection, scan)
coverage = read_review_state(workbench_db, scan.scan_dir)
assert all(publication == coverage for publication in publications)
_, coverage = finish_after_crashes()
surfaces = [row for row in coverage["surfaces"] if row.get("workerId") == worker_id]
assert {row["label"] for row in surfaces} == {"download", "upload"}
upload = next(row for row in surfaces if row["label"] == "upload")
@@ -334,7 +270,7 @@ def test_deadline_retains_equal_task_origins_from_selected_worker_result(
"selected_result", [False, True], ids=["raw-checkpoint", "selected-result"]
)
def test_deadline_dropped_legacy_surface_does_not_rebind_its_pending_task(
workbench_api, workbench_db, deadline_scan, tmp_path, selected_result
workbench_db, deadline_scan, finish_after_crashes, selected_result
):
scan = deadline_scan
worker_id, output = canceled_discovery_output(workbench_db, scan, attempt=2)
@@ -343,8 +279,8 @@ def test_deadline_dropped_legacy_surface_does_not_rebind_its_pending_task(
archived_checkpoint = write_checkpoint(
archived / "checkpoints",
saved_draft(scan.scan_id, surfaces=[surface("download")], deferred=[download_task]),
mtime_ns=100,
)
os.utime(archived_checkpoint, ns=(100, 100))
archived_result = archived / "result.json"
archived_result.write_bytes(archived_checkpoint.read_bytes())
os.utime(archived_result, ns=(110, 110))
@@ -354,8 +290,8 @@ def test_deadline_dropped_legacy_surface_does_not_rebind_its_pending_task(
raw_checkpoint = write_checkpoint(
output / "checkpoints",
saved_draft(scan.scan_id, surfaces=[malformed_surface], deferred=[upload_task]),
mtime_ns=200,
)
os.utime(raw_checkpoint, ns=(200, 200))
if selected_result:
selected = write_checkpoint(
output / "checkpoints",
@@ -364,31 +300,14 @@ def test_deadline_dropped_legacy_surface_does_not_rebind_its_pending_task(
surfaces=[malformed_surface],
deferred=[upload_task, download_task],
),
mtime_ns=210,
)
os.utime(selected, ns=(210, 210))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
os.utime(head, ns=(220, 220))
select_checkpoint(output, selected, mtime_ns=220)
result = output / "result.json"
result.write_bytes(selected.read_bytes())
os.utime(result, ns=(230, 230))
originals = {path: path.read_bytes() for path in output.parent.rglob("*") if path.is_file()}
database = tmp_path / "dropped-surface.db"
with sqlite3.connect(database) as connection:
workbench_db.backup(connection)
publications = []
for hash_seed in (1, 17, 83):
interrupt_in_fresh_python(database, scan, hash_seed)
publications.append(read_review_state(workbench_db, scan.scan_dir))
with sqlite3.connect(database) as connection:
connection.row_factory = sqlite3.Row
finish(workbench_api, connection, scan, terminal_reason="capped")
completed = complete(workbench_api, connection, scan)
coverage = read_review_state(workbench_db, scan.scan_dir)
assert completed["progress"]["status"] == "complete"
assert all(publication == coverage for publication in publications)
completed, coverage = finish_after_crashes()
surfaces = [row for row in coverage["surfaces"] if row.get("workerId") == worker_id]
assert len(surfaces) == 1 and surfaces[0]["label"] == "download"
tasks = [row for row in coverage["deferred"] if row.get("workerId") == worker_id]
@@ -409,7 +328,7 @@ def test_deadline_dropped_legacy_surface_does_not_rebind_its_pending_task(
["parent-collision", "current-checkpoints", "retry-checkpoints", "coalesced-history"],
)
def test_deadline_inherited_surface_links_follow_historical_observations(
workbench_api, workbench_db, deadline_scan, tmp_path, history
workbench_db, deadline_scan, finish_after_crashes, history
):
scan = deadline_scan
worker_id, output = canceled_discovery_output(
@@ -417,26 +336,26 @@ def test_deadline_inherited_surface_links_follow_historical_observations(
)
archived = output.parent / "attempts" / "attempt-01"
first_output = archived if history == "retry-checkpoints" else output
earlier = write_checkpoint(
write_checkpoint(
first_output / "checkpoints",
saved_draft(scan.scan_id, surfaces=[surface("Earlier observation")]),
mtime_ns=100,
)
os.utime(earlier, ns=(100, 100))
expected_labels = {"Earlier observation"}
if history != "parent-collision":
newer = write_checkpoint(
write_checkpoint(
output / "checkpoints",
saved_draft(scan.scan_id, surfaces=[surface("Newer observation")]),
mtime_ns=200,
)
os.utime(newer, ns=(200, 200))
expected_labels.add("Newer observation")
inherited_task = pending("history-review", "Review the inherited surface.")
unknown_task = pending("unknown-review", "Review an unresolved reference.", "not-declared")
deferred_only = write_checkpoint(
write_checkpoint(
output / "checkpoints",
saved_draft(scan.scan_id, deferred=[inherited_task, unknown_task]),
mtime_ns=300,
)
os.utime(deferred_only, ns=(300, 300))
if history == "coalesced-history":
# The merged checkpoint copies a task whose earlier raw source inherited history.
selected = write_checkpoint(
@@ -446,40 +365,23 @@ def test_deadline_inherited_surface_links_follow_historical_observations(
surfaces=[surface("Newer observation")],
deferred=[inherited_task, unknown_task],
),
mtime_ns=400,
)
os.utime(selected, ns=(400, 400))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
os.utime(head, ns=(410, 410))
select_checkpoint(output, selected, mtime_ns=410)
if history == "current-checkpoints":
# An interrupted later write cannot identify an earlier task's target.
future = write_checkpoint(
write_checkpoint(
output / "checkpoints",
saved_draft(scan.scan_id, surfaces=[surface("Later observation")]),
mtime_ns=400,
)
os.utime(future, ns=(400, 400))
canonical_id = f"{worker_id}/entry" if history == "parent-collision" else "parent-entry"
canonical_surface = surface("Canonical parent", canonical_id)
canonical_task = pending("parent-review", "Parent review remains.", canonical_id)
scan.coverage.update(surfaces=[canonical_surface], deferred=[canonical_task])
(scan.scan_dir / "coverage.json").write_text(json.dumps(scan.coverage))
originals = {path: path.read_bytes() for path in output.parent.rglob("*") if path.is_file()}
database = tmp_path / "historical-links.db"
with sqlite3.connect(database) as connection:
workbench_db.backup(connection)
publications = []
for hash_seed in (1, 17, 83):
interrupt_in_fresh_python(database, scan, hash_seed)
publications.append(read_review_state(workbench_db, scan.scan_dir))
with sqlite3.connect(database) as connection:
connection.row_factory = sqlite3.Row
finish(workbench_api, connection, scan, terminal_reason="capped")
completed = complete(workbench_api, connection, scan)
coverage = read_review_state(workbench_db, scan.scan_dir)
assert completed["progress"]["status"] == "complete"
assert all(publication == coverage for publication in publications)
_, coverage = finish_after_crashes()
assert canonical_surface in coverage["surfaces"]
assert canonical_task in coverage["deferred"]
worker_surfaces = [row for row in coverage["surfaces"] if row.get("workerId") == worker_id]
@@ -502,7 +404,7 @@ def test_deadline_inherited_surface_links_follow_historical_observations(
ids=["same-id", "changed-id", "legacy-duplicate-id"],
)
def test_deadline_candidate_supersession_preserves_independent_surface_links(
workbench_api, workbench_db, deadline_scan, tmp_path, changed_surface_id, legacy_duplicate_id
workbench_db, deadline_scan, finish_after_crashes, changed_surface_id, legacy_duplicate_id
):
scan = deadline_scan
worker_id, output = canceled_discovery_output(workbench_db, scan)
@@ -517,46 +419,30 @@ def test_deadline_candidate_supersession_preserves_independent_surface_links(
if legacy_duplicate_id:
# Legacy artifacts may reuse an ID for a candidate and an independent observation.
earlier_surfaces.append(surface("Independent observation"))
earlier = write_checkpoint(
write_checkpoint(
output / "checkpoints",
saved_draft(scan.scan_id, surfaces=earlier_surfaces, deferred=[independent]),
mtime_ns=100,
)
os.utime(earlier, ns=(100, 100))
outcome_id = "outcome" if changed_surface_id else "entry"
outcome = {
**surface("Candidate reviewed", outcome_id, "rejected"),
"candidateId": "candidate",
}
raw_checkpoint = write_checkpoint(
output / "checkpoints", saved_draft(scan.scan_id, complete=True, surfaces=[outcome])
write_checkpoint(
output / "checkpoints",
saved_draft(scan.scan_id, complete=True, surfaces=[outcome]),
mtime_ns=200,
)
os.utime(raw_checkpoint, ns=(200, 200))
# The selected merged checkpoint retains independent work before result publication.
selected = write_checkpoint(
output / "checkpoints",
saved_draft(scan.scan_id, complete=True, surfaces=[outcome], deferred=[independent]),
mtime_ns=210,
)
os.utime(selected, ns=(210, 210))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
os.utime(head, ns=(220, 220))
select_checkpoint(output, selected, mtime_ns=220)
originals = {path: path.read_bytes() for path in output.rglob("*") if path.is_file()}
database = tmp_path / "candidate-links.db"
with sqlite3.connect(database) as connection:
workbench_db.backup(connection)
publications = []
for hash_seed in (1, 17, 83):
interrupt_in_fresh_python(database, scan, hash_seed)
publications.append(read_review_state(workbench_db, scan.scan_dir))
with sqlite3.connect(database) as connection:
connection.row_factory = sqlite3.Row
finish(workbench_api, connection, scan, terminal_reason="capped")
completed = complete(workbench_api, connection, scan)
coverage = read_review_state(workbench_db, scan.scan_dir)
assert completed["progress"]["status"] == "complete"
assert all(publication == coverage for publication in publications)
_, coverage = finish_after_crashes()
assert canonical_surface in coverage["surfaces"]
assert canonical_task in coverage["deferred"]
retained = [row for row in coverage["surfaces"] if row.get("workerId") == worker_id]
@@ -12,7 +12,6 @@ from pathlib import Path
from types import SimpleNamespace
import pytest
from test_deep_scan_successful_publication import add_worker, complete
from test_deep_scan_successful_publication import publication_scan as publication_scan
from workbench_test_support import read_review_state
@@ -63,8 +62,8 @@ def test_stale_coordinator_cannot_replace_newer_canonical_publication(
workbench_api, workbench_db, publication_scan, stale, complete
):
scan = publication_scan()
old_result = add_worker(workbench_db, scan)
new_result = add_worker(workbench_db, scan)
old_result = scan.add_worker()
new_result = scan.add_worker()
with workbench_db:
workbench_db.execute(
"UPDATE deep_scan_runs SET coordinator_generation = 3 WHERE scan_id = ?",
@@ -120,7 +119,7 @@ def test_current_publication_replays_without_changing_checkpoint_or_worker_state
instant = workbench_api["now"]()
monkeypatch.setattr(workbench_api["_WORKBENCH_DB_CONTEXT"], "now", lambda: instant)
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
with workbench_db:
workbench_db.execute(
"UPDATE deep_scan_runs SET coordinator_generation = ?, status = 'running' "
@@ -182,7 +181,7 @@ def test_legacy_terminal_aggregate_survives_a_late_partial_draft_after_write_fai
with monkeypatch.context() as patch:
patch.setitem(finalizer_globals, "write_scan_local_bytes", fail_report)
with pytest.raises(SystemExit, match="Synthetic report write interruption"):
complete(workbench_api, workbench_db, scan)
scan.complete()
run = workbench_db.execute(
"SELECT status, coordinator_generation FROM deep_scan_runs WHERE scan_id = ?",
@@ -212,7 +211,7 @@ def test_legacy_terminal_aggregate_survives_a_late_partial_draft_after_write_fai
for path in scan.scan_dir.rglob("*.json")
if "drafts" not in path.parts
} == saved
assert complete(workbench_api, workbench_db, scan)["progress"]["status"] == "complete"
assert scan.complete()["progress"]["status"] == "complete"
findings = json.loads((scan.scan_dir / "findings.json").read_text())["findings"]
assert [finding["title"] for finding in findings] == [scan.findings[0]["title"]]
assert read_review_state(workbench_db, scan.scan_dir)["deferred"] == scan.coverage["deferred"]
@@ -227,7 +226,7 @@ def test_failed_publication_does_not_acknowledge_staged_input(
workbench_api, workbench_db, publication_scan, monkeypatch, failure
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
with workbench_db:
workbench_db.execute(
"UPDATE deep_scan_runs SET workflow_version = 'deep-scan-mcp/v1', "
@@ -352,7 +351,7 @@ def test_receipt_io_failure_preserves_successful_publication(
if backend_kind == "posix" and os.name == "nt":
pytest.skip("POSIX descriptor-relative directory errors")
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
with workbench_db:
workbench_db.execute(
"UPDATE deep_scan_runs SET workflow_version = ?, coordinator_generation = 2 "
@@ -501,7 +500,7 @@ def test_windows_receipt_root_probe_classifies_storage_and_path_failures(
failure,
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
with workbench_db:
workbench_db.execute(
"UPDATE deep_scan_runs SET coordinator_generation = 2 WHERE scan_id = ?",
@@ -628,7 +627,7 @@ def test_receipt_contract_errors_still_reject_publication(
workbench_api, workbench_db, publication_scan, monkeypatch, failure
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
with workbench_db:
workbench_db.execute(
"UPDATE deep_scan_runs SET workflow_version = 'deep-scan-mcp/v1', "
@@ -672,7 +671,7 @@ def test_accepted_publication_replay_retains_original_warning_and_bytes(
workbench_api, workbench_db, publication_scan, monkeypatch
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
with workbench_db:
workbench_db.execute(
"UPDATE deep_scan_runs SET coordinator_generation = 2 WHERE scan_id = ?",
@@ -9,7 +9,6 @@ from pathlib import Path
import pytest
from test_deep_scan_publication_authority import stage_publication
from test_deep_scan_successful_publication import add_worker
from test_deep_scan_successful_publication import publication_scan as publication_scan
_CRASH_PUBLICATION = """
@@ -60,7 +59,7 @@ def test_publication_crash_replays_selected_input_without_stale_overwrite(
workbench_api, workbench_db, publication_scan, tmp_path, boundary
):
scan = publication_scan()
result_path = add_worker(workbench_db, scan)
result_path = scan.add_worker()
with workbench_db:
workbench_db.execute(
"UPDATE deep_scan_runs SET coordinator_generation = 3 WHERE scan_id = ?",
@@ -7,21 +7,22 @@ import sqlite3
from argparse import Namespace
import pytest
from test_deep_scan_successful_publication import (
add_worker,
assert_published_aggregate,
complete,
)
from test_deep_scan_successful_publication import assert_published_aggregate
from test_deep_scan_successful_publication import (
publication_scan as publication_scan,
)
from workbench_test_support import read_review_state, saved_draft, write_checkpoint
from workbench_test_support import (
read_review_state,
saved_draft,
select_checkpoint,
write_checkpoint,
)
@pytest.fixture
def saturated_scan(publication_scan, workbench_db):
scan = publication_scan()
completed_result = add_worker(workbench_db, scan)
completed_result = scan.add_worker()
completed_result.write_text(
json.dumps(
{
@@ -32,7 +33,7 @@ def saturated_scan(publication_scan, workbench_db):
}
)
)
reducer_result = add_worker(workbench_db, scan)
reducer_result = scan.add_worker()
reducer_result.write_bytes(completed_result.read_bytes())
with workbench_db:
workbench_db.execute(
@@ -84,7 +85,7 @@ def deadline_scan(saturated_scan, workbench_db):
def canceled_discovery_output(connection, scan, *, attempt=1):
result = add_worker(connection, scan, status="canceled")
result = scan.add_worker(connection, status="canceled")
worker_id = result.parent.name
output = scan.scan_dir / "artifacts" / "deep_discovery" / "workers" / worker_id / "output"
output.parent.mkdir(parents=True)
@@ -117,7 +118,7 @@ def test_deadline_preserves_optional_reduced_writeup_behavior(
)
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
assert completed["progress"]["status"] == "complete"
finding = json.loads((scan.scan_dir / "findings.json").read_text())["findings"][0]
@@ -153,7 +154,7 @@ def test_deadline_recovers_valid_findings_from_an_invalid_archived_retry(
)
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
findings = json.loads((scan.scan_dir / "findings.json").read_text())["findings"]
assert {item["identity"]["anchor"] for item in findings} == {
@@ -222,7 +223,7 @@ def test_deadline_preserves_worker_findings_with_optional_and_shared_identity(
)
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
findings = json.loads((scan.scan_dir / "findings.json").read_text())["findings"]
assert len(findings) == 4
@@ -237,19 +238,18 @@ def test_deadline_resolves_worker_local_deferred_ids_before_scoping(
):
scan = deadline_scan
_, output = canceled_discovery_output(workbench_db, scan)
previous = write_checkpoint(
write_checkpoint(
output / "checkpoints",
saved_draft(scan.scan_id, deferred=[{"id": "review", "reason": "Review pending."}]),
mtime_ns=100,
)
os.utime(previous, ns=(100, 100))
current = saved_draft(scan.scan_id, complete=True)
current["coverage"]["resolvedDeferred"] = [{"id": "review", "reason": "Review completed."}]
latest = write_checkpoint(output / "checkpoints", current)
os.utime(latest, ns=(200, 200))
(output / "checkpoint-head.json").write_text(json.dumps({"checkpoint": latest.name}))
latest = write_checkpoint(output / "checkpoints", current, mtime_ns=200)
select_checkpoint(output, latest)
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
complete(workbench_api, workbench_db, scan)
scan.complete()
coverage = read_review_state(workbench_db, scan.scan_dir)
assert not any(item["reason"] == "Review pending." for item in coverage["deferred"])
@@ -277,7 +277,7 @@ def test_deadline_does_not_turn_invalid_worker_receipts_into_parent_artifacts(
)
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
surface = read_review_state(workbench_db, scan.scan_dir)["surfaces"][0]
assert surface["receiptRefs"] == []
@@ -342,7 +342,7 @@ def test_deadline_preserves_worker_receipts_and_surface_links(
expected[label] = (worker_id, receipt, checkpoint, checkpoint.read_bytes())
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
complete(workbench_api, workbench_db, scan)
scan.complete()
coverage = read_review_state(workbench_db, scan.scan_dir)
assert len(coverage["surfaces"]) == 3
@@ -372,7 +372,7 @@ def test_saturated_finish_cancels_unfinished_discovery_without_using_its_drafts(
scan = saturated_scan
unfinished = []
for status in ("queued", "running"):
result = add_worker(workbench_db, scan, status=status)
result = scan.add_worker(status=status)
result.write_text("{unfinished worker draft")
unfinished.append(result)
@@ -391,7 +391,7 @@ def test_saturated_finish_cancels_unfinished_discovery_without_using_its_drafts(
assert worker["mergeState"] == "none"
assert result.read_text() == "{unfinished worker draft"
complete(workbench_api, workbench_db, scan)
scan.complete()
assert_published_aggregate(scan)
@@ -399,7 +399,7 @@ def test_saturated_finish_retains_failed_discovery_diagnostic(
workbench_api, workbench_db, saturated_scan
):
scan = saturated_scan
result = add_worker(workbench_db, scan, status="failed")
result = scan.add_worker(status="failed")
error = "Worker stopped while persisting its result."
with workbench_db:
workbench_db.execute(
@@ -415,7 +415,7 @@ def test_saturated_finish_retains_failed_discovery_diagnostic(
)
assert failed_worker["status"] == "failed"
assert failed_worker["error"] == error
complete(workbench_api, workbench_db, scan)
scan.complete()
assert_published_aggregate(scan)
@@ -424,7 +424,7 @@ def test_unfinished_checkpoints_after_a_completed_reduction(
workbench_api, workbench_db, saturated_scan, stop
):
scan = saturated_scan
result = add_worker(workbench_db, scan, status="canceled")
result = scan.add_worker(status="canceled")
recovered = copy.deepcopy(scan.findings[0])
recovered["identity"]["anchor"] = "unfinished-upload-review"
recovered["title"] = "Separate upload handler bypasses containment"
@@ -468,8 +468,7 @@ def test_unfinished_checkpoints_after_a_completed_reduction(
saved_draft(scan.scan_id, findings=[discarded]),
)
if directory == scan.scan_dir:
head = directory / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": discarded_checkpoint.name}))
head = select_checkpoint(directory, discarded_checkpoint)
observed = (
max(
(directory / name).stat().st_mtime_ns
@@ -506,7 +505,7 @@ def test_unfinished_checkpoints_after_a_completed_reduction(
assert tuple(row) == ("running", None)
manifest = json.loads((scan.scan_dir / "scan-manifest.json").read_text())
assert "sealedAt" not in manifest["scan"]
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
assert completed["progress"]["status"] == "complete"
findings = json.loads((scan.scan_dir / "findings.json").read_text())["findings"]
expected_anchors = {scan.findings[0]["identity"]["anchor"]}
@@ -541,7 +540,7 @@ def test_unfinished_checkpoints_after_a_completed_reduction(
names = ("scan-manifest.json", "findings.json", "report.md")
sealed = {name: (scan.scan_dir / name).read_bytes() for name in names}
finish(workbench_api, workbench_db, scan, terminal_reason=reason)
complete(workbench_api, workbench_db, scan)
scan.complete()
assert {name: (scan.scan_dir / name).read_bytes() for name in names} == sealed
@@ -556,7 +555,7 @@ def test_deadline_after_all_reviews_complete_keeps_reduced_coverage(
)
finish(workbench_api, workbench_db, scan, terminal_reason="capped")
complete(workbench_api, workbench_db, scan)
scan.complete()
assert_published_aggregate(scan)
@@ -570,7 +569,7 @@ def test_finish_preserves_other_worker_failure_checks(
workbench_api, workbench_db, saturated_scan, terminal_reason, kind
):
scan = saturated_scan
result = add_worker(workbench_db, scan, status="failed")
result = scan.add_worker(status="failed")
with workbench_db:
workbench_db.execute(
"UPDATE deep_scan_workers SET kind = ? WHERE id = ?", (kind, result.parent.name)
@@ -602,7 +601,7 @@ def test_rejected_deadline_publication_does_not_leave_parent_observations(
os.utime(scan.scan_dir / name, ns=(1_000_000_000, 1_000_000_000))
pending = {"id": "authorization-review", "reason": "Review the remaining authorization path."}
if with_reduction:
result = add_worker(workbench_db, scan, status="canceled")
result = scan.add_worker(status="canceled")
write_checkpoint(
result.parent / "checkpoints",
saved_draft(scan.scan_id, deferred=[pending]),
@@ -612,8 +611,7 @@ def test_rejected_deadline_publication_does_not_leave_parent_observations(
scan.scan_dir / "checkpoints",
saved_draft(scan.scan_id, findings=scan.findings, deferred=[pending]),
)
head = scan.scan_dir / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
head = select_checkpoint(scan.scan_dir, checkpoint)
for path in (checkpoint, head):
os.utime(path, ns=(2_000_000_000, 2_000_000_000))
saved = workbench_api["saved_results"]
@@ -677,7 +675,7 @@ def test_zero_accepted_deadline_preserves_worker_checkpoint_links_and_receipts(
workers = {}
originals = {}
for name in ("first", "second"):
result = add_worker(workbench_db, scan, status="canceled")
result = scan.add_worker(status="canceled")
worker_id = result.parent.name
output = scan.scan_dir / "artifacts" / "deep_discovery" / "workers" / worker_id / "output"
output.parent.mkdir(parents=True)
@@ -708,8 +706,7 @@ def test_zero_accepted_deadline_preserves_worker_checkpoint_links_and_receipts(
deferred=[{"id": "review", "reason": "Review remains.", "surfaceIds": ["api"]}],
),
)
head = result.parent / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
head = select_checkpoint(result.parent, checkpoint)
workers[worker_id] = receipt
originals.update({path: path.read_bytes() for path in (receipt, checkpoint, head)})
with workbench_db:
@@ -18,6 +18,62 @@ from workbench_test_support import (
)
class PublicationScan(SimpleNamespace):
def add_worker(self, connection=None, *, status="succeeded") -> Path:
worker_id = str(uuid.uuid4())
output = self.scan_dir / "workers" / worker_id
output.mkdir(parents=True)
result = output / "result.json"
connection = self.connection if connection is None else connection
with connection:
connection.execute(
"INSERT INTO deep_scan_workers (id, scan_id, kind, status, merge_state, "
"prompt_path, artifact_dir, result_manifest_path, attempt, created_at, "
"updated_at, completed_at) VALUES (?, ?, 'discovery', ?, ?, ?, ?, ?, 1, ?, ?, ?)",
(
worker_id,
self.scan_id,
status,
"merged" if status == "succeeded" else "none",
str(output / "prompt.md"),
str(output),
str(result),
self.timestamp,
self.timestamp,
self.timestamp,
),
)
return result
def complete(self, connection=None, *, prepare_only=False):
return self.api["complete_scan"](
self.connection if connection is None else connection,
Namespace(scan_id=self.scan_id, claim_token=None, cost_json=None),
prepare_only=prepare_only,
)["scan"]
def fail(self, message="Stopped."):
return self.api["saved_results"].fail_scan(
self.api["_WORKBENCH_DB_CONTEXT"],
self.connection,
Namespace(scan_id=self.scan_id, claim_token=None, cost_json=None, message=message),
)["scan"]
def preserve(self, connection=None):
return self.api["saved_results"].preserve_scan_results(
self.api["_WORKBENCH_DB_CONTEXT"],
self.connection if connection is None else connection,
Namespace(
scan_id=self.scan_id, claim_token=None, thread_id=None, coordinator_generation=None
),
)["scan"]
def recover(self):
return self.api["saved_results"].recover_scan_results(
self.api["_WORKBENCH_DB_CONTEXT"], self.connection, Namespace(scan_id=self.scan_id)
)["scan"]
@pytest.fixture
def publication_scan(workbench_api, workbench_db, tmp_path, monkeypatch):
monkeypatch.setenv("CODEX_SECURITY_STATE_DIR", str(tmp_path / "state"))
@@ -126,7 +182,9 @@ def publication_scan(workbench_api, workbench_db, tmp_path, monkeypatch):
("coverage.json", coverage),
):
(scan_dir / name).write_text(json.dumps(value))
return SimpleNamespace(
return PublicationScan(
api=workbench_api,
connection=workbench_db,
scan_id=scan_id,
scan_dir=scan_dir,
timestamp=timestamp,
@@ -137,64 +195,6 @@ def publication_scan(workbench_api, workbench_db, tmp_path, monkeypatch):
return create
def add_worker(connection, scan, *, status="succeeded") -> Path:
worker_id = str(uuid.uuid4())
output = scan.scan_dir / "workers" / worker_id
output.mkdir(parents=True)
result = output / "result.json"
with connection:
connection.execute(
"INSERT INTO deep_scan_workers (id, scan_id, kind, status, merge_state, "
"prompt_path, artifact_dir, result_manifest_path, attempt, created_at, "
"updated_at, completed_at) VALUES (?, ?, 'discovery', ?, ?, ?, ?, ?, 1, ?, ?, ?)",
(
worker_id,
scan.scan_id,
status,
"merged" if status == "succeeded" else "none",
str(output / "prompt.md"),
str(output),
str(result),
scan.timestamp,
scan.timestamp,
scan.timestamp,
),
)
return result
def complete(workbench_api, connection, scan, *, prepare_only=False):
return workbench_api["complete_scan"](
connection,
Namespace(scan_id=scan.scan_id, claim_token=None, cost_json=None),
prepare_only=prepare_only,
)["scan"]
def fail_scan(workbench_api, connection, scan, message="Stopped."):
return workbench_api["saved_results"].fail_scan(
workbench_api["_WORKBENCH_DB_CONTEXT"],
connection,
Namespace(scan_id=scan.scan_id, claim_token=None, cost_json=None, message=message),
)["scan"]
def preserve_scan_results(workbench_api, connection, scan):
return workbench_api["saved_results"].preserve_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"],
connection,
Namespace(
scan_id=scan.scan_id, claim_token=None, thread_id=None, coordinator_generation=None
),
)["scan"]
def recover_scan_results(workbench_api, connection, scan):
return workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], connection, Namespace(scan_id=scan.scan_id)
)["scan"]
def assert_published_aggregate(scan):
findings = json.loads((scan.scan_dir / "findings.json").read_text())["findings"]
for finding in findings:
@@ -218,9 +218,7 @@ def assert_published_aggregate(scan):
@pytest.mark.parametrize("mode", ["standard", "deep", "deep-nested"])
@pytest.mark.parametrize("linked_writeup", [False, True], ids=["inline", "linked"])
def test_publication_renders_each_source_remediation(
workbench_api, workbench_db, publication_scan, mode, linked_writeup
):
def test_publication_renders_each_source_remediation(publication_scan, mode, linked_writeup):
scan = publication_scan(mode="deep" if mode == "deep-nested" else mode)
finding = scan.findings[0]
first = copy.deepcopy(finding)
@@ -261,7 +259,7 @@ def test_publication_renders_each_source_remediation(
writeup_bytes = writeup.read_bytes()
(scan.scan_dir / "findings.json").write_text(json.dumps({"findings": scan.findings}))
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
assert completed["progress"]["status"] == "complete"
assert_published_aggregate(scan)
@@ -281,10 +279,10 @@ def test_publication_renders_each_source_remediation(
@pytest.mark.parametrize("scope", [".", "subdir"], ids=["repository", "scoped"])
def test_deep_publication_keeps_configured_scope_without_worker_observations(
workbench_api, workbench_db, publication_scan, scope
publication_scan, scope
):
scan = publication_scan(scope=scope)
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_coverage = {
"surfaces": [
{
@@ -310,7 +308,7 @@ def test_deep_publication_keeps_configured_scope_without_worker_observations(
)
source_bytes = result.read_bytes()
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
assert completed["progress"]["status"] == "complete"
assert_published_aggregate(scan)
@@ -326,18 +324,16 @@ def test_deep_publication_keeps_configured_scope_without_worker_observations(
assert "Which deployment controls apply?" not in report
def test_deep_publication_ignores_empty_canceled_checkpoint(
workbench_api, workbench_db, publication_scan
):
def test_deep_publication_ignores_empty_canceled_checkpoint(publication_scan):
scan = publication_scan()
result = add_worker(workbench_db, scan, status="canceled")
result = scan.add_worker(status="canceled")
checkpoint = write_checkpoint(
result.parent / "checkpoints",
saved_draft(scan.scan_id),
)
source_bytes = checkpoint.read_bytes()
complete(workbench_api, workbench_db, scan)
scan.complete()
assert_published_aggregate(scan)
assert checkpoint.read_bytes() == source_bytes
@@ -345,16 +341,14 @@ def test_deep_publication_ignores_empty_canceled_checkpoint(
@pytest.mark.parametrize("old_result", ["unreadable", "removed"])
def test_deep_publication_does_not_require_old_worker_files(
workbench_api, workbench_db, publication_scan, old_result
):
def test_deep_publication_does_not_require_old_worker_files(publication_scan, old_result):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
result.write_text("{old worker output is unavailable")
if old_result == "removed":
result.unlink()
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
assert completed["warnings"] == []
assert_published_aggregate(scan)
@@ -387,28 +381,26 @@ def reviewed_deep_scan(publication_scan, request):
return scan
def test_deep_prepare_and_complete_preserve_the_same_aggregate(
workbench_api, workbench_db, reviewed_deep_scan
):
def test_deep_prepare_and_complete_preserve_the_same_aggregate(workbench_db, reviewed_deep_scan):
scan = reviewed_deep_scan
count = "SELECT terminal_reviewed_surface_count FROM deep_scan_runs WHERE scan_id = ?"
assert workbench_db.execute(count, (scan.scan_id,)).fetchone()[0] is None
prepared = complete(workbench_api, workbench_db, scan, prepare_only=True)
prepared = scan.complete(prepare_only=True)
assert prepared["progress"]["status"] == "running"
assert workbench_db.execute(count, (scan.scan_id,)).fetchone()[0] == 1
names = ("scan-manifest.json", "findings.json")
published = {name: (scan.scan_dir / name).read_bytes() for name in names}
complete(workbench_api, workbench_db, scan, prepare_only=True)
complete(workbench_api, workbench_db, scan)
scan.complete(prepare_only=True)
scan.complete()
# A capped scan with a failed worker cannot publish anew, but its sealed result can be read.
add_worker(workbench_db, scan, status="failed")
scan.add_worker(status="failed")
with workbench_db:
workbench_db.execute(
"UPDATE deep_scan_runs SET terminal_reason = 'capped' WHERE scan_id = ?",
(scan.scan_id,),
)
repeated = complete(workbench_api, workbench_db, scan)
repeated = scan.complete()
assert repeated["progress"]["status"] == "complete"
assert workbench_db.execute(count, (scan.scan_id,)).fetchone()[0] == 1
@@ -416,24 +408,22 @@ def test_deep_prepare_and_complete_preserve_the_same_aggregate(
assert_published_aggregate(scan)
def test_complete_prepared_deep_scan_after_count_migration(
workbench_api, workbench_db, reviewed_deep_scan
):
def test_complete_prepared_deep_scan_after_count_migration(workbench_db, reviewed_deep_scan):
scan = reviewed_deep_scan
complete(workbench_api, workbench_db, scan, prepare_only=True)
scan.complete(prepare_only=True)
count = "SELECT terminal_reviewed_surface_count FROM deep_scan_runs WHERE scan_id = ?"
clear = "UPDATE deep_scan_runs SET terminal_reviewed_surface_count = NULL WHERE scan_id = ?"
# A seal produced before the migration has no stored count.
with workbench_db:
workbench_db.execute(clear, (scan.scan_id,))
complete(workbench_api, workbench_db, scan)
scan.complete()
sealed = json.loads((scan.scan_dir / "scan-manifest.json").read_text())
expected = 1 if "coverageRef" in sealed["scan"] else None
assert workbench_db.execute(count, (scan.scan_id,)).fetchone()[0] == expected
with workbench_db:
workbench_db.execute(clear, (scan.scan_id,))
complete(workbench_api, workbench_db, scan)
scan.complete()
assert workbench_db.execute(count, (scan.scan_id,)).fetchone()[0] is None
@@ -458,7 +448,7 @@ def test_complete_sealed_deep_scan_with_inline_review_state(
sealed["scan"]["reviewState"] = state
path.write_text(json.dumps(sealed, indent=2, sort_keys=True) + "\n")
complete(workbench_api, workbench_db, scan)
scan.complete()
query = "SELECT terminal_reviewed_surface_count FROM deep_scan_runs WHERE scan_id = ?"
assert workbench_db.execute(query, (scan.scan_id,)).fetchone()[0] == count
@@ -468,7 +458,7 @@ def test_stopping_prepared_deep_scan_clears_its_surface_count(
workbench_api, workbench_db, reviewed_deep_scan, stop
):
scan = reviewed_deep_scan
complete(workbench_api, workbench_db, scan, prepare_only=True)
scan.complete(prepare_only=True)
count = "SELECT terminal_reviewed_surface_count FROM deep_scan_runs WHERE scan_id = ?"
assert workbench_db.execute(count, (scan.scan_id,)).fetchone()[0] == 1
if stop == "cancel":
@@ -478,14 +468,14 @@ def test_stopping_prepared_deep_scan_clears_its_surface_count(
Namespace(scan_id=scan.scan_id, thread_id=None),
)
else:
fail_scan(workbench_api, workbench_db, scan)
scan.fail()
assert workbench_db.execute(count, (scan.scan_id,)).fetchone()[0] is None
@pytest.mark.parametrize("mode", ["standard", "deep"])
@pytest.mark.parametrize("after_sealing", [False, True])
def test_completion_captures_target_warnings_before_first_seal(
workbench_api, workbench_db, publication_scan, monkeypatch, tmp_path, mode, after_sealing
workbench_api, publication_scan, monkeypatch, tmp_path, mode, after_sealing
):
scan = publication_scan(mode=mode)
source = tmp_path / "target" / "subdir" / "extract.py"
@@ -500,13 +490,13 @@ def test_completion_captures_target_warnings_before_first_seal(
with monkeypatch.context() as patch:
patch.setitem(completion_globals, "_prepare_scan_finalization", prepare_then_change_target)
complete(workbench_api, workbench_db, scan, prepare_only=True)
scan.complete(prepare_only=True)
manifest_path = scan.scan_dir / "scan-manifest.json"
sealed_bytes = manifest_path.read_bytes()
if after_sealing:
source.write_text("# Changed after preparation sealed the scan\n")
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
assert completed["progress"]["status"] == "complete"
assert len(completed["warnings"]) == 1
@@ -526,13 +516,11 @@ def test_completion_captures_target_warnings_before_first_seal(
@pytest.mark.skipif(os.name == "nt", reason="Unix filenames can contain non-UTF-8 bytes")
@pytest.mark.parametrize("mode", ["standard", "deep"])
def test_completion_preserves_non_utf8_filename_warning(
workbench_api, workbench_db, publication_scan, tmp_path, mode
):
def test_completion_preserves_non_utf8_filename_warning(publication_scan, tmp_path, mode):
scan = publication_scan(mode=mode)
os.mkfifo(os.fsencode(tmp_path / "target") + b"/new-pipe-\xff")
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
assert completed["progress"]["status"] == "complete"
warning = completed["warnings"][0]
@@ -547,7 +535,7 @@ def test_completion_preserves_non_utf8_filename_warning(
assert invocation["toolExecutionNotifications"] == [
{"level": "warning", "message": {"text": portable_warning}}
]
complete(workbench_api, workbench_db, scan)
scan.complete()
assert manifest_path.read_bytes() == sealed_bytes
@@ -581,7 +569,7 @@ def test_preseal_target_warning_survives_failed_publication(
with monkeypatch.context() as patch:
patch.setitem(finalizer_globals, "write_scan_local_bytes", fail_first_report)
with pytest.raises(SystemExit, match="Synthetic first report write failure"):
complete(workbench_api, workbench_db, scan)
scan.complete()
row = workbench_db.execute("SELECT * FROM scans WHERE id = ?", (scan.scan_id,)).fetchone()
assert row["status"] == ("failed" if mode == "standard" else "running")
@@ -589,7 +577,7 @@ def test_preseal_target_warning_survives_failed_publication(
# The failed output write must not erase an earlier observation if the
# next attempt finds that the target has returned to its original state.
source_path.write_bytes(source_before)
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
assert completed["progress"]["status"] == "complete"
row = workbench_db.execute("SELECT * FROM scans WHERE id = ?", (scan.scan_id,)).fetchone()
manifest = json.loads((scan.scan_dir / "scan-manifest.json").read_text())
@@ -615,7 +603,7 @@ def test_preseal_target_warning_survives_failed_publication(
@pytest.mark.cross_platform
@pytest.mark.parametrize("scope", [".", "subdir"])
def test_deep_completion_preserves_findings_with_missing_optional_writeups(
workbench_api, workbench_db, publication_scan, scope
workbench_db, publication_scan, scope
):
scan = publication_scan(scope=scope)
valid_path = "findings/valid/valid.md"
@@ -641,7 +629,7 @@ def test_deep_completion_preserves_findings_with_missing_optional_writeups(
(scan.scan_dir / "findings.json").write_text(json.dumps({"findings": scan.findings}))
original_files = {valid_file: valid_file.read_bytes()}
for kind in ("discovery", "dedup"):
result = add_worker(workbench_db, scan)
result = scan.add_worker()
result.write_text(
json.dumps(saved_draft(scan.scan_id, findings=scan.findings, complete=True))
)
@@ -655,8 +643,8 @@ def test_deep_completion_preserves_findings_with_missing_optional_writeups(
)
# Preparing and then completing also exercises replay of the sealed parent.
prepared = complete(workbench_api, workbench_db, scan, prepare_only=True)
completed = complete(workbench_api, workbench_db, scan)
prepared = scan.complete(prepare_only=True)
completed = scan.complete()
assert completed["progress"]["status"] == "complete"
assert completed["findingCount"] == 3
@@ -681,9 +669,7 @@ def test_deep_completion_preserves_findings_with_missing_optional_writeups(
@pytest.mark.cross_platform
@pytest.mark.parametrize("invalid", ["unsafe-path", "directory"])
def test_deep_scope_filter_does_not_hide_invalid_writeups(
workbench_api, workbench_db, publication_scan, invalid
):
def test_deep_scope_filter_does_not_hide_invalid_writeups(workbench_db, publication_scan, invalid):
scan = publication_scan(scope="subdir")
finding = scan.findings[0]
finding["locations"] = [{"path": "unrelated/extract.py", "startLine": 1}]
@@ -696,7 +682,7 @@ def test_deep_scope_filter_does_not_hide_invalid_writeups(
(scan.scan_dir / "findings.json").write_text(json.dumps({"findings": scan.findings}))
with pytest.raises(SystemExit, match="reportPath|regular non-symlink file"):
complete(workbench_api, workbench_db, scan)
scan.complete()
assert (
workbench_db.execute("SELECT status FROM scans WHERE id = ?", (scan.scan_id,)).fetchone()[0]
!= "complete"
@@ -706,7 +692,7 @@ def test_deep_scope_filter_does_not_hide_invalid_writeups(
@pytest.mark.cross_platform
@pytest.mark.parametrize("invalid", ["finding", "coverage"])
def test_missing_deep_writeup_does_not_enable_general_recovery(
workbench_api, workbench_db, publication_scan, invalid
workbench_db, publication_scan, invalid
):
scan = publication_scan()
scan.findings[0]["writeup"] = {"reportPath": "findings/missing/missing.md"}
@@ -718,7 +704,7 @@ def test_missing_deep_writeup_does_not_enable_general_recovery(
(scan.scan_dir / "coverage.json").write_text(json.dumps(scan.coverage))
with pytest.raises(SystemExit, match="severity|surfaces"):
complete(workbench_api, workbench_db, scan)
scan.complete()
assert (
workbench_db.execute("SELECT status FROM scans WHERE id = ?", (scan.scan_id,)).fetchone()[0]
!= "complete"
@@ -743,7 +729,7 @@ def test_missing_deep_writeup_does_not_enable_general_recovery(
],
)
def test_stopped_deep_scan_still_salvages_saved_findings(
workbench_api, workbench_db, publication_scan, source, scope, has_parent
workbench_db, publication_scan, source, scope, has_parent
):
scan = publication_scan(scope=scope)
if not has_parent:
@@ -755,9 +741,7 @@ def test_stopped_deep_scan_still_salvages_saved_findings(
"terminal_reason = NULL, completed_at = NULL WHERE scan_id = ?",
(scan.scan_id,),
)
result = add_worker(
workbench_db, scan, status="succeeded" if source == "deep-reducer-result" else "running"
)
result = scan.add_worker(status="succeeded" if source == "deep-reducer-result" else "running")
if source.startswith("deep-reducer"):
with workbench_db:
workbench_db.execute(
@@ -787,7 +771,7 @@ def test_stopped_deep_scan_still_salvages_saved_findings(
result.write_text("{interrupted worker output")
result_bytes = result.read_bytes()
stopped = fail_scan(workbench_api, workbench_db, scan, "Scan interrupted.")
stopped = scan.fail("Scan interrupted.")
assert stopped["progress"]["status"] == "failed"
manifest = json.loads((scan.scan_dir / "scan-manifest.json").read_text())
@@ -801,7 +785,7 @@ def test_stopped_deep_scan_still_salvages_saved_findings(
artifact_names = ("scan-manifest.json", "findings.json")
published = {name: (scan.scan_dir / name).read_bytes() for name in artifact_names}
recovered = recover_scan_results(workbench_api, workbench_db, scan)
recovered = scan.recover()
assert recovered["findingCount"] == len(expected_summaries)
assert {name: (scan.scan_dir / name).read_bytes() for name in artifact_names} == published
if checkpoint is not None:
@@ -811,7 +795,7 @@ def test_stopped_deep_scan_still_salvages_saved_findings(
@pytest.mark.parametrize("source", ["result", "checkpoint", "parent-checkpoint"])
def test_stopped_deep_scan_ignores_non_reducer_sources_without_coverage(
workbench_api, workbench_db, publication_scan, source
workbench_db, publication_scan, source
):
scan = publication_scan()
with workbench_db:
@@ -831,9 +815,7 @@ def test_stopped_deep_scan_ignores_non_reducer_sources_without_coverage(
if source == "parent-checkpoint":
source_path = write_checkpoint(scan.scan_dir / "checkpoints", saved)
else:
result = add_worker(
workbench_db, scan, status="succeeded" if source == "result" else "running"
)
result = scan.add_worker(status="succeeded" if source == "result" else "running")
if source == "result":
result.write_text(json.dumps(saved))
source_path = result
@@ -842,7 +824,7 @@ def test_stopped_deep_scan_ignores_non_reducer_sources_without_coverage(
source_bytes = source_path.read_bytes()
source_relative = source_path.relative_to(scan.scan_dir).as_posix()
stopped = fail_scan(workbench_api, workbench_db, scan, "Scan interrupted.")
stopped = scan.fail("Scan interrupted.")
assert stopped["progress"]["status"] == "failed"
assert stopped["resultsRecoveryNeeded"] is False
@@ -859,7 +841,7 @@ def test_stopped_deep_scan_ignores_non_reducer_sources_without_coverage(
artifact_names = ("scan-manifest.json", "findings.json")
published = {name: (scan.scan_dir / name).read_bytes() for name in artifact_names}
recovered = recover_scan_results(workbench_api, workbench_db, scan)
recovered = scan.recover()
assert recovered["findingCount"] == 1
assert recovered["resultsRecoveryNeeded"] is False
@@ -867,14 +849,12 @@ def test_stopped_deep_scan_ignores_non_reducer_sources_without_coverage(
assert source_path.read_bytes() == source_bytes
def test_standard_publication_preserves_deferred_work(
workbench_api, workbench_db, publication_scan
):
def test_standard_publication_preserves_deferred_work(publication_scan):
scan = publication_scan(mode="standard")
scan.coverage["deferred"] = [{"id": "remaining-review", "reason": "Another surface remains."}]
(scan.scan_dir / "coverage.json").write_text(json.dumps(scan.coverage))
complete(workbench_api, workbench_db, scan)
scan.complete()
assert_published_aggregate(scan)
@@ -901,7 +881,7 @@ def test_deep_publication_write_failure_keeps_original_terminal_cause(
patch.setitem(finalizer_globals, "write_scan_local_bytes", fail_report)
for _ in range(2):
with pytest.raises(SystemExit, match="Synthetic report write interruption"):
complete(workbench_api, workbench_db, scan)
scan.complete()
warnings = json.loads(
workbench_db.execute(
"SELECT completion_warnings_json FROM scans WHERE id = ?", (scan.scan_id,)
@@ -923,7 +903,7 @@ def test_deep_publication_write_failure_keeps_original_terminal_cause(
{"id": "entry", "label": "Entry review", "disposition": "no_issue_found", "receiptRefs": []}
]
(scan.scan_dir / "coverage.json").write_text(json.dumps(scan.coverage))
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
assert completed["progress"]["status"] == "complete"
assert (
workbench_db.execute(
@@ -941,7 +921,7 @@ def test_deep_publication_write_failure_keeps_original_terminal_cause(
@pytest.mark.parametrize("resumed", [False, True])
@pytest.mark.parametrize("scope", ["subdir", "./subdir/", "subdir/extract.py"])
def test_scoped_deep_completion_filters_old_parent_and_preserves_accepted_sources(
workbench_api, workbench_db, publication_scan, resumed, scope
workbench_db, publication_scan, resumed, scope
):
scan = publication_scan(paths=[scope, "background jobs"])
findings = []
@@ -959,7 +939,7 @@ def test_scoped_deep_completion_filters_old_parent_and_preserves_accepted_source
accepted = []
if resumed:
for kind in ("discovery", "dedup"):
result = add_worker(workbench_db, scan)
result = scan.add_worker()
result.write_text(json.dumps({"scanId": scan.scan_id, "findings": findings}))
with workbench_db:
workbench_db.execute(
@@ -968,7 +948,7 @@ def test_scoped_deep_completion_filters_old_parent_and_preserves_accepted_source
(kind, str(result)),
)
accepted.append((result, result.read_bytes()))
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
assert completed["progress"]["status"] == "complete"
paths = [
row["locations"][0]["path"]
@@ -1003,21 +983,19 @@ def test_resumed_sealed_out_of_scope_deep_scan_is_not_rewritten(
names = ["scan-manifest.json", "findings.json", "coverage.json", "report.md"]
original = {name: (scan.scan_dir / name).read_bytes() for name in names}
with pytest.raises(SystemExit, match="sealed Deep scan contains findings outside"):
complete(workbench_api, workbench_db, scan)
scan.complete()
assert {name: (scan.scan_dir / name).read_bytes() for name in names} == original
# Historical sealed reads are retained; this change is not a migration.
workbench_api["finalize_scan"](scan.scan_dir)
assert {name: (scan.scan_dir / name).read_bytes() for name in names} == original
def test_deep_scope_filter_does_not_hide_unsafe_finding_locations(
workbench_api, workbench_db, publication_scan
):
def test_deep_scope_filter_does_not_hide_unsafe_finding_locations(publication_scan):
scan = publication_scan(paths=["subdir", "background jobs"])
scan.findings[0]["locations"] = [{"path": "../outside.py", "startLine": 1}]
(scan.scan_dir / "findings.json").write_text(json.dumps({"findings": scan.findings}))
with pytest.raises(SystemExit, match="path"):
complete(workbench_api, workbench_db, scan)
scan.complete()
manifest = json.loads((scan.scan_dir / "scan-manifest.json").read_text())
assert manifest["scan"].get("status") != "completed"
@@ -1041,7 +1019,7 @@ def test_deep_publication_preserves_original_scope_kinds_after_checkout_changes(
(scan.scan_dir / "findings.json").write_text(json.dumps({"findings": findings}))
accepted = []
for kind in ("discovery", "dedup"):
result = add_worker(workbench_db, scan)
result = scan.add_worker()
result.write_text(json.dumps(saved_draft(scan.scan_id, findings=findings, complete=True)))
with workbench_db:
workbench_db.execute(
@@ -1064,9 +1042,9 @@ def test_deep_publication_preserves_original_scope_kinds_after_checkout_changes(
== file_paths
)
if stopped:
fail_scan(workbench_api, workbench_db, scan, "interrupted")
scan.fail("interrupted")
else:
assert complete(workbench_api, workbench_db, scan)["progress"]["status"] == "complete"
assert scan.complete()["progress"]["status"] == "complete"
expected_paths = ["subdir/extract.py"] + ([] if file_paths else ["subdir/extract.py/generated"])
assert [
item["locations"][0]["path"]
@@ -1095,7 +1073,7 @@ def test_legacy_deep_scope_does_not_reclassify_a_changed_checkout(
target = Path(row["target_path"]) / "subdir"
shutil.rmtree(target)
target.write_text("new checkout file\n")
assert complete(workbench_api, workbench_db, scan)["progress"]["status"] == "complete"
assert scan.complete()["progress"]["status"] == "complete"
findings = json.loads((scan.scan_dir / "findings.json").read_text())["findings"]
assert len(findings) == 1
@@ -1107,22 +1085,18 @@ def test_legacy_deep_scope_does_not_reclassify_a_changed_checkout(
("./subdir/extract.py", "subdir/extract.py/generated"),
],
)
def test_stopped_deep_projection_filters_the_canonical_parent(
workbench_api, workbench_db, publication_scan, scope, location
):
def test_stopped_deep_projection_filters_the_canonical_parent(publication_scan, scope, location):
scan = publication_scan(paths=[scope, "background jobs"])
scan.findings[0]["locations"] = [{"path": location, "startLine": 1}]
(scan.scan_dir / "findings.json").write_text(json.dumps({"findings": scan.findings}))
stopped = fail_scan(workbench_api, workbench_db, scan, "Scan interrupted.")
stopped = scan.fail("Scan interrupted.")
assert stopped["progress"]["status"] == "failed"
assert stopped["findingCount"] == 0
assert json.loads((scan.scan_dir / "findings.json").read_text())["findings"] == []
@pytest.mark.parametrize("scope", ["subdir/extract.py", "./subdir/extract.py"])
def test_stopped_file_scope_filters_siblings_before_assigning_identity(
workbench_api, workbench_db, publication_scan, scope
):
def test_stopped_file_scope_filters_siblings_before_assigning_identity(publication_scan, scope):
scan = publication_scan(paths=[scope])
finding = copy.deepcopy(scan.findings[0])
for key in ("identity", "findingId", "occurrenceId", "fingerprints"):
@@ -1137,13 +1111,13 @@ def test_stopped_file_scope_filters_siblings_before_assigning_identity(
checkpoint_bytes = checkpoint.read_bytes()
for name in ("scan-manifest.json", "findings.json", "coverage.json"):
(scan.scan_dir / name).unlink()
fail_scan(workbench_api, workbench_db, scan, "Interrupted.")
scan.fail("Interrupted.")
findings = json.loads((scan.scan_dir / "findings.json").read_text())["findings"]
assert len(findings) == 1
assert findings[0]["locations"][0]["path"] == "subdir/extract.py"
assert findings[0]["identity"] == {"anchor": "candidate-review"}
names = ("scan-manifest.json", "findings.json")
published = {name: (scan.scan_dir / name).read_bytes() for name in names}
recover_scan_results(workbench_api, workbench_db, scan)
scan.recover()
assert {name: (scan.scan_dir / name).read_bytes() for name in names} == published
assert checkpoint.read_bytes() == checkpoint_bytes
@@ -8,13 +8,17 @@ import uuid
from argparse import Namespace
import pytest
from test_deep_scan_successful_publication import add_worker
from test_deep_scan_successful_publication import publication_scan as publication_scan
from workbench_test_support import read_review_state, write_checkpoint
from workbench_test_support import (
read_review_state,
select_checkpoint,
write_checkpoint,
write_result_draft,
)
@pytest.fixture
def stop_scan(workbench_api, workbench_db, monkeypatch):
def stop_scan(workbench_api, monkeypatch):
saved = workbench_api["saved_results"]
def fail_publication(*args, **kwargs):
@@ -24,13 +28,7 @@ def stop_scan(workbench_api, workbench_db, monkeypatch):
with monkeypatch.context() as patch:
if interrupt_publication:
patch.setattr(saved, "_write_prepared_scan_finalization", fail_publication)
stopped = saved.fail_scan(
workbench_api["_WORKBENCH_DB_CONTEXT"],
workbench_db,
Namespace(
scan_id=scan.scan_id, claim_token=None, cost_json=None, message="Stopped."
),
)["scan"]
stopped = scan.fail()
assert stopped["resultsRecoveryNeeded"] is interrupt_publication
return stop
@@ -41,7 +39,6 @@ def stop_scan(workbench_api, workbench_db, monkeypatch):
@pytest.mark.parametrize("newer_parent", [False, True])
@pytest.mark.parametrize("retry_publication", [False, True])
def test_parent_candidate_outcome_compares_headless_worker_chronology(
workbench_api,
workbench_db,
publication_scan,
stop_scan,
@@ -51,7 +48,7 @@ def test_parent_candidate_outcome_compares_headless_worker_chronology(
retry_publication,
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_id = result.parent.name
with workbench_db:
workbench_db.execute(
@@ -77,15 +74,11 @@ def test_parent_candidate_outcome_compares_headless_worker_chronology(
"deferred": [task],
},
}
result.write_text(json.dumps(draft))
os.utime(result, ns=(300, 300))
write_result_draft(result, draft, mtime_ns=300)
originals = {result: result.read_bytes()}
if has_head:
checkpoint = write_checkpoint(result.parent / "checkpoints", draft)
os.utime(checkpoint, ns=(300, 300))
head = result.parent / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(300, 300))
checkpoint = write_checkpoint(result.parent / "checkpoints", draft, mtime_ns=300)
head = select_checkpoint(result.parent, checkpoint, mtime_ns=300)
originals.update({path: path.read_bytes() for path in (checkpoint, head)})
(scan.scan_dir / "findings.json").write_text(json.dumps({"findings": []}))
parent = scan.scan_dir / "coverage.json"
@@ -114,9 +107,7 @@ def test_parent_candidate_outcome_compares_headless_worker_chronology(
modified = 400 if newer_parent else 200
os.utime(parent, ns=(modified, modified))
stop_scan(scan, retry_publication)
workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)
scan.recover()
coverage = read_review_state(workbench_db, scan.scan_dir)
pending = [row for row in coverage["deferred"] if row.get("reason") == task["reason"]]
assert len(pending) == int(not newer_parent)
@@ -133,10 +124,10 @@ def test_parent_candidate_outcome_compares_headless_worker_chronology(
@pytest.mark.parametrize("tagged_surface", [False, True])
@pytest.mark.parametrize("merge_state", ["buffered", "merging", "merged"])
def test_missing_deferred_projection_links_first_duplicate_surface(
workbench_api, workbench_db, publication_scan, parent_surfaces, merge_state, tagged_surface
workbench_db, publication_scan, parent_surfaces, merge_state, tagged_surface
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_id = result.parent.name
with workbench_db:
workbench_db.execute(
@@ -229,20 +220,13 @@ def test_missing_deferred_projection_links_first_duplicate_surface(
earlier["coverage"]["resolvedDeferred"] = [
{"id": deferred["id"], "reason": "Earlier source follow-up completed."}
]
checkpoint = write_checkpoint(result.parent / "checkpoints", earlier)
os.utime(checkpoint, ns=(100, 100))
write_checkpoint(result.parent / "checkpoints", earlier, mtime_ns=100)
os.utime(result, ns=(300, 300))
if parent_surfaces != "no-parent":
os.utime(scan.scan_dir / "coverage.json", ns=(200, 200))
workbench_api["saved_results"].fail_scan(
workbench_api["_WORKBENCH_DB_CONTEXT"],
workbench_db,
Namespace(scan_id=scan.scan_id, claim_token=None, cost_json=None, message="Stopped."),
)
scan.fail()
published = (scan.scan_dir / "scan-manifest.json").read_bytes()
recovered = workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)["scan"]
recovered = scan.recover()
assert recovered["resultsRecoveryNeeded"] is False
assert (scan.scan_dir / "scan-manifest.json").read_bytes() == published
coverage = read_review_state(workbench_db, scan.scan_dir)
@@ -282,9 +266,7 @@ def test_missing_deferred_projection_links_first_duplicate_surface(
},
)
original_late = late.read_bytes()
workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)
scan.recover()
manifest = json.loads((scan.scan_dir / "scan-manifest.json").read_bytes())
assert late.relative_to(scan.scan_dir).as_posix() in manifest["scan"]["preservedSources"]
assert read_review_state(workbench_db, scan.scan_dir) == coverage
@@ -294,10 +276,10 @@ def test_missing_deferred_projection_links_first_duplicate_surface(
@pytest.mark.parametrize("parent_review", [False, True])
def test_missing_accepted_result_does_not_project_an_archived_attempt(
workbench_api, workbench_db, publication_scan, parent_review
workbench_db, publication_scan, parent_review
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_id = result.parent.name
result = scan.scan_dir / "artifacts" / worker_id / "output" / "result.json"
result.parent.mkdir(parents=True)
@@ -344,14 +326,8 @@ def test_missing_accepted_result_does_not_project_an_archived_attempt(
else:
for name in ("scan-manifest.json", "findings.json", "coverage.json"):
(scan.scan_dir / name).unlink()
workbench_api["saved_results"].fail_scan(
workbench_api["_WORKBENCH_DB_CONTEXT"],
workbench_db,
Namespace(scan_id=scan.scan_id, claim_token=None, cost_json=None, message="Stopped."),
)
workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)
scan.fail()
scan.recover()
coverage = read_review_state(workbench_db, scan.scan_dir)
surface = next(
item for item in coverage["surfaces"] if item["label"] == "Prior unfinished review"
@@ -370,11 +346,11 @@ def test_missing_accepted_result_does_not_project_an_archived_attempt(
@pytest.mark.parametrize("failed_first", [False, True])
def test_failed_worker_reviews_do_not_replace_accepted_reviews(
workbench_api, workbench_db, publication_scan, failed_first
workbench_db, publication_scan, failed_first
):
scan = publication_scan()
# These fixture rows share created_at; recovery reads them in worker-ID order.
first, second = sorted([add_worker(workbench_db, scan), add_worker(workbench_db, scan)])
first, second = sorted([scan.add_worker(), scan.add_worker()])
failed, accepted = (first, second) if failed_first else (second, first)
with workbench_db:
workbench_db.execute(
@@ -426,11 +402,7 @@ def test_failed_worker_reviews_do_not_replace_accepted_reviews(
drafts[label] = draft
for name in ("scan-manifest.json", "findings.json", "coverage.json"):
(scan.scan_dir / name).unlink()
workbench_api["saved_results"].fail_scan(
workbench_api["_WORKBENCH_DB_CONTEXT"],
workbench_db,
Namespace(scan_id=scan.scan_id, claim_token=None, cost_json=None, message="Stopped."),
)
scan.fail()
coverage = read_review_state(workbench_db, scan.scan_dir)
assert coverage["reviews"] == [review]
for field in ("surfaces", "deferred", "explicitExclusions", "openQuestions"):
@@ -447,9 +419,7 @@ def test_failed_worker_reviews_do_not_replace_accepted_reviews(
item.get("reason") == "accepted source needs proof." for item in coverage["deferred"]
)
published = (scan.scan_dir / "scan-manifest.json").read_bytes()
workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)
scan.recover()
assert (scan.scan_dir / "scan-manifest.json").read_bytes() == published
late = write_checkpoint(
accepted.parent / "checkpoints",
@@ -460,9 +430,7 @@ def test_failed_worker_reviews_do_not_replace_accepted_reviews(
},
)
originals[late] = late.read_bytes()
recovered = workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)["scan"]
recovered = scan.recover()
assert recovered["resultsRecoveryNeeded"] is False
assert read_review_state(workbench_db, scan.scan_dir) == coverage
manifest = json.loads((scan.scan_dir / "scan-manifest.json").read_text())
@@ -475,7 +443,6 @@ def test_failed_worker_reviews_do_not_replace_accepted_reviews(
@pytest.mark.parametrize("retained_deferred", [False, True])
@pytest.mark.parametrize("idless_surface", [False, True])
def test_missing_projection_keeps_surface_links_and_independent_reviews(
workbench_api,
workbench_db,
publication_scan,
worker_count,
@@ -503,7 +470,7 @@ def test_missing_projection_keeps_surface_links_and_independent_reviews(
) + [surface]
reviews, surfaces, deferred_records, originals = [], [], [], {}
for _ in range(worker_count):
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_id = result.parent.name
reviews.append({"workerId": worker_id, "attempt": 1, "completeness": "partial"})
if idless_surface:
@@ -562,21 +529,8 @@ def test_missing_projection_keeps_surface_links_and_independent_reviews(
}
)
)
saved = workbench_api["saved_results"]
context = workbench_api["_WORKBENCH_DB_CONTEXT"]
saved.fail_scan(
context,
workbench_db,
Namespace(
scan_id=scan.scan_id,
claim_token=None,
cost_json=None,
message="Stopped.",
),
)
recovered = saved.recover_scan_results(context, workbench_db, Namespace(scan_id=scan.scan_id))[
"scan"
]
scan.fail()
recovered = scan.recover()
assert recovered["resultsRecoveryNeeded"] is False
coverage = read_review_state(workbench_db, scan.scan_dir)
pending = [item for item in coverage["deferred"] if item.get("reason") == deferred["reason"]]
@@ -601,17 +555,17 @@ def test_missing_projection_keeps_surface_links_and_independent_reviews(
assert "completeness" not in coverage
assert all(path.read_bytes() == data for path, data in originals.items())
published = (scan.scan_dir / "scan-manifest.json").read_bytes()
saved.recover_scan_results(context, workbench_db, Namespace(scan_id=scan.scan_id))
scan.recover()
assert (scan.scan_dir / "scan-manifest.json").read_bytes() == published
@pytest.mark.parametrize("attempt", [1, 2])
@pytest.mark.parametrize("retry_publication", [False, True])
def test_previous_attempt_resolution_does_not_clear_current_gap(
workbench_api, workbench_db, publication_scan, attempt, retry_publication, stop_scan
workbench_db, publication_scan, attempt, retry_publication, stop_scan
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_id = result.parent.name
deferred = {"candidateId": "candidate-1", "reason": "Validate the current attempt."}
result.write_text(
@@ -658,9 +612,7 @@ def test_previous_attempt_resolution_does_not_clear_current_gap(
parent_observed = observed + 2_000_000_000
os.utime(parent_path, ns=(parent_observed, parent_observed))
stop_scan(scan, retry_publication)
recovered = workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)["scan"]
recovered = scan.recover()
assert recovered["resultsRecoveryNeeded"] is False
coverage = read_review_state(workbench_db, scan.scan_dir)
pending = [item for item in coverage["deferred"] if item.get("reason") == deferred["reason"]]
@@ -670,10 +622,10 @@ def test_previous_attempt_resolution_does_not_clear_current_gap(
@pytest.mark.parametrize("selected_checkpoint", [False, True])
def test_recovery_compares_open_questions_using_canonical_normalization(
workbench_api, workbench_db, publication_scan, selected_checkpoint
workbench_db, publication_scan, selected_checkpoint
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_id = result.parent.name
questions = [
" Which deployment controls apply? ",
@@ -694,9 +646,7 @@ def test_recovery_compares_open_questions_using_canonical_normalization(
checkpoint = write_checkpoint(result.parent / "checkpoints", json.loads(result.read_text()))
os.utime(result, ns=(100, 100))
os.utime(checkpoint, ns=(150, 150))
(result.parent / "checkpoint-head.json").write_text(
json.dumps({"checkpoint": checkpoint.name})
)
select_checkpoint(result.parent, checkpoint)
projected = [
{"question": question, "provenance": {"workerId": worker_id, "attempt": 1}}
for question in ("Which deployment controls apply?", "Which runtime settings apply?")
@@ -710,14 +660,8 @@ def test_recovery_compares_open_questions_using_canonical_normalization(
}
)
)
workbench_api["saved_results"].fail_scan(
workbench_api["_WORKBENCH_DB_CONTEXT"],
workbench_db,
Namespace(scan_id=scan.scan_id, claim_token=None, cost_json=None, message="Stopped."),
)
recovered = workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)["scan"]
scan.fail()
recovered = scan.recover()
assert recovered["resultsRecoveryNeeded"] is False
coverage = read_review_state(workbench_db, scan.scan_dir)
assert coverage["openQuestions"] == projected
@@ -727,10 +671,10 @@ def test_recovery_compares_open_questions_using_canonical_normalization(
@pytest.mark.parametrize("parent_projection", ["raw", "projected", "missing"])
@pytest.mark.parametrize("retry_publication", [False, True])
def test_rejected_retry_preserves_original_finding_history(
workbench_api, workbench_db, publication_scan, stop_scan, parent_projection, retry_publication
workbench_db, publication_scan, stop_scan, parent_projection, retry_publication
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_id = result.parent.name
candidate_id = "candidate-1"
finding = copy.deepcopy(scan.findings[0])
@@ -766,7 +710,7 @@ def test_rejected_retry_preserves_original_finding_history(
)
with workbench_db:
workbench_db.execute("UPDATE deep_scan_workers SET attempt = 2 WHERE id = ?", (worker_id,))
other_result = add_worker(workbench_db, scan)
other_result = scan.add_worker()
other_result.write_text(
json.dumps({"scanId": scan.scan_id, "findings": [], "coverage": scan.coverage})
)
@@ -808,9 +752,7 @@ def test_rejected_retry_preserves_original_finding_history(
(scan.scan_dir / name).unlink()
originals = {path: path.read_bytes() for path in (previous, result, other_result)}
stop_scan(scan, retry_publication)
recovered = workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)["scan"]
recovered = scan.recover()
assert recovered["resultsRecoveryNeeded"] is False
assert recovered["findingCount"] == 0
coverage = read_review_state(workbench_db, scan.scan_dir)
@@ -824,9 +766,7 @@ def test_rejected_retry_preserves_original_finding_history(
assert "previousFindings" not in item
assert all(path.read_bytes() == original for path, original in originals.items())
published = (scan.scan_dir / "scan-manifest.json").read_bytes()
workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)
scan.recover()
assert (scan.scan_dir / "scan-manifest.json").read_bytes() == published
@@ -835,11 +775,11 @@ def test_rejected_retry_preserves_original_finding_history(
"recovery", [None, "retry", "missing", "changed", "incomplete", "late", "fallback-late"]
)
def test_stopped_recovery_keeps_current_parent_projection(
workbench_api, workbench_db, publication_scan, stop_scan, older_complete, recovery
workbench_db, publication_scan, stop_scan, older_complete, recovery
):
retry_publication = recovery not in {None, "fallback-late"}
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_id = result.parent.name
deferred = {"candidateId": "candidate-1", "reason": "The current review remains unresolved."}
result.write_text(
@@ -852,7 +792,7 @@ def test_stopped_recovery_keeps_current_parent_projection(
}
)
)
reducer = add_worker(workbench_db, scan)
reducer = scan.add_worker()
reducer.write_text(json.dumps({"scanId": scan.scan_id, "findings": []}))
reducer_checkpoint = write_checkpoint(
reducer.parent / "checkpoints", json.loads(reducer.read_text())
@@ -944,9 +884,7 @@ def test_stopped_recovery_keeps_current_parent_projection(
},
)
original_sources[late] = late.read_bytes()
recovered = workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)["scan"]
recovered = scan.recover()
assert recovered["resultsRecoveryNeeded"] is False
coverage = read_review_state(workbench_db, scan.scan_dir)
expected_questions = [] if recovery == "fallback-late" else [question]
@@ -968,18 +906,16 @@ def test_stopped_recovery_keeps_current_parent_projection(
assert all(path.read_bytes() == original for path, original in original_sources.items())
assert all(path.read_bytes() == original for path, original in frozen_sources.items())
published = (scan.scan_dir / "scan-manifest.json").read_bytes()
workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)
scan.recover()
assert (scan.scan_dir / "scan-manifest.json").read_bytes() == published
@pytest.mark.parametrize("select_head", [False, True])
def test_matching_accepted_checkpoint_preserves_receipt_path(
workbench_api, workbench_db, publication_scan, select_head
workbench_db, publication_scan, select_head
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_id = result.parent.name
result = (
scan.scan_dir
@@ -1021,17 +957,11 @@ def test_matching_accepted_checkpoint_preserves_receipt_path(
checkpoint = write_checkpoint(result.parent / "checkpoints", draft)
os.utime(result, ns=(100, 100))
os.utime(checkpoint, ns=(150, 150))
head = result.parent / "checkpoint-head.json"
if select_head:
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(200, 200))
select_checkpoint(result.parent, checkpoint, mtime_ns=200)
for name in ("scan-manifest.json", "findings.json", "coverage.json"):
(scan.scan_dir / name).unlink()
workbench_api["saved_results"].fail_scan(
workbench_api["_WORKBENCH_DB_CONTEXT"],
workbench_db,
Namespace(scan_id=scan.scan_id, claim_token=None, cost_json=None, message="Stopped."),
)
scan.fail()
coverage = read_review_state(workbench_db, scan.scan_dir)
matching = [row for row in coverage["surfaces"] if row.get("label") == "Accepted source review"]
assert matching
@@ -1045,10 +975,10 @@ def test_matching_accepted_checkpoint_preserves_receipt_path(
@pytest.mark.parametrize("retry_publication", [False, True])
def test_accepted_worker_missing_completeness_keeps_valid_findings(
workbench_api, workbench_db, publication_scan, stop_scan, retry_publication
workbench_db, publication_scan, stop_scan, retry_publication
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_id = result.parent.name
finding = copy.deepcopy(scan.findings[0])
finding["summary"] = "Synthetic accepted worker evidence."
@@ -1067,9 +997,7 @@ def test_accepted_worker_missing_completeness_keeps_valid_findings(
)
original = result.read_bytes()
stop_scan(scan, retry_publication)
recovered = workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)["scan"]
recovered = scan.recover()
assert recovered["resultsRecoveryNeeded"] is False
findings = json.loads((scan.scan_dir / "findings.json").read_text())["findings"]
assert any(row["summary"] == finding["summary"] for row in findings)
@@ -1081,10 +1009,10 @@ def test_accepted_worker_missing_completeness_keeps_valid_findings(
@pytest.mark.parametrize("retry_publication", [False, True])
def test_idless_accepted_surface_matches_projection_after_checkpoint_id_inference(
workbench_api, workbench_db, publication_scan, stop_scan, retry_publication
workbench_db, publication_scan, stop_scan, retry_publication
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_id = result.parent.name
surface = {
"label": "Accepted source review",
@@ -1105,8 +1033,8 @@ def test_idless_accepted_surface_matches_projection_after_checkpoint_id_inferenc
"complete": False,
"coverage": {**scan.coverage, "surfaces": [{**surface, "id": "older-source-id"}]},
},
mtime_ns=100,
)
os.utime(checkpoint, ns=(100, 100))
os.utime(result, ns=(200, 200))
projected = {
**surface,
@@ -1124,16 +1052,12 @@ def test_idless_accepted_surface_matches_projection_after_checkpoint_id_inferenc
)
originals = {path: path.read_bytes() for path in (result, checkpoint)}
stop_scan(scan, retry_publication)
recovered = workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)["scan"]
recovered = scan.recover()
assert recovered["resultsRecoveryNeeded"] is False
coverage = read_review_state(workbench_db, scan.scan_dir)
assert coverage["surfaces"] == [projected]
published = (scan.scan_dir / "scan-manifest.json").read_bytes()
workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)
scan.recover()
assert (scan.scan_dir / "scan-manifest.json").read_bytes() == published
assert all(path.read_bytes() == original for path, original in originals.items())
@@ -1142,8 +1066,6 @@ def test_idless_accepted_surface_matches_projection_after_checkpoint_id_inferenc
@pytest.mark.parametrize("retry_publication", [False, True])
@pytest.mark.parametrize("selected_checkpoint", [False, True])
def test_parent_candidate_provenance_cannot_override_accepted_worker_evidence(
workbench_api,
workbench_db,
publication_scan,
stop_scan,
claimed_worker,
@@ -1151,7 +1073,7 @@ def test_parent_candidate_provenance_cannot_override_accepted_worker_evidence(
selected_checkpoint,
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_id = result.parent.name
finding = copy.deepcopy(scan.findings[0])
finding["provenance"]["candidateId"] = "source-candidate"
@@ -1169,8 +1091,7 @@ def test_parent_candidate_provenance_cannot_override_accepted_worker_evidence(
originals = {result: result.read_bytes()}
if selected_checkpoint:
checkpoint = write_checkpoint(result.parent / "checkpoints", json.loads(result.read_text()))
head = result.parent / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
head = select_checkpoint(result.parent, checkpoint)
pending_result = json.loads(result.read_text())
pending_result["findings"] = []
pending_result["coverage"] = {
@@ -1184,8 +1105,7 @@ def test_parent_candidate_provenance_cannot_override_accepted_worker_evidence(
}
],
}
result.write_text(json.dumps(pending_result))
os.utime(result, ns=(100, 100))
write_result_draft(result, pending_result, mtime_ns=100)
os.utime(checkpoint, ns=(300, 300))
os.utime(head, ns=(300, 300))
originals = {path: path.read_bytes() for path in (result, checkpoint, head)}
@@ -1213,9 +1133,7 @@ def test_parent_candidate_provenance_cannot_override_accepted_worker_evidence(
)
os.utime(scan.scan_dir / "coverage.json", ns=(400, 400))
stop_scan(scan, retry_publication)
recovered = workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)["scan"]
recovered = scan.recover()
assert recovered["resultsRecoveryNeeded"] is False
findings = json.loads((scan.scan_dir / "findings.json").read_text())["findings"]
assert [row["summary"] for row in findings] == [finding["summary"]]
@@ -1225,10 +1143,10 @@ def test_parent_candidate_provenance_cannot_override_accepted_worker_evidence(
@pytest.mark.parametrize("other_worker", [False, True])
@pytest.mark.parametrize("retry_publication", [False, True])
def test_projected_generic_closure_updates_parent_copy_in_its_worker_namespace(
workbench_api, workbench_db, publication_scan, stop_scan, other_worker, retry_publication
workbench_db, publication_scan, stop_scan, other_worker, retry_publication
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_id = result.parent.name
surface = {
"id": "source-surface",
@@ -1277,7 +1195,7 @@ def test_projected_generic_closure_updates_parent_copy_in_its_worker_namespace(
}
)
)
closure_result = add_worker(workbench_db, scan) if other_worker else result
closure_result = scan.add_worker() if other_worker else result
if other_worker:
closure_result.write_text(json.dumps({**draft, "coverage": scan.coverage}))
closure = {
@@ -1293,14 +1211,10 @@ def test_projected_generic_closure_updates_parent_copy_in_its_worker_namespace(
os.utime(result, ns=(100, 100))
os.utime(parent_coverage, ns=(200, 200))
os.utime(checkpoint, ns=(300, 300))
(closure_result.parent / "checkpoint-head.json").write_text(
json.dumps({"checkpoint": checkpoint.name})
)
select_checkpoint(closure_result.parent, checkpoint)
originals = {path: path.read_bytes() for path in {result, closure_result, checkpoint}}
stop_scan(scan, retry_publication)
workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)
scan.recover()
coverage = read_review_state(workbench_db, scan.scan_dir)
pending = [row for row in coverage["deferred"] if row.get("reason") == task["reason"]]
assert len(pending) == int(other_worker)
@@ -1315,9 +1229,7 @@ def test_projected_generic_closure_updates_parent_copy_in_its_worker_namespace(
)
assert all(path.read_bytes() == value for path, value in originals.items())
published = (scan.scan_dir / "scan-manifest.json").read_bytes()
workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)
scan.recover()
assert (scan.scan_dir / "scan-manifest.json").read_bytes() == published
@@ -1325,7 +1237,6 @@ def test_projected_generic_closure_updates_parent_copy_in_its_worker_namespace(
@pytest.mark.parametrize("retry_publication", [False, True])
@pytest.mark.parametrize("parent_review", ["earlier", "copied-later", "changed-later"])
def test_selected_candidate_outcome_removes_its_projected_parent_pending_rows(
workbench_api,
workbench_db,
publication_scan,
stop_scan,
@@ -1334,7 +1245,7 @@ def test_selected_candidate_outcome_removes_its_projected_parent_pending_rows(
parent_review,
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_id = result.parent.name
candidate = "source-candidate"
surface = {
@@ -1413,14 +1324,10 @@ def test_selected_candidate_outcome_removes_its_projected_parent_pending_rows(
modified = 200 if parent_review == "earlier" else 400
os.utime(coverage_path, ns=(modified, modified))
os.utime(checkpoint, ns=(300, 300))
head = result.parent / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(300, 300))
select_checkpoint(result.parent, checkpoint, mtime_ns=300)
originals = {path: path.read_bytes() for path in (result, checkpoint)}
stop_scan(scan, retry_publication)
workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)
scan.recover()
coverage = read_review_state(workbench_db, scan.scan_dir)
if parent_review != "changed-later":
assert not any(row.get("reason") == task["reason"] for row in coverage["deferred"])
@@ -1436,9 +1343,7 @@ def test_selected_candidate_outcome_removes_its_projected_parent_pending_rows(
assert len(findings) == int(disposition == "reported")
assert all(path.read_bytes() == value for path, value in originals.items())
published = (scan.scan_dir / "scan-manifest.json").read_bytes()
workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)
scan.recover()
assert (scan.scan_dir / "scan-manifest.json").read_bytes() == published
@@ -1458,10 +1363,10 @@ def test_selected_candidate_outcome_removes_its_projected_parent_pending_rows(
],
)
def test_selected_worker_projection_keeps_links_and_pending_authority(
workbench_api, workbench_db, publication_scan, stop_scan, change, retry_publication
workbench_db, publication_scan, stop_scan, change, retry_publication
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_id = result.parent.name
prefix = f"{worker_id}-attempt-1"
candidate = "source-candidate"
@@ -1612,11 +1517,8 @@ def test_selected_worker_projection_keeps_links_and_pending_authority(
"disposition": "rejected",
}
)
checkpoint = write_checkpoint(result.parent / "checkpoints", updated)
os.utime(checkpoint, ns=(300, 300))
(result.parent / "checkpoint-head.json").write_text(
json.dumps({"checkpoint": checkpoint.name})
)
checkpoint = write_checkpoint(result.parent / "checkpoints", updated, mtime_ns=300)
select_checkpoint(result.parent, checkpoint)
os.utime(result, ns=(100, 100))
os.utime(coverage_path, ns=(200, 200))
if change == "reopened mixed receipts":
@@ -1629,9 +1531,7 @@ def test_selected_worker_projection_keeps_links_and_pending_authority(
path: path.read_bytes() for path in [result] + ([checkpoint] if checkpoint else [])
}
stop_scan(scan, retry_publication)
workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)
scan.recover()
coverage = read_review_state(workbench_db, scan.scan_dir)
pending = [row for row in coverage["deferred"] if row.get("reason") == task["reason"]]
assert len(pending) == int(
@@ -1673,9 +1573,7 @@ def test_selected_worker_projection_keeps_links_and_pending_authority(
}
assert all(path.read_bytes() == content for path, content in originals.items())
published = (scan.scan_dir / "scan-manifest.json").read_bytes()
workbench_api["saved_results"].recover_scan_results(
workbench_api["_WORKBENCH_DB_CONTEXT"], workbench_db, Namespace(scan_id=scan.scan_id)
)
scan.recover()
assert (scan.scan_dir / "scan-manifest.json").read_bytes() == published
@@ -1728,7 +1626,7 @@ def test_linked_archived_receipts_preserve_accepted_surface_links(
workbench_api, workbench_db, publication_scan, stop_scan, spelling, parent, retry
):
scan = publication_scan()
initial = add_worker(workbench_db, scan)
initial = scan.add_worker()
worker_id = initial.parent.name
output = scan.scan_dir / "artifacts" / worker_id / "output"
output.mkdir(parents=True)
@@ -1791,8 +1689,7 @@ def test_linked_archived_receipts_preserve_accepted_surface_links(
elif spelling == "omitted":
selected["coverage"]["surfaces"] = []
checkpoint = write_checkpoint(output / "checkpoints", selected)
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
head = select_checkpoint(output, checkpoint)
for path, stamp in ((result, 100), (coverage_path, 200), (checkpoint, 300), (head, 300)):
os.utime(path, ns=(stamp, stamp))
if not parent:
@@ -1837,7 +1734,7 @@ def test_recovery_projects_receipts_from_their_source_directory(
retry,
):
scan = publication_scan()
initial = add_worker(workbench_db, scan)
initial = scan.add_worker()
worker_id = initial.parent.name
output = scan.scan_dir / "artifacts" / worker_id / "output"
output.mkdir(parents=True)
@@ -1908,10 +1805,10 @@ def test_recovery_projects_receipts_from_their_source_directory(
def test_deferred_projection_preserves_each_referenced_source_surface(
workbench_api, workbench_db, publication_scan
workbench_db, publication_scan
):
scan = publication_scan()
result = add_worker(workbench_db, scan)
result = scan.add_worker()
worker_id = result.parent.name
surfaces = [
{
@@ -1941,11 +1838,7 @@ def test_deferred_projection_preserves_each_referenced_source_surface(
original = result.read_bytes()
for name in ("scan-manifest.json", "findings.json", "coverage.json"):
(scan.scan_dir / name).unlink()
workbench_api["saved_results"].fail_scan(
workbench_api["_WORKBENCH_DB_CONTEXT"],
workbench_db,
Namespace(scan_id=scan.scan_id, claim_token=None, cost_json=None, message="Stopped."),
)
scan.fail()
coverage = read_review_state(workbench_db, scan.scan_dir)
projected = {row["provenance"]["sourceId"]: row for row in coverage["surfaces"]}
assert set(projected) == {surface["id"] for surface in surfaces}
@@ -10,6 +10,7 @@ from workbench_test_support import (
saved_binding,
saved_discovery_worker,
saved_draft,
select_checkpoint,
write_checkpoint,
)
@@ -37,8 +38,7 @@ def saved_worker(root: Path, worker_id: str, *, headed: bool = False):
result.write_text(json.dumps(complete))
observed(result, 20)
if headed:
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
head = select_checkpoint(output, checkpoint)
observed(head, 20)
worker = saved_discovery_worker(output, worker_id, 2)
worker.update(status="succeeded", result_manifest_path=str(result))
@@ -103,8 +103,7 @@ def test_worker_reopening_invalidates_its_copied_parent_closeout(
reopened = {"id": "review-a", "reason": "New evidence requires another review."}
checkpoint = write_checkpoint(output / "checkpoints", saved_draft(SCAN_ID, deferred=[reopened]))
observed(checkpoint, reopened_at)
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
head = select_checkpoint(output, checkpoint)
observed(head, reopened_at)
coverage = recover(tmp_path, workbench_api["saved_results"], [worker])
assert sorted(coverage.get("resolvedDeferred", []), key=lambda row: row["id"]) == (
@@ -7,13 +7,14 @@ import os
from argparse import Namespace
import pytest
from test_deep_scan_successful_publication import add_worker, complete
from test_deep_scan_successful_publication import publication_scan as publication_scan
from workbench_test_support import (
read_review_state,
saved_draft,
select_checkpoint,
sort_checkpoint_entries,
write_checkpoint,
write_result_draft,
)
@@ -69,12 +70,10 @@ def test_canonical_candidate_resolution_keeps_legacy_checkpoint_authority(
scan.scan_id,
deferred=[{"candidateId": "candidate-review", "reason": "Validation is pending."}],
)
checkpoint = write_checkpoint(scan.scan_dir / "checkpoints", pending)
os.utime(checkpoint, ns=(pending_time, pending_time))
checkpoint = write_checkpoint(scan.scan_dir / "checkpoints", pending, mtime_ns=pending_time)
canonical_disposition(scan, disposition, complete_marker)
original = checkpoint.read_bytes()
saved = workbench_api["saved_results"]
context = workbench_api["_WORKBENCH_DB_CONTEXT"]
prepared_coverage = []
write = saved._write_prepared_scan_finalization
@@ -85,18 +84,12 @@ def test_canonical_candidate_resolution_keeps_legacy_checkpoint_authority(
return write(prepared, **kwargs)
if flow in {"complete", "prepare"}:
completed = complete(workbench_api, workbench_db, scan, prepare_only=flow == "prepare")
completed = scan.complete(prepare_only=flow == "prepare")
assert completed["progress"]["status"] == ("running" if flow == "prepare" else "complete")
else:
with monkeypatch.context() as patch:
patch.setattr(saved, "_write_prepared_scan_finalization", publish)
saved.fail_scan(
context,
workbench_db,
Namespace(
scan_id=scan.scan_id, claim_token=None, cost_json=None, message="Stopped."
),
)
scan.fail()
if flow == "interrupted-stop":
row = workbench_db.execute(
"SELECT * FROM scans WHERE id = ?", (scan.scan_id,)
@@ -107,13 +100,7 @@ def test_canonical_candidate_resolution_keeps_legacy_checkpoint_authority(
# later file-authored draft reopens this candidate.
late = {**scan.coverage, "deferred": pending["coverage"]["deferred"]}
(scan.scan_dir / "coverage.json").write_text(json.dumps(late))
saved.preserve_scan_results(
context,
workbench_db,
Namespace(
scan_id=scan.scan_id, claim_token=None, thread_id=None, coordinator_generation=None
),
)
scan.preserve()
coverage = read_review_state(workbench_db, scan.scan_dir)
assert "completeness" not in coverage
for document in [coverage, *prepared_coverage]:
@@ -127,9 +114,7 @@ def test_canonical_candidate_resolution_keeps_legacy_checkpoint_authority(
)
if flow in {"stop", "interrupted-stop"}:
before = (scan.scan_dir / "scan-manifest.json").read_bytes()
recovered = saved.recover_scan_results(
context, workbench_db, Namespace(scan_id=scan.scan_id)
)["scan"]
recovered = scan.recover()
assert not recovered["resultsRecoveryNeeded"]
assert (scan.scan_dir / "scan-manifest.json").read_bytes() == before
assert read_review_state(workbench_db, scan.scan_dir) == coverage
@@ -145,24 +130,16 @@ def test_accepted_pending_root_tie_survives_canonical_disposition(
scan.scan_id,
deferred=[{"candidateId": "candidate-review", "reason": "Accepted pending review."}],
)
checkpoint = write_checkpoint(scan.scan_dir / "checkpoints", pending)
os.utime(checkpoint, ns=(100, 100))
head = scan.scan_dir / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(200, 200))
checkpoint = write_checkpoint(scan.scan_dir / "checkpoints", pending, mtime_ns=100)
select_checkpoint(scan.scan_dir, checkpoint, mtime_ns=200)
saved = workbench_api["saved_results"]
saved._capture_saved_source(scan.scan_dir, "checkpoint-head.json", scan.scan_id)
canonical_disposition(scan, disposition, True)
context = workbench_api["_WORKBENCH_DB_CONTEXT"]
saved.fail_scan(
context,
workbench_db,
Namespace(scan_id=scan.scan_id, claim_token=None, cost_json=None, message="Stopped."),
)
scan.fail()
coverage = read_review_state(workbench_db, scan.scan_dir)
assert "completeness" not in coverage
assert any(row.get("candidateId") == "candidate-review" for row in coverage["deferred"])
saved.recover_scan_results(context, workbench_db, Namespace(scan_id=scan.scan_id))
scan.recover()
assert read_review_state(workbench_db, scan.scan_dir) == coverage
@@ -184,19 +161,15 @@ def test_restored_root_observation_keeps_tied_pending_payload(
_, terminal = saved._read_saved_parent_result(scan.scan_dir, scan.scan_id)
for name in ("scan-manifest.json", "findings.json", "coverage.json"):
os.utime(scan.scan_dir / name, ns=(0, 0))
checkpoint = write_checkpoint(scan.scan_dir / "checkpoints", terminal)
os.utime(checkpoint, ns=(50, 50))
head = scan.scan_dir / "checkpoint-head.json"
checkpoint = write_checkpoint(scan.scan_dir / "checkpoints", terminal, mtime_ns=50)
for observed in (100, 300, 100):
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(observed, observed))
select_checkpoint(scan.scan_dir, checkpoint, mtime_ns=observed)
saved._capture_saved_source(scan.scan_dir, "checkpoint-head.json", scan.scan_id)
pending = saved_draft(
scan.scan_id,
deferred=[{"candidateId": "candidate-review", "reason": "Review remains pending."}],
)
pending_path = write_checkpoint(scan.scan_dir / "checkpoints", pending)
os.utime(pending_path, ns=(pending_time, pending_time))
write_checkpoint(scan.scan_dir / "checkpoints", pending, mtime_ns=pending_time)
prepared_coverage = []
write = saved._write_prepared_scan_finalization
@@ -206,28 +179,17 @@ def test_restored_root_observation_keeps_tied_pending_payload(
raise OSError("Synthetic restored-observation publication interruption")
return write(prepared, **kwargs)
context = workbench_api["_WORKBENCH_DB_CONTEXT"]
with monkeypatch.context() as patch:
patch.setattr(saved, "_write_prepared_scan_finalization", publish)
saved.fail_scan(
context,
workbench_db,
Namespace(scan_id=scan.scan_id, claim_token=None, cost_json=None, message="Stopped."),
)
saved.preserve_scan_results(
context,
workbench_db,
Namespace(
scan_id=scan.scan_id, claim_token=None, thread_id=None, coordinator_generation=None
),
)
scan.fail()
scan.preserve()
coverage = read_review_state(workbench_db, scan.scan_dir)
assert len(prepared_coverage) == 1
for document in [coverage, *prepared_coverage]:
assert any(
row.get("candidateId") == "candidate-review" for row in document["deferred"]
) is (pending_time >= 100)
saved.recover_scan_results(context, workbench_db, Namespace(scan_id=scan.scan_id))
scan.recover()
assert read_review_state(workbench_db, scan.scan_dir) == coverage
@@ -269,20 +231,19 @@ def test_root_outcome_uses_its_own_completion_marker(
os.utime(scan.scan_dir / name, ns=(0, 0))
results = sorted(
[add_worker(workbench_db, scan), add_worker(workbench_db, scan)],
[scan.add_worker(), scan.add_worker()],
key=lambda path: path.parent.name,
)
# Registration timestamps are equal, so IDs determine both arrival orders.
for result, worker_complete in zip(results, [not complete_worker_last, complete_worker_last]):
result.write_text(
json.dumps(
saved_draft(
scan.scan_id,
complete=worker_complete,
)
)
write_result_draft(
result,
saved_draft(
scan.scan_id,
complete=worker_complete,
),
mtime_ns=100,
)
os.utime(result, ns=(100, 100))
assert [
row["result_manifest_path"]
for row in workbench_db.execute(
@@ -296,19 +257,16 @@ def test_root_outcome_uses_its_own_completion_marker(
)
if flow == "recover":
saved.fail_scan(context, workbench_db, stop_args)
selected = write_checkpoint(scan.scan_dir / "checkpoints", root_draft)
os.utime(selected, ns=(100, 100))
head = scan.scan_dir / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
os.utime(head, ns=(200, 200))
selected = write_checkpoint(scan.scan_dir / "checkpoints", root_draft, mtime_ns=100)
select_checkpoint(scan.scan_dir, selected, mtime_ns=200)
pending = write_checkpoint(
scan.scan_dir / "checkpoints",
saved_draft(
scan.scan_id,
deferred=[{"candidateId": "candidate-review", "reason": "Validation is pending."}],
),
mtime_ns=200,
)
os.utime(pending, ns=(200, 200))
originals = {path: path.read_bytes() for path in [selected, pending, *results]}
prepared_coverage = []
write = saved._write_prepared_scan_finalization
@@ -325,16 +283,10 @@ def test_root_outcome_uses_its_own_completion_marker(
saved.fail_scan(context, workbench_db, stop_args)
elif interrupted:
with pytest.raises(OSError, match="Synthetic mixed-source publication interruption"):
saved.recover_scan_results(context, workbench_db, Namespace(scan_id=scan.scan_id))
scan.recover()
else:
saved.recover_scan_results(context, workbench_db, Namespace(scan_id=scan.scan_id))
published = saved.preserve_scan_results(
context,
workbench_db,
Namespace(
scan_id=scan.scan_id, claim_token=None, thread_id=None, coordinator_generation=None
),
)["scan"]
scan.recover()
published = scan.preserve()
assert not published["resultsRecoveryNeeded"]
coverage = read_review_state(workbench_db, scan.scan_dir)
assert len(prepared_coverage) == 1
@@ -343,7 +295,7 @@ def test_root_outcome_uses_its_own_completion_marker(
row.get("candidateId") == "candidate-review" for row in document["deferred"]
) is (root_complete is False)
manifest = (scan.scan_dir / "scan-manifest.json").read_bytes()
saved.recover_scan_results(context, workbench_db, Namespace(scan_id=scan.scan_id))
scan.recover()
assert read_review_state(workbench_db, scan.scan_dir) == coverage
assert (scan.scan_dir / "scan-manifest.json").read_bytes() == manifest
assert all(path.read_bytes() == contents for path, contents in originals.items())
@@ -406,8 +358,7 @@ def test_legacy_tied_root_parent_preserves_accepted_pending_evidence(
checkpoint = write_checkpoint(scan.scan_dir / "checkpoints", draft)
observed = 100 if name == "reported" else 500
os.utime(checkpoint, ns=(observed, observed))
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(observed, observed))
select_checkpoint(scan.scan_dir, checkpoint, mtime_ns=observed)
captures.update(
saved._capture_saved_source(scan.scan_dir, "checkpoint-head.json", scan.scan_id)
)
@@ -463,9 +414,7 @@ def test_legacy_tied_root_parent_preserves_accepted_pending_evidence(
assert any(
row.get("candidateId") == "candidate-review" for row in current_coverage["deferred"]
)
replayed = saved.recover_scan_results(context, workbench_db, Namespace(scan_id=scan.scan_id))[
"scan"
]
replayed = scan.recover()
assert replayed["findingCount"] == 1
assert not replayed["resultsRecoveryNeeded"]
before_sources = json.loads(manifest)["scan"]["preservedSources"]
@@ -490,14 +439,11 @@ def test_legacy_tied_root_parent_preserves_accepted_pending_evidence(
if wrapped:
assert manifest_path.read_bytes() == manifest
manifest = manifest_path.read_bytes()
saved.recover_scan_results(context, workbench_db, Namespace(scan_id=scan.scan_id))
scan.recover()
assert manifest_path.read_bytes() == manifest
head.write_text(json.dumps({"checkpoint": checkpoints[later_selection].name}))
os.utime(head, ns=(600, 600))
recovered = saved.recover_scan_results(context, workbench_db, Namespace(scan_id=scan.scan_id))[
"scan"
]
select_checkpoint(scan.scan_dir, checkpoints[later_selection], mtime_ns=600)
recovered = scan.recover()
assert recovered["findingCount"] == (0 if later_selection == "rejected" else 1)
assert not recovered["resultsRecoveryNeeded"]
coverage = read_review_state(workbench_db, scan.scan_dir)
@@ -565,18 +511,15 @@ def test_legacy_pending_ties_aggregate_accepted_provenance(
head = scan.scan_dir / "checkpoint-head.json"
for draft, observed in observations:
draft["coverage"] = {**scan.coverage, **draft["coverage"]}
checkpoint = write_checkpoint(scan.scan_dir / "checkpoints", draft)
os.utime(checkpoint, ns=(observed, observed))
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(observed, observed))
checkpoint = write_checkpoint(scan.scan_dir / "checkpoints", draft, mtime_ns=observed)
select_checkpoint(scan.scan_dir, checkpoint, mtime_ns=observed)
captures.update(
saved._capture_saved_source(scan.scan_dir, "checkpoint-head.json", scan.scan_id)
)
head.unlink()
raw = saved_draft(scan.scan_id, deferred=[unobserved])
raw["coverage"] = {**scan.coverage, **raw["coverage"]}
unobserved_path = write_checkpoint(scan.scan_dir / "checkpoints", raw)
os.utime(unobserved_path, ns=(100, 100))
unobserved_path = write_checkpoint(scan.scan_dir / "checkpoints", raw, mtime_ns=100)
captures.update(
saved._capture_saved_source(
scan.scan_dir, unobserved_path.relative_to(scan.scan_dir).as_posix(), scan.scan_id
@@ -23,7 +23,9 @@ from workbench_test_support import (
run_workbench,
saved_discovery_worker,
saved_draft,
select_checkpoint,
write_checkpoint,
write_result_draft,
)
@@ -79,9 +81,7 @@ def save_worker(root: Path, module, worker_id: str, drafts: list[dict], result:
path = checkpoints / f"{module._digest(draft)}.json"
path.write_text(json.dumps(draft))
os.utime(path, ns=(index * 100, index * 100))
result_path = output / "result.json"
result_path.write_text(json.dumps(result))
os.utime(result_path, ns=(1000, 1000))
write_result_draft(output / "result.json", result, mtime_ns=1000)
return saved_discovery_worker(output, worker_id, 1)
@@ -245,15 +245,15 @@ def test_missing_parent_identity_reuses_established_checkpoint(
"Synthetic review finding",
summary="Retain the saved result.",
)
checkpoint = write_checkpoint(
write_checkpoint(
tmp_path / "checkpoints",
saved_draft(
"identity-scan",
complete=True,
findings=[{**finding, "identity": {"anchor": saved_anchor}}],
),
mtime_ns=100,
)
os.utime(checkpoint, ns=(100, 100))
if explicit_end_line:
finding["locations"][0]["endLine"] = 1
write_saved_parent(
@@ -362,10 +362,11 @@ def test_stopped_deep_recovery_uses_host_mode_for_terminal_replacement(
write_saved_parent(scan_dir, saved_draft(scan_id, findings=[first], complete=True), 100)
revised = {**first, "title": "Revised review", "summary": "Revised synthetic evidence."}
del revised["identity"]
checkpoint = write_checkpoint(
scan_dir / "checkpoints", saved_draft(scan_id, findings=[revised], complete=True)
write_checkpoint(
scan_dir / "checkpoints",
saved_draft(scan_id, findings=[revised], complete=True),
mtime_ns=200,
)
os.utime(checkpoint, ns=(200, 200))
fail_deep_scan(state, codex_home, scan_id)
findings_path = scan_dir / "findings.json"
findings = json.loads(findings_path.read_text())["findings"]
@@ -425,11 +426,9 @@ def test_torn_worker_closure_reuses_observed_legacy_identity(
closures=[{"id": identity, "reason": "Review completed."}],
complete=True,
),
mtime_ns=1100,
)
os.utime(checkpoint, ns=(1100, 1100))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(1200, 1200))
select_checkpoint(output, checkpoint, mtime_ns=1200)
originals = {path: path.read_bytes() for path in output.rglob("*.json")}
result = recover(tmp_path, saved_results, [worker, other])
replay = recover(
@@ -566,13 +565,13 @@ def test_unsafe_deferred_update_keeps_the_earlier_valid_path(
state, codex_home, _, scan_dir, scan_id = deep_scan_fixture(tmp_path, run=setup_workbench)
_, result = accepted_standard_worker(state, codex_home, scan_dir, scan_id, run=setup_workbench)
original = {"id": "review", "reason": "Review remains.", "paths": ["app.py"]}
checkpoint = write_checkpoint(
result.parent / "checkpoints", saved_draft(scan_id, deferred=[original])
write_checkpoint(
result.parent / "checkpoints",
saved_draft(scan_id, deferred=[original]),
mtime_ns=100,
)
os.utime(checkpoint, ns=(100, 100))
update = {**original, "paths": ["../outside.py"]}
result.write_text(json.dumps(saved_draft(scan_id, deferred=[update])))
os.utime(result, ns=(200, 200))
write_result_draft(result, saved_draft(scan_id, deferred=[update]), mtime_ns=200)
fail_deep_scan(state, codex_home, scan_id, deep_status="failed")
@@ -654,9 +653,7 @@ def test_new_work_survives_accepted_candidate_rejection(
for index, checkpoint in enumerate(checkpoints, 1):
os.utime(checkpoint, ns=(index * 100, index * 100))
os.utime(checkpoints[2], ns=(raw_modified, raw_modified))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoints[1].name}))
os.utime(head, ns=(200, 200))
select_checkpoint(output, checkpoints[1], mtime_ns=200)
documents = recover(tmp_path, saved_results, workers)
replay = recover(tmp_path, saved_results, workers, documents[0]["scan"]["preservedSources"])
for result in (documents, replay):
@@ -733,21 +730,18 @@ def test_generic_surface_recovery_uses_resolved_candidate_identity(
]
for index, checkpoint in enumerate(checkpoints, 1):
os.utime(checkpoint, ns=(index * 100, index * 100))
result_path.write_text(json.dumps(accepted))
os.utime(result_path, ns=(200, 200))
write_result_draft(result_path, accepted, mtime_ns=200)
# The terminal checkpoint survives a failed replacement of result.json.
head = result_path.parent / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoints[2 if rejected_here else 1].name}))
head = select_checkpoint(result_path.parent, checkpoints[2 if rejected_here else 1])
observed = 300 if rejected_here else 200
os.utime(head, ns=(observed, observed))
if outcome == "other_worker":
other_worker_id, other_result = accepted_standard_worker(
state, codex_home, scan_dir, scan_id, name="other-worker", run=setup_workbench
)
other_result.write_text(
json.dumps(saved_draft(scan_id, surfaces=[rejection], complete=True))
write_result_draft(
other_result, saved_draft(scan_id, surfaces=[rejection], complete=True), mtime_ns=200
)
os.utime(other_result, ns=(200, 200))
first_coverage, recovered = cancel_and_preserve(
monkeypatch, saved_results, state, codex_home, scan_dir, scan_id
@@ -842,11 +836,8 @@ def test_split_deferred_rows_keep_distinct_ids_in_frozen_recovery(
]
for index, checkpoint in enumerate(checkpoints, 1):
os.utime(checkpoint, ns=(index * 100, index * 100))
result_path.write_text(json.dumps(initial))
os.utime(result_path, ns=(100, 100))
head = result_path.parent / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoints[0].name}))
os.utime(head, ns=(100, 100))
write_result_draft(result_path, initial, mtime_ns=100)
select_checkpoint(result_path.parent, checkpoints[0], mtime_ns=100)
if close_first:
first_id = split[0]["id"] if explicit_ids else saved_results._saved_coverage_id(split[0])
terminal = saved_draft(
@@ -854,10 +845,10 @@ def test_split_deferred_rows_keep_distinct_ids_in_frozen_recovery(
closures=[{"id": first_id, "reason": "First path reviewed."}],
complete=True,
)
terminal_checkpoint = write_checkpoint(result_path.parent / "checkpoints", terminal)
os.utime(terminal_checkpoint, ns=(300, 300))
head.write_text(json.dumps({"checkpoint": terminal_checkpoint.name}))
os.utime(head, ns=(300, 300))
terminal_checkpoint = write_checkpoint(
result_path.parent / "checkpoints", terminal, mtime_ns=300
)
select_checkpoint(result_path.parent, terminal_checkpoint, mtime_ns=300)
if explicit_ids:
expected_ids.remove(first_id)
first_coverage, replay = cancel_and_preserve(
@@ -925,11 +916,8 @@ def test_unnamed_observation_does_not_replace_saved_context(
accepted_index = 1 if observation == "explicit-update" else 0
observed = (accepted_index + 1) * 100
if layout == "worker":
result_path.write_text(json.dumps(accepted))
os.utime(result_path, ns=(observed, observed))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoints[accepted_index].name}))
os.utime(head, ns=(observed, observed))
write_result_draft(result_path, accepted, mtime_ns=observed)
select_checkpoint(output, checkpoints[accepted_index], mtime_ns=observed)
first_coverage, replay = cancel_and_preserve(
monkeypatch, saved_results, state, codex_home, scan_dir, scan_id
)
@@ -1093,12 +1081,9 @@ def test_recovery_finalization_preserves_distinct_reports_at_a_revised_location(
]
output = tmp_path / "reviewer"
for sequence, draft in enumerate(drafts, 1):
path = write_checkpoint(output / "checkpoints", draft)
os.utime(path, ns=(sequence * 1_000_000_000, sequence * 1_000_000_000))
write_checkpoint(output / "checkpoints", draft, mtime_ns=sequence * 1_000_000_000)
if saved_result:
result = output / "result.json"
result.write_text(json.dumps(drafts[-1]))
os.utime(result, ns=(3_000_000_000, 3_000_000_000))
write_result_draft(output / "result.json", drafts[-1], mtime_ns=3_000_000_000)
worker = saved_discovery_worker(output, "reviewer")
sources = {path: path.read_bytes() for path in output.rglob("*.json")}
documents = recover(tmp_path, saved_results, [worker])
@@ -1184,10 +1169,8 @@ def test_parent_represents_worker_versions_before_candidate_enrichment(
output.mkdir()
draft = {"scanId": "identity-scan", "complete": True, "findings": [reduced]}
result = output / "result.json"
result.write_text(json.dumps(draft))
os.utime(result, ns=(1500, 1500))
checkpoint = write_checkpoint(output / "checkpoints", draft)
os.utime(checkpoint, ns=(1500, 1500))
write_result_draft(result, draft, mtime_ns=1500)
write_checkpoint(output / "checkpoints", draft, mtime_ns=1500)
reducer = {
"id": "reducer",
"kind": "dedup",
@@ -64,8 +64,7 @@ def test_stopped_publication_recovers_after_unicode_reviews_are_closed(tmp_path:
scan_id,
deferred=[{"reason": reason, "paths": ["src/example.py"]} for reason, _ in SURROGATE_IDS],
)
checkpoint = write_checkpoint(result.parent / "checkpoints", pending)
os.utime(checkpoint, ns=(100, 100))
write_checkpoint(result.parent / "checkpoints", pending, mtime_ns=100)
closed = saved_draft(
scan_id,
closures=[{"id": identity, "reason": "Review completed."} for _, identity in SURROGATE_IDS],
@@ -72,15 +72,15 @@ def test_workbench_cancels_running_scan_and_rejects_late_updates(tmp_path: Path)
assert delivered["results"]["progress"]["status"] == "canceled"
assert delivered["results"]["handoffStatus"] == "delivered"
restarted = start_delivered_scan(state_dir, "--workspace-id", str(saved["id"]))
restarted_scan_id = str(restarted["results"]["scanId"])
restarted = start_delivered_scan(state_dir, str(saved["id"]))
restarted_scan_id = str(restarted["scanId"])
assert restarted_scan_id != scan_id
assert restarted["results"]["progress"]["status"] == "running"
assert restarted["progress"]["status"] == "running"
previous_scan = get_scan(state_dir, scan_id)
assert previous_scan["scan"]["scanId"] == scan_id
assert previous_scan["workspace"]["results"]["scanId"] == scan_id
assert previous_scan["workspace"]["results"]["progress"]["status"] == "canceled"
write_completed_contract(Path(str(restarted["results"]["scanDir"])), restarted_scan_id, target)
write_completed_contract(Path(str(restarted["scanDir"])), restarted_scan_id, target)
scan_command(state_dir, "complete-scan", restarted_scan_id)
rejected = cancel_scan(state_dir, restarted_scan_id, thread_id, check=False)
assert rejected["returncode"] != 0
@@ -18,6 +18,7 @@ from workbench_test_support import (
fail_deep_scan,
get_scan,
preserve_scan_results,
read_draft_documents,
read_review_state,
replay_saved_results,
run_workbench,
@@ -25,9 +26,11 @@ from workbench_test_support import (
saved_discovery_worker,
saved_draft,
scan_command,
select_checkpoint,
start_delivered_scan,
write_checkpoint,
write_completed_contract,
write_result_draft,
)
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
@@ -47,12 +50,6 @@ def drafts(scan_id: str) -> tuple[dict, dict]:
return pending, closed
def select(output: Path, checkpoint: Path, observed: int) -> None:
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(observed, observed))
@pytest.mark.parametrize("selection", ["same", "reopened"])
@pytest.mark.parametrize("has_result", [False, True])
def test_late_head_changes_require_explicit_recovery(
@@ -66,11 +63,10 @@ def test_late_head_changes_require_explicit_recovery(
os.utime(reopened, ns=(100, 100))
os.utime(completed, ns=(150, 150))
if has_result:
result.write_text(json.dumps(pending))
os.utime(result, ns=(100, 100))
write_result_draft(result, pending, mtime_ns=100)
else:
result.unlink()
select(result.parent, completed, 200)
select_checkpoint(result.parent, completed, mtime_ns=200)
environment = {"CODEX_HOME": str(codex_home)}
fail_deep_scan(state, codex_home, scan_id, deep_status="failed")
manifest_path = scan_dir / "scan-manifest.json"
@@ -85,7 +81,9 @@ def test_late_head_changes_require_explicit_recovery(
)
assert get_scan(state, scan_id)["scan"]["resultsRecoveryNeeded"] is False
select(result.parent, reopened if selection == "reopened" else completed, 300)
select_checkpoint(
result.parent, reopened if selection == "reopened" else completed, mtime_ns=300
)
snapshots = list((result.parent / "checkpoint-heads").iterdir())
assert get_scan(state, scan_id)["scan"]["resultsRecoveryNeeded"] is True
assert list((result.parent / "checkpoint-heads").iterdir()) == snapshots
@@ -132,8 +130,7 @@ def test_frozen_parent_replay_ignores_nonreference_ancestry(
previous.append(checkpoint.relative_to(tmp_path).as_posix())
os.utime(checkpoint, ns=(100, 100))
pending["previousParentCheckpoints"] = [*previous, *ancestry]
checkpoint = write_checkpoint(tmp_path / "checkpoints", pending)
os.utime(checkpoint, ns=(200, 200))
checkpoint = write_checkpoint(tmp_path / "checkpoints", pending, mtime_ns=200)
originals = {path: path.read_bytes() for path in (tmp_path / "checkpoints").iterdir()}
warnings = []
first = saved.merge_saved_results(
@@ -165,7 +162,7 @@ def test_recovery_keeps_one_surface_with_optional_empty_receipts(
if has_receipts:
surface["receiptRefs"] = []
checkpoint = write_checkpoint(tmp_path / "checkpoints", draft)
select(tmp_path, checkpoint, 50)
select_checkpoint(tmp_path, checkpoint, mtime_ns=50)
original = checkpoint.read_bytes()
if has_canonical:
canonical = copy.deepcopy(draft)
@@ -199,8 +196,7 @@ def test_file_authored_resolution_can_leave_manifest_unchanged(
pending = saved_draft(
scan_id, deferred=[{"candidateId": "candidate", "reason": "Review remains."}, independent]
)
checkpoint = write_checkpoint(tmp_path / "checkpoints", pending)
os.utime(checkpoint, ns=(200, 200))
write_checkpoint(tmp_path / "checkpoints", pending, mtime_ns=200)
completed = saved_draft(
scan_id,
deferred=[independent] if retain_pending else [],
@@ -233,8 +229,7 @@ def test_file_authored_deferred_update_preserves_valid_checkpoint_evidence(
) -> None:
scan_id, pending, _, binding = checkpoint_scan
pending["complete"] = False
checkpoint = write_checkpoint(tmp_path / "checkpoints", pending)
os.utime(checkpoint, ns=(100, 100))
write_checkpoint(tmp_path / "checkpoints", pending, mtime_ns=100)
current = copy.deepcopy(pending)
current["coverage"]["deferred"][0].update(update)
write_saved_parent(tmp_path, current, 200)
@@ -274,8 +269,7 @@ def test_recovery_preserves_accepted_generic_surface_closeout(
legacy = copy.deepcopy(pending)
if anonymous:
legacy["coverage"]["surfaces"][0].pop("id")
checkpoint = write_checkpoint(directory / "checkpoints", legacy)
os.utime(checkpoint, ns=(100, 100))
write_checkpoint(directory / "checkpoints", legacy, mtime_ns=100)
# A prior writer returned the assigned surface ID, but its checkpoint was anonymous.
published = copy.deepcopy(pending)
published["coverage"]["surfaces"][0]["receiptRefs"] = []
@@ -283,8 +277,7 @@ def test_recovery_preserves_accepted_generic_surface_closeout(
write_saved_parent(directory, published, 150)
else:
result = directory / "result.json"
result.write_text(json.dumps(published))
os.utime(result, ns=(150, 150))
write_result_draft(result, published, mtime_ns=150)
closed_surface = {**surface, "disposition": "no_issue_found", "receiptRefs": []}
closed = saved_draft(
scan_id,
@@ -292,9 +285,8 @@ def test_recovery_preserves_accepted_generic_surface_closeout(
closures=[{"id": "review", "reason": "Review completed."}],
complete=True,
)
completed = write_checkpoint(directory / "checkpoints", closed)
os.utime(completed, ns=(200, 200))
select(directory, completed, 300)
completed = write_checkpoint(directory / "checkpoints", closed, mtime_ns=200)
select_checkpoint(directory, completed, mtime_ns=300)
workers = (
[]
if layout == "parent"
@@ -321,8 +313,7 @@ def test_malformed_parent_deferred_id_reaches_existing_recovery_diagnostics(
) -> None:
scan_id, pending, _, binding = checkpoint_scan
pending["complete"] = False
checkpoint = write_checkpoint(tmp_path / "checkpoints", pending)
os.utime(checkpoint, ns=(100, 100))
write_checkpoint(tmp_path / "checkpoints", pending, mtime_ns=100)
current = copy.deepcopy(pending)
current["complete"] = complete
current["coverage"]["deferred"][0]["id"] = identity
@@ -365,18 +356,15 @@ def test_recovery_preserves_distinct_legacy_tasks_with_one_id(
{"id": "review", "reason": "Review worker.", "paths": ["worker.py"]},
]
legacy = saved_draft(scan_id, deferred=tasks)
checkpoint = write_checkpoint(directory / "checkpoints", legacy)
os.utime(checkpoint, ns=(100, 100))
write_checkpoint(directory / "checkpoints", legacy, mtime_ns=100)
if rewrite:
rewritten = saved_draft(scan_id, deferred=tasks[:1])
checkpoint = write_checkpoint(directory / "checkpoints", rewritten)
os.utime(checkpoint, ns=(150, 150))
write_checkpoint(directory / "checkpoints", rewritten, mtime_ns=150)
closed = saved_draft(
scan_id, closures=[{"id": "review", "reason": "API reviewed."}], complete=True
)
completed = write_checkpoint(directory / "checkpoints", closed)
os.utime(completed, ns=(200, 200))
select(directory, completed, 300)
completed = write_checkpoint(directory / "checkpoints", closed, mtime_ns=200)
select_checkpoint(directory, completed, mtime_ns=300)
workers = (
[]
if layout == "parent"
@@ -421,13 +409,13 @@ def test_recovery_keeps_generic_work_that_collides_with_candidate_aliases(
other = {"id": "other-review", "reason": "Other review.", "surfaceIds": ["generic-surface"]}
surface = {"id": "generic-surface", "label": "Generic review", "disposition": "needs_follow_up"}
pending = saved_draft(scan_id, deferred=[generic, candidate, other], surfaces=[surface])
checkpoint = write_checkpoint(directory / "checkpoints", pending)
os.utime(checkpoint, ns=(100, 100))
write_checkpoint(directory / "checkpoints", pending, mtime_ns=100)
if rewrite:
checkpoint = write_checkpoint(
directory / "checkpoints", saved_draft(scan_id, deferred=[candidate, other])
write_checkpoint(
directory / "checkpoints",
saved_draft(scan_id, deferred=[candidate, other]),
mtime_ns=150,
)
os.utime(checkpoint, ns=(150, 150))
terminal = saved_draft(
scan_id,
closures=[{"id": "other-review", "reason": "Other review completed."}],
@@ -449,9 +437,8 @@ def test_recovery_keeps_generic_work_that_collides_with_candidate_aliases(
finding = json.loads((contract / "findings.json").read_text())["findings"][0]
finding.setdefault("extensions", {})["candidateId"] = "candidate-a"
terminal["findings"] = [finding]
completed = write_checkpoint(directory / "checkpoints", terminal)
os.utime(completed, ns=(200, 200))
select(directory, completed, 300)
completed = write_checkpoint(directory / "checkpoints", terminal, mtime_ns=200)
select_checkpoint(directory, completed, mtime_ns=300)
workers = (
[]
if layout == "parent"
@@ -491,9 +478,8 @@ def test_selected_parent_replaces_stale_completion_marker(
progress = saved_draft(scan_id, deferred=tasks, complete=complete)
if complete is None:
progress.pop("complete")
checkpoint = write_checkpoint(tmp_path / "checkpoints", progress)
os.utime(checkpoint, ns=(200, 200))
select(tmp_path, checkpoint, 300)
checkpoint = write_checkpoint(tmp_path / "checkpoints", progress, mtime_ns=200)
select_checkpoint(tmp_path, checkpoint, mtime_ns=300)
first = saved.merge_saved_results(
tmp_path, scan_id, binding, [], [], stopped=True, reason="interrupted"
)
@@ -518,8 +504,7 @@ def test_reported_surface_requires_its_own_valid_candidate_finding(
scan_id,
deferred=[{"id": "candidate-task", "candidateId": "candidate-a", "reason": "Review."}],
)
checkpoint = write_checkpoint(directory / "checkpoints", pending)
os.utime(checkpoint, ns=(100, 100))
write_checkpoint(directory / "checkpoints", pending, mtime_ns=100)
terminal = saved_draft(
scan_id,
complete=True,
@@ -545,14 +530,12 @@ def test_reported_surface_requires_its_own_valid_candidate_finding(
if evidence == "malformed":
finding.pop("title")
terminal["findings"] = [finding]
completed = write_checkpoint(directory / "checkpoints", terminal)
os.utime(completed, ns=(200, 200))
completed = write_checkpoint(directory / "checkpoints", terminal, mtime_ns=200)
if layout == "result":
result = directory / "result.json"
result.write_text(json.dumps(terminal))
os.utime(result, ns=(300, 300))
write_result_draft(result, terminal, mtime_ns=300)
else:
select(directory, completed, 300)
select_checkpoint(directory, completed, mtime_ns=300)
workers = [saved_discovery_worker(output, "worker", 2 if layout == "archived" else 1)]
first = saved.merge_saved_results(
tmp_path, scan_id, binding, workers, [], stopped=True, reason="interrupted"
@@ -579,13 +562,12 @@ def test_completion_checks_selected_parent_checkpoint(
workspace = create_saved_workspace(state, target)
started = start_delivered_scan(
state,
"--workspace-id",
str(workspace["id"]),
"--scan-root",
str(tmp_path / "scans"),
)
scan_id = str(started["results"]["scanId"])
scan_dir = Path(started["results"]["scanDir"])
scan_id = str(started["scanId"])
scan_dir = Path(started["scanDir"])
write_completed_contract(scan_dir, scan_id, target, relative_path="app.py")
manifest_path = scan_dir / "scan-manifest.json"
manifest = json.loads(manifest_path.read_text())
@@ -608,9 +590,8 @@ def test_completion_checks_selected_parent_checkpoint(
artifacts = ("scan-manifest.json", "findings.json", "coverage.json")
for name in artifacts:
os.utime(scan_dir / name, ns=(100, 100))
checkpoint = write_checkpoint(scan_dir / "checkpoints", draft)
os.utime(checkpoint, ns=(200, 200))
select(scan_dir, checkpoint, 300)
checkpoint = write_checkpoint(scan_dir / "checkpoints", draft, mtime_ns=200)
select_checkpoint(scan_dir, checkpoint, mtime_ns=300)
original = {
name: (scan_dir / name).read_bytes() for name in (*artifacts, "checkpoint-head.json")
}
@@ -676,9 +657,8 @@ def test_selected_parent_retains_semantic_context_through_frozen_recovery(
}
for name in ("scan-manifest.json", "findings.json", "coverage.json"):
os.utime(tmp_path / name, ns=(100, 100))
checkpoint = write_checkpoint(tmp_path / "checkpoints", selected)
os.utime(checkpoint, ns=(200, 200))
select(tmp_path, checkpoint, 300)
checkpoint = write_checkpoint(tmp_path / "checkpoints", selected, mtime_ns=200)
select_checkpoint(tmp_path, checkpoint, mtime_ns=300)
first = saved.merge_saved_results(
tmp_path, scan_id, binding, [], [], stopped=stopped, reason="interrupted"
)
@@ -703,7 +683,7 @@ def test_frozen_observations_survive_live_head_changes(
reopened = write_checkpoint(directory / "checkpoints", pending)
os.utime(completed, ns=(100, 100))
os.utime(reopened, ns=(200, 200))
select(directory, completed, 300)
select_checkpoint(directory, completed, mtime_ns=300)
workers = (
[]
if layout == "parent"
@@ -727,7 +707,7 @@ def test_frozen_observations_survive_live_head_changes(
snapshot = next(path for path in frozen if "/checkpoint-heads/" in f"/{path}")
assert pending["coverage"]["deferred"][0] not in first[2]["deferred"]
for checkpoint in (reopened, completed):
select(directory, checkpoint, 400)
select_checkpoint(directory, checkpoint, mtime_ns=400)
replay = merge(frozen)
assert replay[2] == first[2]
legacy = {
@@ -754,13 +734,13 @@ def test_multiple_parent_observations_keep_latest_selection_and_pending_ties(
os.utime(completed, ns=(100, 100))
os.utime(reopened, ns=(200, 200))
for checkpoint, observed in ((completed, 300), (reopened, 400), (completed, 500)):
select(tmp_path, checkpoint, observed)
select_checkpoint(tmp_path, checkpoint, mtime_ns=observed)
saved._capture_saved_source(tmp_path, "checkpoint-head.json", scan_id)
first = saved.merge_saved_results(
tmp_path, scan_id, binding, [], [], stopped=True, reason="interrupted"
)
assert pending["coverage"]["deferred"][0] not in first[2]["deferred"]
select(tmp_path, reopened, 500)
select_checkpoint(tmp_path, reopened, mtime_ns=500)
tied = saved.merge_saved_results(
tmp_path, scan_id, binding, [], [], stopped=True, reason="interrupted"
)
@@ -776,7 +756,7 @@ def test_head_snapshot_reads_content_and_time_from_one_descriptor(
scan_id, pending, closed, _ = checkpoint_scan
completed = write_checkpoint(tmp_path / "checkpoints", closed)
reopened = write_checkpoint(tmp_path / "checkpoints", pending)
select(tmp_path, completed, observed)
select_checkpoint(tmp_path, completed, mtime_ns=observed)
replacement = tmp_path / "replacement.json"
replacement.write_text(json.dumps({"checkpoint": reopened.name}))
os.utime(replacement, ns=(observed + 1, observed + 1))
@@ -803,9 +783,8 @@ def test_legacy_live_head_sources_convert_their_recorded_observation(
tmp_path: Path, checkpoint_scan
) -> None:
scan_id, pending, closed, binding = checkpoint_scan
checkpoint = write_checkpoint(tmp_path / "checkpoints", closed)
os.utime(checkpoint, ns=(100, 100))
select(tmp_path, checkpoint, 200)
checkpoint = write_checkpoint(tmp_path / "checkpoints", closed, mtime_ns=100)
select_checkpoint(tmp_path, checkpoint, mtime_ns=200)
paths = [checkpoint.relative_to(tmp_path).as_posix(), "checkpoint-head.json"]
frozen = {path: saved._read_saved_result(tmp_path, path, scan_id)[1] for path in paths}
first = saved.merge_saved_results(
@@ -832,7 +811,7 @@ def test_legacy_live_head_sources_convert_their_recorded_observation(
"checkpoint": checkpoint.name,
"observedAtNs": "200",
}
select(tmp_path, checkpoint, 300)
select_checkpoint(tmp_path, checkpoint, mtime_ns=300)
with pytest.raises(
saved.ContractError, match="Frozen stopped-scan checkpoint set is incomplete"
):
@@ -881,14 +860,7 @@ def test_parent_head_selection_matches_frozen_publication_retry(
write_completed_contract(
contract, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
)
initial = {
key: json.loads((contract / filename).read_text())
for key, filename in (
("manifest", "scan-manifest.json"),
("findings", "findings.json"),
("coverage", "coverage.json"),
)
}
initial = read_draft_documents(contract)
if evidence == "reported":
finalize_scan_contract._populate_unsealed_finding_identities(
initial["manifest"], initial["findings"]
@@ -928,7 +900,7 @@ def test_parent_head_selection_matches_frozen_publication_retry(
os.utime(original_checkpoint, ns=(100, 100))
for filename in ("findings.json", "scan-manifest.json"):
os.utime(scan_dir / filename, ns=(100, 100))
select(scan_dir, original_checkpoint, 100)
select_checkpoint(scan_dir, original_checkpoint, mtime_ns=100)
terminal = copy.deepcopy(initial)
terminal["manifest"]["scan"].pop("complete")
@@ -961,7 +933,7 @@ def test_parent_head_selection_matches_frozen_publication_retry(
terminal_checkpoint = scan_dir / "checkpoints" / terminal_head["checkpoint"]
assert terminal_checkpoint != original_checkpoint
os.utime(terminal_checkpoint, ns=(head_time, head_time))
select(scan_dir, terminal_checkpoint, head_time)
select_checkpoint(scan_dir, terminal_checkpoint, mtime_ns=head_time)
assert read_review_state(state, scan_dir) == initial["coverage"]
first = []
@@ -1039,13 +1011,9 @@ def test_selected_worker_checkpoint_preserves_terminal_coverage(
output = tmp_path / "worker"
output.mkdir()
result_path = output / "result.json"
result_path.write_text(json.dumps(result))
os.utime(result_path, ns=(200, 200))
checkpoint = write_checkpoint(output / "checkpoints", selected)
os.utime(checkpoint, ns=(head_time, head_time))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(head_time, head_time))
write_result_draft(result_path, result, mtime_ns=200)
checkpoint = write_checkpoint(output / "checkpoints", selected, mtime_ns=head_time)
head = select_checkpoint(output, checkpoint, mtime_ns=head_time)
unselected = write_checkpoint(
output / "checkpoints",
saved_draft(
@@ -1053,8 +1021,8 @@ def test_selected_worker_checkpoint_preserves_terminal_coverage(
surfaces=[{**surface, "id": "unselected", "label": "Unselected"}],
complete=True,
),
mtime_ns=400,
)
os.utime(unselected, ns=(400, 400))
original_bytes = {
path: path.read_bytes() for path in (result_path, checkpoint, head, unselected)
}
@@ -1093,14 +1061,9 @@ def test_terminal_selected_checkpoint_replaces_result_coverage(tmp_path, head_ti
)
output = tmp_path / "worker"
output.mkdir()
result_path = output / "result.json"
result_path.write_text(json.dumps(result))
os.utime(result_path, ns=(200, 200))
checkpoint = write_checkpoint(output / "checkpoints", selected)
os.utime(checkpoint, ns=(head_time, head_time))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(head_time, head_time))
write_result_draft(output / "result.json", result, mtime_ns=200)
checkpoint = write_checkpoint(output / "checkpoints", selected, mtime_ns=head_time)
select_checkpoint(output, checkpoint, mtime_ns=head_time)
workers = [saved_discovery_worker(output)]
first = saved.merge_saved_results(
tmp_path, scan_id, binding, workers, [], stopped=True, reason="interrupted"
@@ -1124,24 +1087,18 @@ def test_multiple_selected_terminal_observations(tmp_path, complete):
output = tmp_path / "worker"
output.mkdir()
result = saved_draft(scan_id, surfaces=[before], complete=True)
(output / "result.json").write_text(json.dumps(result))
os.utime(output / "result.json", ns=(200, 200))
head = output / "checkpoint-head.json"
write_result_draft(output / "result.json", result, mtime_ns=200)
intermediate = copy.deepcopy(result)
intermediate["coverage"]["openQuestions"] = [{"question": "Review question."}]
intermediate_checkpoint = write_checkpoint(output / "checkpoints", intermediate)
os.utime(intermediate_checkpoint, ns=(250, 250))
head.write_text(json.dumps({"checkpoint": intermediate_checkpoint.name}))
os.utime(head, ns=(250, 250))
intermediate_checkpoint = write_checkpoint(output / "checkpoints", intermediate, mtime_ns=250)
select_checkpoint(output, intermediate_checkpoint, mtime_ns=250)
workers = [saved_discovery_worker(output)]
saved.merge_saved_results(
tmp_path, scan_id, binding, workers, [], stopped=True, reason="interrupted"
)
terminal = saved_draft(scan_id, surfaces=[after], complete=complete)
checkpoint = write_checkpoint(output / "checkpoints", terminal)
os.utime(checkpoint, ns=(300, 300))
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(300, 300))
checkpoint = write_checkpoint(output / "checkpoints", terminal, mtime_ns=300)
select_checkpoint(output, checkpoint, mtime_ns=300)
first = saved.merge_saved_results(
tmp_path, scan_id, binding, workers, [], stopped=True, reason="interrupted"
)
@@ -1166,18 +1123,18 @@ def test_older_attempt_selected_head_cannot_supersede_current_result(tmp_path):
outdated = {**current, "label": "Old attempt"}
output = tmp_path / "worker"
output.mkdir()
(output / "result.json").write_text(
json.dumps(saved_draft(scan_id, surfaces=[current], complete=True))
write_result_draft(
output / "result.json",
saved_draft(scan_id, surfaces=[current], complete=True),
mtime_ns=200,
)
os.utime(output / "result.json", ns=(200, 200))
archived = output / "attempts" / "attempt-1"
checkpoint = write_checkpoint(
archived / "checkpoints", saved_draft(scan_id, surfaces=[outdated], complete=True)
archived / "checkpoints",
saved_draft(scan_id, surfaces=[outdated], complete=True),
mtime_ns=300,
)
os.utime(checkpoint, ns=(300, 300))
head = archived / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(300, 300))
select_checkpoint(archived, checkpoint, mtime_ns=300)
workers = [saved_discovery_worker(output, attempt=2)]
first = saved.merge_saved_results(
tmp_path, scan_id, binding, workers, [], stopped=True, reason="interrupted"
@@ -1216,21 +1173,17 @@ def test_generic_worker_closeout_preserves_receipt_owners(
surfaces=[surface],
deferred=[{"id": "review", "reason": "Review remains.", "surfaceIds": ["api"]}],
)
prior_checkpoint = write_checkpoint(archived / "checkpoints", pending)
os.utime(prior_checkpoint, ns=(100, 100))
(archived / "result.json").write_text(json.dumps(pending))
os.utime(archived / "result.json", ns=(100, 100))
write_checkpoint(archived / "checkpoints", pending, mtime_ns=100)
write_result_draft(archived / "result.json", pending, mtime_ns=100)
closed = saved_draft(
scan_id,
surfaces=[{**surface, "disposition": "no_issue_found", "receiptRefs": [current_ref]}],
closures=[{"id": "review", "reason": "Review completed."}],
complete=True,
)
current_checkpoint = write_checkpoint(output / "checkpoints", closed)
os.utime(current_checkpoint, ns=(200, 200))
select(output, current_checkpoint, 300)
(output / "result.json").write_text(json.dumps(closed))
os.utime(output / "result.json", ns=(200, 200))
current_checkpoint = write_checkpoint(output / "checkpoints", closed, mtime_ns=200)
select_checkpoint(output, current_checkpoint, mtime_ns=300)
write_result_draft(output / "result.json", closed, mtime_ns=200)
worker = {
**saved_discovery_worker(output, "worker", 2),
"status": "succeeded",
@@ -1361,7 +1314,7 @@ def test_legacy_tied_worker_heads_keep_pending_work_on_replay(tmp_path: Path, sc
frozen = {}
for checkpoint in (completed, reopened):
os.utime(checkpoint, ns=(100, 100))
select(output, checkpoint, 500)
select_checkpoint(output, checkpoint, mtime_ns=500)
frozen.update(
{
path: digest
@@ -80,8 +80,8 @@ def test_context_stdin_is_not_read_before_argument_parsing(
stdin.buffer.read.assert_not_called()
# These two commands declare their option groups separately. All other commands
# use the shared workbench declaration exercised by the parser tests above.
# Exercise both workspace setup and Deep Scan creation before either can allocate state.
# The parser-only cases above also check that conflicting options leave stdin untouched.
@pytest.mark.parametrize(
"command",
[CREATE_WORKSPACE, ["begin-deep-scan", "--thread-id", "thread-context", "--target-path", "."]],
@@ -117,11 +117,10 @@ def _start_diff_scan_with_draft(tmp_path: Path, kind: str) -> tuple[Path, Path,
)
registered = start_delivered_scan(
state_dir,
"--workspace-id",
workspace_id,
"--scan-root",
str(tmp_path / "scans"),
)["results"]
)
else:
if kind == "working_tree":
(target / "README.md").write_text("uncommitted fixture\n")
@@ -542,23 +541,8 @@ def test_scoped_cli_completion_adopts_registered_revision_kind(tmp_path: Path) -
text=True,
).stdout.strip()
scan_dir = tmp_path / "scan"
scan_dir.mkdir(mode=0o700)
registered = run_workbench(
state_dir,
"register-cli-scan",
"--repository",
str(target),
"--scan-dir",
str(scan_dir),
"--recipe-json",
json.dumps(
{
"config": {},
"mode": "standard",
"repository": str(target),
"target": {"kind": "paths", "paths": ["app"]},
}
),
registered = register_cli_scan(
state_dir, target, scan_dir, scan_target={"kind": "paths", "paths": ["app"]}
)
assert registered["contract"]["target"]["allowedKinds"] == ["git_revision"]
scan_id = str(registered["scanId"])
@@ -661,23 +645,11 @@ def test_cli_completion_adopts_diff_kind_with_bound_range_digest(tmp_path: Path)
(target / "README.md").write_text("second fixture\n")
subprocess.run(["git", "commit", "-qam", "Second commit"], cwd=target, check=True)
scan_dir = tmp_path / "scan"
scan_dir.mkdir(mode=0o700)
registered = run_workbench(
registered = register_cli_scan(
state_dir,
"register-cli-scan",
"--repository",
str(target),
"--scan-dir",
str(scan_dir),
"--recipe-json",
json.dumps(
{
"config": {},
"mode": "standard",
"repository": str(target),
"target": {"kind": "refs", "paths": [], "base": "HEAD~1", "head": "HEAD"},
}
),
target,
scan_dir,
scan_target={"kind": "refs", "paths": [], "base": "HEAD~1", "head": "HEAD"},
)
assert registered["contract"]["target"]["allowedKinds"] == ["git_diff"]
scan_id = str(registered["scanId"])
@@ -930,7 +902,7 @@ def test_rejected_completion_restores_parent_head_before_corrected_retry(
coverage = read_review_state(state_dir, scan_dir)
coverage["deferred"] = [{"id": "review", "reason": "Review remains."}]
independent = write_checkpoint(
write_checkpoint(
scan_dir / "checkpoints",
{
"scanId": scan_id,
@@ -940,15 +912,15 @@ def test_rejected_completion_restores_parent_head_before_corrected_retry(
"deferred": [{"id": "other-review", "reason": "Independent earlier review."}],
},
},
mtime_ns=50,
)
os.utime(independent, ns=(50, 50))
head_path = scan_dir / "checkpoint-head.json"
if existing_head:
checkpoint = write_checkpoint(
scan_dir / "checkpoints",
saved_results._parent_scan_draft(scan_id, manifest["scan"], findings, coverage),
mtime_ns=100,
)
os.utime(checkpoint, ns=(100, 100))
head_path.write_text(json.dumps({"checkpoint": checkpoint.name}, indent=3))
os.utime(head_path, ns=(100, 100))
saved_results._capture_saved_source(scan_dir, "checkpoint-head.json", scan_id)
File diff suppressed because it is too large Load Diff
@@ -16,6 +16,7 @@ from types import SimpleNamespace
import pytest
from workbench_test_support import (
RemediationRequest,
create_saved_git_workspace,
create_saved_workspace,
create_workspace,
@@ -25,16 +26,14 @@ from workbench_test_support import (
get_scan,
initialize_git_repository,
mark_deep_coordinator_succeeded,
read_draft_documents,
read_review_state,
request_remediation,
request_remediation_action,
resume_deep_scan,
run_workbench,
save_workspace,
saved_coverage,
saved_draft,
scan_command,
set_remediation,
set_triage,
start_saved_scan,
start_scan_command,
@@ -85,14 +84,7 @@ def test_late_parent_draft_is_retained_without_mutating_frozen_stopped_seal(
) -> None:
state_dir, target, scan_id, scan_dir = empty_target_scan(tmp_path)
write_completed_contract(scan_dir, scan_id, target)
documents = {
key: json.loads((scan_dir / filename).read_text())
for key, filename in (
("manifest", "scan-manifest.json"),
("findings", "findings.json"),
("coverage", "coverage.json"),
)
}
documents = read_draft_documents(scan_dir)
fail_scan(state_dir, scan_id, "Stopped.")
stopped = get_scan(state_dir, scan_id)["scan"]
seal = (scan_dir / "scan-manifest.json").read_bytes()
@@ -445,14 +437,7 @@ def test_model_only_draft_is_available_before_findings_and_survives_stop(
scan_id, scan_dir = start_workspace_scan(state_dir, str(saved["id"]), tmp_path / "scans")
update_progress(state_dir, scan_id, "--phase", "threat_model")
write_completed_contract(scan_dir, scan_id, target)
documents = {
key: json.loads((scan_dir / filename).read_text())
for key, filename in (
("manifest", "scan-manifest.json"),
("findings", "findings.json"),
("coverage", "coverage.json"),
)
}
documents = read_draft_documents(scan_dir)
model = {
"format": "markdown",
"content": "# Service Boundaries\n\nQueue producers and consumers.\n",
@@ -554,14 +539,7 @@ def test_invalid_model_or_binding_keeps_history_available_for_semantic_repair(
saved = create_saved_workspace(state_dir, target)
scan_id, scan_dir = start_workspace_scan(state_dir, str(saved["id"]), tmp_path / "scans")
write_completed_contract(scan_dir, scan_id, target)
documents = {
key: json.loads((scan_dir / filename).read_text())
for key, filename in (
("manifest", "scan-manifest.json"),
("findings", "findings.json"),
("coverage", "coverage.json"),
)
}
documents = read_draft_documents(scan_dir)
model = {"summary": "Queue boundaries.", "assets": ["Stored messages"]}
documents["manifest"]["scan"].update(threatModel=model, complete=False)
malformed = json.loads(json.dumps(documents["manifest"]))
@@ -1149,17 +1127,20 @@ def test_export_rejects_replaced_scan_directory(tmp_path: Path) -> None:
assert not (outside / "exports" / "findings.csv").exists()
def symlink_scan_parent(scan_dir: Path, replacement_parent: Path) -> Path:
stored_parent = scan_dir.parent
moved_parent = stored_parent.with_name(f"{stored_parent.name}.moved")
stored_parent.rename(moved_parent)
shutil.copytree(moved_parent, replacement_parent)
stored_parent.symlink_to(replacement_parent, target_is_directory=True)
return replacement_parent / scan_dir.name
def test_csv_export_rejects_replaced_scan_directory_ancestor(tmp_path: Path) -> None:
state_dir, target, scan_id, scan_dir = empty_target_scan(tmp_path)
write_completed_contract(scan_dir, scan_id, target)
scan_command(state_dir, "complete-scan", scan_id)
stored_parent = scan_dir.parent
moved_parent = stored_parent.with_name(f"{stored_parent.name}.moved")
stored_parent.rename(moved_parent)
replacement_parent = tmp_path / "replacement-parent"
shutil.copytree(moved_parent, replacement_parent)
stored_parent.symlink_to(replacement_parent, target_is_directory=True)
replacement_scan_dir = replacement_parent / scan_dir.name
replacement_scan_dir = symlink_scan_parent(scan_dir, tmp_path / "replacement-parent")
failed = scan_command(state_dir, "export-findings", scan_id, "--format", "csv", check=False)
assert failed["returncode"] != 0
assert not (replacement_scan_dir / "exports" / "findings.csv").exists()
@@ -1179,13 +1160,7 @@ def test_completion_rejects_replaced_scan_directory(tmp_path: Path) -> None:
def test_completion_rejects_replaced_scan_directory_ancestor(tmp_path: Path) -> None:
state_dir, target, scan_id, scan_dir = empty_target_scan(tmp_path)
write_completed_contract(scan_dir, scan_id, target)
stored_parent = scan_dir.parent
moved_parent = stored_parent.with_name(f"{stored_parent.name}.moved")
stored_parent.rename(moved_parent)
replacement_parent = tmp_path / "replacement-parent"
shutil.copytree(moved_parent, replacement_parent)
stored_parent.symlink_to(replacement_parent, target_is_directory=True)
replacement_scan_dir = replacement_parent / scan_dir.name
replacement_scan_dir = symlink_scan_parent(scan_dir, tmp_path / "replacement-parent")
failed = scan_command(state_dir, "complete-scan", scan_id, check=False)
assert failed["returncode"] != 0
assert not (replacement_scan_dir / "exports" / "results.sarif").exists()
@@ -1196,32 +1171,14 @@ def test_remediation_apply_rejects_replaced_scan_directory_ancestor(tmp_path: Pa
write_completed_contract(scan_dir, scan_id, target)
completed = scan_command(state_dir, "complete-scan", scan_id)["scan"]
occurrence_id = str(completed["findings"][0]["occurrenceId"])
request_id = str(uuid.uuid4())
request = RemediationRequest(state_dir, occurrence_id)
generation_token = str(uuid.uuid4())
request_remediation(state_dir, occurrence_id, request_id, generation_token)
request.start(generation_token)
patch_path = scan_dir / "remediation.patch"
patch_path.write_text("diff --git a/src/extract.py b/src/extract.py\n")
set_remediation(
state_dir,
occurrence_id,
request_id,
generation_token,
"1",
"generated",
"--patch-path",
patch_path.name,
"--patch-digest",
f"sha256:{hashlib.sha256(patch_path.read_bytes()).hexdigest()}",
)
stored_parent = scan_dir.parent
moved_parent = stored_parent.with_name(f"{stored_parent.name}.moved")
stored_parent.rename(moved_parent)
replacement_parent = tmp_path / "replacement-parent"
shutil.copytree(moved_parent, replacement_parent)
stored_parent.symlink_to(replacement_parent, target_is_directory=True)
failed = request_remediation_action(
state_dir, occurrence_id, request_id, "2", "apply", str(uuid.uuid4()), check=False
)
request.generate(generation_token, patch_path)
symlink_scan_parent(scan_dir, tmp_path / "replacement-parent")
failed = request.request_action("2", "apply", str(uuid.uuid4()), check=False)
assert "canonical non-symlink directory" in str(failed["stderr"])
@@ -1246,14 +1203,7 @@ def test_parent_draft_preserves_reconciled_candidate_identity_before_publication
target,
coverage_mode="deep_repository" if mode == "deep" else "repository",
)
documents = {
key: json.loads((scan_dir / filename).read_text())
for key, filename in (
("manifest", "scan-manifest.json"),
("findings", "findings.json"),
("coverage", "coverage.json"),
)
}
documents = read_draft_documents(scan_dir)
if mode == "deep":
documents["manifest"]["scan"]["complete"] = False
documents["findings"]["findings"] = []
@@ -1400,14 +1350,7 @@ def test_deep_draft_admission_survives_interrupted_projection(
workspace = create_saved_workspace(state_dir, target, mode="deep")
scan_id, scan_dir = start_workspace_scan(state_dir, str(workspace["id"]), tmp_path / "scans")
write_completed_contract(scan_dir, scan_id, target, coverage_mode="deep_repository")
documents = {
key: json.loads((scan_dir / filename).read_text())
for key, filename in (
("manifest", "scan-manifest.json"),
("findings", "findings.json"),
("coverage", "coverage.json"),
)
}
documents = read_draft_documents(scan_dir)
documents["manifest"]["scan"]["complete"] = False
raw = {
"scanId": scan_id,
File diff suppressed because it is too large Load Diff
@@ -47,11 +47,10 @@ def test_scan_failure_keeps_complete_diagnostic_and_existing_terminal_value(
workspace = create_saved_workspace(state_dir, target)
started = start_delivered_scan(
state_dir,
"--workspace-id",
str(workspace["id"]),
"--scan-root",
str(tmp_path / "scans"),
)["results"]
)
scan_id = str(started["scanId"])
failed = fail_scan(state_dir, scan_id, message)["scan"]
@@ -7,33 +7,26 @@ from pathlib import Path
import pytest
from test_workbench_standard_deep_results import deep_scan_fixture
from workbench_test_support import read_review_state, run_workbench, write_completed_contract
from workbench_test_support import (
read_draft_documents,
read_review_state,
run_workbench,
write_completed_contract,
)
@pytest.mark.parametrize("filename", ["findings.json", "coverage.json"])
@pytest.mark.parametrize("previous", ["unfinished", "symlink"])
def test_terminal_deep_draft_compares_previous_bytes_without_parsing_review_documents(
tmp_path: Path, filename: str, previous: str
) -> None:
state_dir, codex_home, target, scan_dir, scan_id = deep_scan_fixture(tmp_path)
def stage_model_draft(tmp_path, scan_dir, scan_id, target, model, *, complete=True):
contract_dir = tmp_path / "contract"
contract_dir.mkdir()
write_completed_contract(
contract_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
)
documents = {
key: json.loads((contract_dir / name).read_text())
for key, name in (
("manifest", "scan-manifest.json"),
("findings", "findings.json"),
("coverage", "coverage.json"),
)
}
model = {"format": "markdown", "content": "# Saved model\n"}
documents = read_draft_documents(contract_dir)
documents["manifest"] = {
"scan": {
**{key: documents["manifest"]["scan"][key] for key in ("target", "scope")},
"threatModel": model,
**({} if complete else {"complete": False}),
}
}
documents["findings"]["findings"] = []
@@ -42,6 +35,17 @@ def test_terminal_deep_draft_compares_previous_bytes_without_parsing_review_docu
drafts.mkdir(exist_ok=True)
staged = drafts / f"{uuid.uuid4()}.json"
staged.write_text(json.dumps(documents))
return documents, staged
@pytest.mark.parametrize("filename", ["findings.json", "coverage.json"])
@pytest.mark.parametrize("previous", ["unfinished", "symlink"])
def test_terminal_deep_draft_compares_previous_bytes_without_parsing_review_documents(
tmp_path: Path, filename: str, previous: str
) -> None:
state_dir, codex_home, target, scan_dir, scan_id = deep_scan_fixture(tmp_path)
model = {"format": "markdown", "content": "# Saved model\n"}
_, staged = stage_model_draft(tmp_path, scan_dir, scan_id, target, model)
args = ("write-scan-draft", "--scan-id", scan_id, "--draft-path", str(staged))
environment = {"CODEX_HOME": str(codex_home)}
run_workbench(state_dir, *args, environment=environment)
@@ -131,33 +135,10 @@ def test_deep_setup_draft_before_orchestration(
),
)
scan_id = str(registered["scanId"])
contract_dir = tmp_path / "contract"
contract_dir.mkdir()
write_completed_contract(
contract_dir, scan_id, target, relative_path="app.py", coverage_mode="deep_repository"
)
documents = {
key: json.loads((contract_dir / name).read_text())
for key, name in (
("manifest", "scan-manifest.json"),
("findings", "findings.json"),
("coverage", "coverage.json"),
)
}
model = {"format": "markdown", "content": "# Supplied setup model\n"}
documents["manifest"] = {
"scan": {
**{key: documents["manifest"]["scan"][key] for key in ("target", "scope")},
"threatModel": model,
**({} if complete else {"complete": False}),
}
}
documents["findings"]["findings"] = []
documents["coverage"].update(surfaces=[], deferred=[])
drafts = scan_dir / "drafts"
drafts.mkdir(exist_ok=True)
staged = drafts / f"{uuid.uuid4()}.json"
staged.write_text(json.dumps(documents))
documents, staged = stage_model_draft(
tmp_path, scan_dir, scan_id, target, model, complete=complete
)
args = ("write-scan-draft", "--scan-id", scan_id, "--draft-path", str(staged))
environment = {"CODEX_HOME": str(codex_home)}
if complete and not initialized:
@@ -32,11 +32,10 @@ def _create_workspace(state_dir: Path, target: Path) -> str:
def _start_scan(state_dir: Path, workspace_id: str, scan_root: Path) -> dict[str, Any]:
return start_delivered_scan(
state_dir,
"--workspace-id",
workspace_id,
"--scan-root",
str(scan_root),
)["results"]
)
def _complete_scan(
@@ -4,6 +4,7 @@ import json
import os
import sqlite3
from contextlib import closing
from functools import partial
from pathlib import Path
import pytest
@@ -11,15 +12,20 @@ import pytest
TIMESTAMP = "2026-08-01T00:00:00Z"
def workflow(api, connection, action, *, workflow_id="synthetic-workflow", **payload):
def run_workflow(api, connection, action, *, workflow_id="synthetic-workflow", **payload):
return api["finding_workflow"](
connection, {"id": workflow_id, "action": action, **payload}, TIMESTAMP
)
@pytest.fixture
def workflow(workbench_api, workbench_db):
return partial(run_workflow, workbench_api, workbench_db)
@pytest.mark.parametrize("optional", [False, True])
def test_source_snapshot_excludes_private_storage_without_hiding_source(
workbench_api, workbench_db, tmp_path, monkeypatch, optional
workflow, tmp_path, monkeypatch, optional
):
repository = tmp_path / "repository"
repository.mkdir()
@@ -39,8 +45,6 @@ def test_source_snapshot_excludes_private_storage_without_hiding_source(
def snapshot():
return workflow(
workbench_api,
workbench_db,
"source",
repository=str(repository),
privateStatePaths=[str(private)],
@@ -54,26 +58,14 @@ def test_source_snapshot_excludes_private_storage_without_hiding_source(
source.write_text("changed source")
assert snapshot()["content"] != before["content"]
with pytest.raises(SystemExit, match="repository root"):
workflow(
workbench_api,
workbench_db,
"source",
repository=str(repository),
privateStatePaths=[str(repository)],
)
workflow("source", repository=str(repository), privateStatePaths=[str(repository)])
with pytest.raises(SystemExit, match="absolute paths"):
workflow(
workbench_api,
workbench_db,
"source",
repository=str(repository),
privateStatePaths=["relative-state"],
)
workflow("source", repository=str(repository), privateStatePaths=["relative-state"])
@pytest.mark.parametrize("location", ["root", "descendant"])
def test_source_snapshot_preserves_unreadable_directory_errors(
workbench_api, workbench_db, tmp_path, monkeypatch, location
workflow, tmp_path, monkeypatch, location
):
repository = tmp_path / "repository"
repository.mkdir()
@@ -95,8 +87,6 @@ def test_source_snapshot_preserves_unreadable_directory_errors(
def snapshot(excluded):
return workflow(
workbench_api,
workbench_db,
"source",
repository=str(repository),
gitDisabled=True,
@@ -113,37 +103,25 @@ def test_source_snapshot_preserves_unreadable_directory_errors(
@pytest.mark.parametrize("stage", ["scan", "publish", "dedupe"])
def test_failed_stages_resume_and_completed_results_are_immutable(
workbench_api, workbench_db, stage
):
assert workflow(workbench_api, workbench_db, "get") == {"workflow": None}
bound = workflow(workbench_api, workbench_db, "bind", binding={})["workflow"]
def test_failed_stages_resume_and_completed_results_are_immutable(workflow, stage):
assert workflow("get") == {"workflow": None}
bound = workflow("bind", binding={})["workflow"]
assert bound["stages"] == {
name: {"status": "pending"} for name in ("scan", "publish", "dedupe")
}
assert (
workflow(workbench_api, workbench_db, "begin", stage=stage)["workflow"]["stages"][stage][
"status"
]
== "running"
)
failed = workflow(workbench_api, workbench_db, "fail", stage=stage, error="Synthetic failure")
assert workflow("begin", stage=stage)["workflow"]["stages"][stage]["status"] == "running"
failed = workflow("fail", stage=stage, error="Synthetic failure")
assert failed["workflow"]["stages"][stage] == {"status": "failed", "error": "Synthetic failure"}
assert (
workflow(workbench_api, workbench_db, "begin", stage=stage)["workflow"]["stages"][stage][
"status"
]
== "running"
)
assert workflow("begin", stage=stage)["workflow"]["stages"][stage]["status"] == "running"
result = {"findingIds": [], "duplicateGroups": []}
completed = workflow(workbench_api, workbench_db, "complete", stage=stage, result=result)
completed = workflow("complete", stage=stage, result=result)
assert completed["workflow"]["stages"][stage] == {"status": "completed", "result": result}
for action, payload in [
("begin", {}),
("fail", {"error": "Late failure", "result": {"unexpected": True}}),
("complete", {"result": {"unexpected": True}}),
]:
assert workflow(workbench_api, workbench_db, action, stage=stage, **payload) == completed
assert workflow(action, stage=stage, **payload) == completed
@pytest.mark.parametrize(
@@ -156,59 +134,42 @@ def test_failed_stages_resume_and_completed_results_are_immutable(
({"scope": {"allRepositories": True}}, {"scope": {"repositoryId": "repository-a"}}),
],
)
def test_bindings_and_workflow_identities_remain_separate(
workbench_api, workbench_db, binding, changed
):
workflow(workbench_api, workbench_db, "bind", binding=binding)
saved = workflow(
workbench_api, workbench_db, "complete", stage="dedupe", result={"duplicateGroups": []}
)
def test_bindings_and_workflow_identities_remain_separate(workflow, workbench_db, binding, changed):
workflow("bind", binding=binding)
saved = workflow("complete", stage="dedupe", result={"duplicateGroups": []})
with pytest.raises(SystemExit, match="already bound to a different"):
workflow(workbench_api, workbench_db, "bind", binding=changed)
workflow("bind", binding=changed)
assert not workbench_db.in_transaction
assert workflow(workbench_api, workbench_db, "get") == saved
separate = workflow(
workbench_api, workbench_db, "bind", workflow_id="separate", binding=changed
)
assert workflow("get") == saved
separate = workflow("bind", workflow_id="separate", binding=changed)
assert separate["workflow"]["id"] == "separate"
assert separate["workflow"]["stages"]["dedupe"] == {"status": "pending"}
for key, value in changed.items():
assert separate["workflow"][key] == value
assert workflow(workbench_api, workbench_db, "get") == saved
assert workflow("get") == saved
@pytest.mark.parametrize("result", [{"duplicateGroups": []}, {"duplicateGroups": [["a", "b"]]}])
def test_pending_publication_payload_survives_failure_until_completion(
workbench_api, workbench_db, result
):
workflow(workbench_api, workbench_db, "bind", binding={})
workflow(workbench_api, workbench_db, "begin", stage="dedupe")
def test_pending_publication_payload_survives_failure_until_completion(workflow, result):
workflow("bind", binding={})
workflow("begin", stage="dedupe")
pending = {"groups": result["duplicateGroups"]}
prepared = workflow(
workbench_api,
workbench_db,
"prepare-dedupe",
stage="dedupe",
result=result,
pendingWrite=pending,
)
prepared = workflow("prepare-dedupe", stage="dedupe", result=result, pendingWrite=pending)
assert prepared["workflow"]["stages"]["dedupe"] == {
"status": "running",
"result": result,
"pendingWrite": pending,
}
workflow(workbench_api, workbench_db, "fail", stage="dedupe", error="Lost acknowledgement")
resumed = workflow(workbench_api, workbench_db, "begin", stage="dedupe")["workflow"]["stages"][
"dedupe"
]
workflow("fail", stage="dedupe", error="Lost acknowledgement")
resumed = workflow("begin", stage="dedupe")["workflow"]["stages"]["dedupe"]
assert resumed["result"] == result
assert resumed["pendingWrite"] == pending
completed = workflow(workbench_api, workbench_db, "complete", stage="dedupe", result=result)
completed = workflow("complete", stage="dedupe", result=result)
assert completed["workflow"]["stages"]["dedupe"] == {"status": "completed", "result": result}
def test_review_checkpoints_keep_the_first_valid_result_and_enforce_workflow_ownership(
workbench_api, workbench_db
workflow, workbench_db
):
binding = {
"version": 1,
@@ -228,59 +189,29 @@ def test_review_checkpoints_keep_the_first_valid_result_and_enforce_workflow_own
}
result = {"decision": "DISTINCT", "rationale": "Independent corrections"}
with pytest.raises(sqlite3.IntegrityError):
workflow(
workbench_api,
workbench_db,
"save-review",
key="review-1",
binding=binding,
result=result,
)
workflow(workbench_api, workbench_db, "bind", binding={})
assert workflow(workbench_api, workbench_db, "get-review", key="review-1") == {"review": None}
workflow(
workbench_api, workbench_db, "save-review", key="review-1", binding=binding, result=result
)
workflow(
workbench_api,
workbench_db,
"save-review",
key="review-1",
binding=binding,
result={"unexpected": True},
)
assert workflow(workbench_api, workbench_db, "get-review", key="review-1") == {"review": result}
assert workflow(
workbench_api, workbench_db, "get-review", workflow_id="another", key="review-1"
) == {"review": None}
workflow("save-review", key="review-1", binding=binding, result=result)
workflow("bind", binding={})
assert workflow("get-review", key="review-1") == {"review": None}
workflow("save-review", key="review-1", binding=binding, result=result)
workflow("save-review", key="review-1", binding=binding, result={"unexpected": True})
assert workflow("get-review", key="review-1") == {"review": result}
assert workflow("get-review", workflow_id="another", key="review-1") == {"review": None}
row = workbench_db.execute("SELECT * FROM finding_workflow_reviews").fetchone()
assert row["source_repository_path"] == binding["source"]["repository"]
assert row["settings_digest"] == binding["settingsDigest"]
assert json.loads(row["result_json"]) == result
replacement = {"assessment": {"report": "Regenerated validation"}, "evidenceDigest": "new"}
workflow("save-review", key="review-1", binding=binding, result=replacement, replace=True)
assert workflow("get-review", key="review-1") == {"review": result}
workflow(
workbench_api,
workbench_db,
"save-review",
key="review-1",
binding=binding,
result=replacement,
replace=True,
)
assert workflow(workbench_api, workbench_db, "get-review", key="review-1") == {"review": result}
workflow(
workbench_api,
workbench_db,
"save-review",
key="review-1",
binding={**binding, "stage": "scan-validation"},
result=replacement,
replace=True,
)
assert workflow(workbench_api, workbench_db, "get-review", key="review-1") == {
"review": replacement
}
assert workflow("get-review", key="review-1") == {"review": replacement}
@pytest.mark.parametrize(
@@ -292,13 +223,13 @@ def test_review_checkpoints_keep_the_first_valid_result_and_enforce_workflow_own
],
)
def test_rejected_workflow_mutations_roll_back_without_leaking_state(
workbench_api, workbench_db, payload
workflow, workbench_db, payload
):
saved = workflow(workbench_api, workbench_db, "bind", binding={})
saved = workflow("bind", binding={})
with pytest.raises(SystemExit):
workflow(workbench_api, workbench_db, **payload)
workflow(**payload)
assert not workbench_db.in_transaction
assert workflow(workbench_api, workbench_db, "get") == saved
assert workflow("get") == saved
def test_workflow_column_migration_is_atomic_and_preserves_resume_state(workbench_api, tmp_path):
@@ -428,13 +359,10 @@ def test_workflow_column_migration_is_atomic_and_preserves_resume_state(workbenc
connection.row_factory = sqlite3.Row
connection.execute("PRAGMA foreign_keys = ON")
with closing(connection):
migrated_workflow = partial(run_workflow, workbench_api, connection)
for state in (completed, unfinished, pending):
assert workflow(workbench_api, connection, "get", workflow_id=state["id"]) == {
"workflow": state
}
assert workflow(
workbench_api,
connection,
assert migrated_workflow("get", workflow_id=state["id"]) == {"workflow": state}
assert migrated_workflow(
"bind",
workflow_id=completed["id"],
binding={"scanId": completed["scanId"], "scope": completed["scope"]},
@@ -442,22 +370,14 @@ def test_workflow_column_migration_is_atomic_and_preserves_resume_state(workbenc
review = connection.execute("SELECT * FROM finding_workflow_reviews").fetchone()
assert review["scope_repository_id"] == completed["scope"]["repositoryId"]
assert review["prompt_digest"] == review_binding["promptDigest"]
assert workflow(
workbench_api,
connection,
"get-review",
workflow_id=completed["id"],
key="synthetic-review",
assert migrated_workflow(
"get-review", workflow_id=completed["id"], key="synthetic-review"
) == {"review": review_result}
for stage in ("scan", "publish", "dedupe"):
state = workflow(
workbench_api, connection, "begin", workflow_id=completed["id"], stage=stage
)
state = migrated_workflow("begin", workflow_id=completed["id"], stage=stage)
assert state == {"workflow": completed}
workflow(workbench_api, connection, "begin", workflow_id=unfinished["id"], stage="scan")
resumed = workflow(
workbench_api,
connection,
migrated_workflow("begin", workflow_id=unfinished["id"], stage="scan")
resumed = migrated_workflow(
"complete",
workflow_id=unfinished["id"],
stage="scan",
@@ -470,38 +390,27 @@ def test_workflow_column_migration_is_atomic_and_preserves_resume_state(workbenc
@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="FIFOs require a Unix filesystem")
def test_optional_review_snapshot_disables_cache_for_unsupported_file_types(
workbench_api, workbench_db, tmp_path
):
def test_optional_review_snapshot_disables_cache_for_unsupported_file_types(workflow, tmp_path):
target = tmp_path / "repository"
target.mkdir()
source = target / "source.ts"
source.write_text("export const value = 1;\n", encoding="utf-8")
first = workflow(workbench_api, workbench_db, "source", repository=str(target))
first = workflow("source", repository=str(target))
assert first["source"]["content"].startswith("codex-security-snapshot/v1:")
pipe = target / "pipe"
os.mkfifo(pipe)
with pytest.raises(SystemExit, match="Unsupported local file type: pipe"):
workflow(workbench_api, workbench_db, "source", repository=str(target))
assert workflow(
workbench_api, workbench_db, "source", repository=str(target), optional=True
) == {"source": None}
workflow("source", repository=str(target))
assert workflow("source", repository=str(target), optional=True) == {"source": None}
pipe.unlink()
assert (
workflow(workbench_api, workbench_db, "source", repository=str(target), optional=True)
== first
)
assert workflow("source", repository=str(target), optional=True) == first
source.write_text("export const value = 2;\n", encoding="utf-8")
assert (
workflow(workbench_api, workbench_db, "source", repository=str(target), optional=True)[
"source"
]["content"]
workflow("source", repository=str(target), optional=True)["source"]["content"]
!= first["source"]["content"]
)
with pytest.raises(FileNotFoundError):
workflow(
workbench_api, workbench_db, "source", repository=str(target / "missing"), optional=True
)
workflow("source", repository=str(target / "missing"), optional=True)
@pytest.mark.skipif(
@@ -509,9 +418,7 @@ def test_optional_review_snapshot_disables_cache_for_unsupported_file_types(
reason="Mode permissions require a non-root Unix user",
)
@pytest.mark.parametrize("kind", ["file", "directory"])
def test_optional_review_snapshot_disables_cache_for_unreadable_entries(
workbench_api, workbench_db, tmp_path, kind
):
def test_optional_review_snapshot_disables_cache_for_unreadable_entries(workflow, tmp_path, kind):
target = tmp_path / "repository"
target.mkdir()
(target / "source.ts").write_text("export const value = 1;\n", encoding="utf-8")
@@ -521,78 +428,45 @@ def test_optional_review_snapshot_disables_cache_for_unreadable_entries(
(entry / "cache.txt").write_text("Synthetic cache data.", encoding="utf-8")
else:
entry.write_text("Synthetic cache data.", encoding="utf-8")
first = workflow(workbench_api, workbench_db, "source", repository=str(target), optional=True)
first = workflow("source", repository=str(target), optional=True)
mode = entry.stat().st_mode
entry.chmod(0)
try:
with pytest.raises((PermissionError, SystemExit)):
workflow(workbench_api, workbench_db, "source", repository=str(target))
assert workflow(
workbench_api, workbench_db, "source", repository=str(target), optional=True
) == {"source": None}
workflow("source", repository=str(target))
assert workflow("source", repository=str(target), optional=True) == {"source": None}
finally:
entry.chmod(mode)
assert (
workflow(workbench_api, workbench_db, "source", repository=str(target), optional=True)
== first
)
assert workflow("source", repository=str(target), optional=True) == first
with pytest.raises(FileNotFoundError):
workflow(
workbench_api, workbench_db, "source", repository=str(target / "missing"), optional=True
)
workflow("source", repository=str(target / "missing"), optional=True)
@pytest.mark.parametrize("metadata_name", [".git", ".svn"])
def test_optional_evidence_snapshot_includes_source_metadata(
workbench_api, workbench_db, tmp_path, metadata_name
):
def test_optional_evidence_snapshot_includes_source_metadata(workflow, tmp_path, metadata_name):
evidence = tmp_path / "evidence"
metadata = evidence / metadata_name
metadata.mkdir(parents=True)
(evidence / "proof.txt").write_text("Original proof.\n")
head = metadata / "HEAD"
head.write_text("Synthetic metadata.\n")
source = workflow(workbench_api, workbench_db, "source", repository=str(evidence))
before = workflow(
workbench_api,
workbench_db,
"source",
repository=str(evidence),
evidence=True,
optional=True,
)
source = workflow("source", repository=str(evidence))
before = workflow("source", repository=str(evidence), evidence=True, optional=True)
head.write_text("Changed metadata.\n")
assert workflow(workbench_api, workbench_db, "source", repository=str(evidence)) == source
assert (
workflow(
workbench_api,
workbench_db,
"source",
repository=str(evidence),
evidence=True,
optional=True,
)
!= before
)
assert workflow("source", repository=str(evidence)) == source
assert workflow("source", repository=str(evidence), evidence=True, optional=True) != before
if hasattr(os, "mkfifo"):
pipe = metadata / "pipe"
os.mkfifo(pipe)
try:
assert workflow(
workbench_api,
workbench_db,
"source",
repository=str(evidence),
evidence=True,
optional=True,
) == {"source": None}
assert workflow("source", repository=str(evidence), evidence=True, optional=True) == {
"source": None
}
finally:
pipe.unlink()
def test_optional_evidence_snapshot_does_not_follow_directory_links(
workbench_api, workbench_db, tmp_path
):
def test_optional_evidence_snapshot_does_not_follow_directory_links(workflow, tmp_path):
evidence = tmp_path / "evidence"
evidence.mkdir()
outside = tmp_path / "outside"
@@ -606,40 +480,18 @@ def test_optional_evidence_snapshot_does_not_follow_directory_links(
if os.name == "nt":
pytest.skip("Directory symlinks are unavailable on this Windows filesystem")
raise
before = workflow(
workbench_api,
workbench_db,
"source",
repository=str(evidence),
evidence=True,
optional=True,
)
before = workflow("source", repository=str(evidence), evidence=True, optional=True)
source.write_text("Changed outside contents.\n")
assert (
workflow(
workbench_api,
workbench_db,
"source",
repository=str(evidence),
evidence=True,
optional=True,
)
== before
)
assert workflow("source", repository=str(evidence), evidence=True, optional=True) == before
evidence.rename(tmp_path / "original")
evidence.symlink_to(outside, target_is_directory=True)
assert workflow(
workbench_api,
workbench_db,
"source",
repository=str(evidence),
evidence=True,
optional=True,
) == {"source": None}
assert workflow("source", repository=str(evidence), evidence=True, optional=True) == {
"source": None
}
@pytest.mark.parametrize("kind", ["missing", "file", "unreadable"])
def test_optional_evidence_snapshot_unavailable_roots(workbench_api, workbench_db, tmp_path, kind):
def test_optional_evidence_snapshot_unavailable_roots(workflow, tmp_path, kind):
evidence = tmp_path / "evidence"
if kind == "file":
evidence.write_text("Not a directory.\n")
@@ -649,23 +501,12 @@ def test_optional_evidence_snapshot_unavailable_roots(workbench_api, workbench_d
evidence.mkdir()
evidence.chmod(0)
try:
assert workflow(
workbench_api,
workbench_db,
"source",
repository=str(evidence),
evidence=True,
optional=True,
) == {"source": None}
assert workflow("source", repository=str(evidence), evidence=True, optional=True) == {
"source": None
}
if kind == "missing":
with pytest.raises(FileNotFoundError):
workflow(
workbench_api,
workbench_db,
"source",
repository=str(evidence),
optional=True,
)
workflow("source", repository=str(evidence), optional=True)
finally:
if kind == "unreadable":
evidence.chmod(0o700)
@@ -34,9 +34,9 @@ def complete_scan(
workspace = save_workspace(
state_dir, str(workspace["id"]), str(target), include_paths[0], "standard"
)
started = start_delivered_scan(state_dir, "--workspace-id", str(workspace["id"]))
scan_id = str(started["results"]["scanId"])
scan_dir = Path(str(started["results"]["scanDir"]))
started = start_delivered_scan(state_dir, str(workspace["id"]))
scan_id = str(started["scanId"])
scan_dir = Path(str(started["scanDir"]))
write_completed_contract(
scan_dir,
scan_id,
@@ -259,7 +259,7 @@ def test_repository_index_reports_latest_scan_open_findings_and_missing_checkout
"Fixture close decision.",
)
running_workspace = create_saved_workspace(state_dir, first_target)
older_running = start_delivered_scan(state_dir, "--workspace-id", str(running_workspace["id"]))
older_running = start_delivered_scan(state_dir, str(running_workspace["id"]))
complete_scan(state_dir, first_target, identity_anchor="first-finding")
distinct_first = complete_scan(
state_dir,
@@ -269,7 +269,7 @@ def test_repository_index_reports_latest_scan_open_findings_and_missing_checkout
relative_path="docs/extract.py",
)
latest_second = complete_scan(state_dir, second_target, identity_anchor="second-finding")
update_progress(state_dir, str(older_running["results"]["scanId"]), "--phase", "discovery")
update_progress(state_dir, str(older_running["scanId"]), "--phase", "discovery")
second_target.rename(tmp_path / "moved-second-repo")
repositories = run_workbench(state_dir, "list-repositories")["repositories"]
@@ -13,8 +13,8 @@ from workbench_test_support import (
def test_progress_preserves_phase_receipts_until_validation(tmp_path: Path) -> None:
state_dir, target = empty_target_paths(tmp_path)
saved = create_saved_workspace(state_dir, target)
started = start_delivered_scan(state_dir, "--workspace-id", str(saved["id"]))
scan_id = str(started["results"]["scanId"])
started = start_delivered_scan(state_dir, str(saved["id"]))
scan_id = str(started["scanId"])
discovery = update_progress(
state_dir,
@@ -69,8 +69,8 @@ def test_progress_preserves_phase_receipts_until_validation(tmp_path: Path) -> N
def test_historical_preflight_issues_survive_progress_updates(tmp_path: Path) -> None:
state_dir, target = empty_target_paths(tmp_path)
saved = create_saved_workspace(state_dir, target)
started = start_delivered_scan(state_dir, "--workspace-id", str(saved["id"]))
scan_id = str(started["results"]["scanId"])
started = start_delivered_scan(state_dir, str(saved["id"]))
scan_id = str(started["scanId"])
issues = [
{
"capability": "delegated_workers",
@@ -2,11 +2,9 @@ from __future__ import annotations
import copy
import json
import os
from types import SimpleNamespace
import pytest
from test_deep_scan_successful_publication import complete
from test_deep_scan_successful_publication import publication_scan as publication_scan
from workbench_test_support import read_review_state, saved_draft, write_checkpoint
@@ -30,9 +28,10 @@ def test_stopped_scan_requires_valid_rejection_evidence_before_sealing(
finding = copy.deepcopy(scan.findings[0])
finding["provenance"] = {"source": "local_plugin", "candidateId": "candidate-a"}
checkpoint = write_checkpoint(
scan.scan_dir / "checkpoints", saved_draft(scan.scan_id, findings=[finding])
scan.scan_dir / "checkpoints",
saved_draft(scan.scan_id, findings=[finding]),
mtime_ns=100,
)
os.utime(checkpoint, ns=(100, 100))
checkpoint_bytes = checkpoint.read_bytes()
(scan.scan_dir / "findings.json").write_text(json.dumps({"findings": []}))
scan.coverage["surfaces"] = (
@@ -98,7 +97,7 @@ def test_stopped_scan_requires_valid_rejection_evidence_before_sealing(
],
)
def test_standard_completion_requires_valid_closure_evidence_before_sealing(
workbench_api, workbench_db, publication_scan, reason, invalid
workbench_db, publication_scan, reason, invalid
):
scan = publication_scan(mode="standard")
report_path = scan.scan_dir / "report.md"
@@ -109,8 +108,8 @@ def test_standard_completion_requires_valid_closure_evidence_before_sealing(
scan.scan_id,
deferred=[{"id": "review", "reason": "Review authorization remains pending."}],
),
mtime_ns=100,
)
os.utime(checkpoint, ns=(100, 100))
checkpoint_bytes = checkpoint.read_bytes()
scan.coverage["deferred"] = []
closure = {"id": "review", "reason": reason}
@@ -121,9 +120,9 @@ def test_standard_completion_requires_valid_closure_evidence_before_sealing(
if invalid:
with pytest.raises(SystemExit, match="well-formed Unicode"):
complete(workbench_api, workbench_db, scan)
scan.complete()
else:
completed = complete(workbench_api, workbench_db, scan)
completed = scan.complete()
assert completed["warnings"] == []
assert checkpoint.read_bytes() == checkpoint_bytes
@@ -1,19 +1,14 @@
from __future__ import annotations
import hashlib
import subprocess
import uuid
from pathlib import Path
import pytest
from workbench_test_support import (
cancel_remediation_request,
RemediationRequest,
empty_target_paths,
mark_remediation_delivered,
request_remediation,
request_remediation_action,
run_workbench,
set_remediation,
start_saved_scan,
write_completed_contract,
write_remediation_patch,
@@ -32,78 +27,47 @@ def test_cancel_finding_remediation_request_restores_previous_state(
completed = run_workbench(state_dir, "complete-scan", "--scan-id", scan_id)["scan"]
occurrence_id = str(completed["findings"][0]["occurrenceId"])
canceled_request_id = str(uuid.uuid4())
canceled_request = RemediationRequest(state_dir, occurrence_id)
canceled_token = str(uuid.uuid4())
requested_initial = request_remediation(
state_dir, occurrence_id, canceled_request_id, canceled_token
)["scan"]
canceled_initial = cancel_remediation_request(
state_dir, occurrence_id, canceled_request_id, canceled_token
)["scan"]
requested_initial = canceled_request.start(canceled_token)["scan"]
canceled_initial = canceled_request.cancel(canceled_token)["scan"]
assert canceled_initial["findings"][0]["remediationState"] == {"state": "idle"}
assert canceled_initial["updatedAt"] > requested_initial["updatedAt"]
replayed_cancel = cancel_remediation_request(
state_dir, occurrence_id, canceled_request_id, canceled_token
)["scan"]
replayed_cancel = canceled_request.cancel(canceled_token)["scan"]
assert replayed_cancel["findings"][0]["remediationState"] == {"state": "idle"}
request_id = str(uuid.uuid4())
request = RemediationRequest(state_dir, occurrence_id)
generation_token = str(uuid.uuid4())
request_remediation(state_dir, occurrence_id, request_id, generation_token)
request.start(generation_token)
patch_path = scan_dir / "remediation.patch"
write_remediation_patch(patch_path)
generated = set_remediation(
state_dir,
occurrence_id,
request_id,
generation_token,
"1",
"generated",
"--patch-path",
patch_path.name,
"--patch-digest",
f"sha256:{hashlib.sha256(patch_path.read_bytes()).hexdigest()}",
)["scan"]
generated = request.generate(generation_token, patch_path)["scan"]
assert generated["findings"][0]["remediationState"]["state"] == "generated"
replacement_request_id = str(uuid.uuid4())
replacement_request = RemediationRequest(state_dir, occurrence_id)
replacement_token = str(uuid.uuid4())
request_remediation(state_dir, occurrence_id, replacement_request_id, replacement_token)
canceled_replacement = cancel_remediation_request(
state_dir, occurrence_id, replacement_request_id, replacement_token
)["scan"]
replacement_request.start(replacement_token)
canceled_replacement = replacement_request.cancel(replacement_token)["scan"]
restored = canceled_replacement["findings"][0]["remediationState"]
assert restored["requestId"] == request_id
assert restored["requestId"] == request.id
assert restored["state"] == "generated"
assert restored["pendingAction"] is None
assert restored["patchPath"] == patch_path.name
apply_token = str(uuid.uuid4())
request_remediation_action(
state_dir, occurrence_id, request_id, str(restored["version"]), "apply", apply_token
)
canceled_apply = cancel_remediation_request(state_dir, occurrence_id, request_id, apply_token)[
"scan"
]
request.request_action(str(restored["version"]), "apply", apply_token)
canceled_apply = request.cancel(apply_token)["scan"]
restored_after_apply = canceled_apply["findings"][0]["remediationState"]
assert restored_after_apply["state"] == "generated"
assert restored_after_apply["pendingAction"] is None
assert restored_after_apply["actionClaimToken"] is None
apply_token = str(uuid.uuid4())
apply_requested = request_remediation_action(
state_dir,
occurrence_id,
request_id,
str(restored_after_apply["version"]),
"apply",
apply_token,
apply_requested = request.request_action(
str(restored_after_apply["version"]), "apply", apply_token
)["scan"]
subprocess.run(["git", "apply", "--no-index", str(patch_path)], cwd=target, check=True)
applied = set_remediation(
state_dir,
occurrence_id,
request_id,
applied = request.update(
apply_token,
str(apply_requested["findings"][0]["remediationState"]["version"]),
"applied",
@@ -112,20 +76,12 @@ def test_cancel_finding_remediation_request_restores_previous_state(
)["scan"]
verify_token = str(uuid.uuid4())
verify_requested = request_remediation_action(
state_dir,
occurrence_id,
request_id,
str(applied["findings"][0]["remediationState"]["version"]),
"verify",
verify_token,
verify_requested = request.request_action(
str(applied["findings"][0]["remediationState"]["version"]), "verify", verify_token
)["scan"]["findings"][0]["remediationState"]
if verification_started:
mark_remediation_delivered(state_dir, occurrence_id, request_id, verify_token)
verify_requested = set_remediation(
state_dir,
occurrence_id,
request_id,
request.mark_delivered(verify_token)
verify_requested = request.update(
verify_token,
str(verify_requested["version"]),
"verifying",
@@ -138,16 +94,14 @@ def test_cancel_finding_remediation_request_restores_previous_state(
"--occurrence-id",
occurrence_id,
"--request-id",
request_id,
request.id,
"--action-token",
str(uuid.uuid4()),
check=False,
)
assert wrong_owner["returncode"] != 0
assert "owned by a different action token" in wrong_owner["stderr"]
canceled_verify = cancel_remediation_request(
state_dir, occurrence_id, request_id, verify_token
)["scan"]
canceled_verify = request.cancel(verify_token)["scan"]
restored_after_verify = canceled_verify["findings"][0]["remediationState"]
assert restored_after_verify["state"] == "applied"
assert restored_after_verify["pendingAction"] is None
@@ -158,28 +112,15 @@ def test_cancel_finding_remediation_request_restores_previous_state(
assert restored_after_verify["patchPath"] == patch_path.name
assert restored_after_verify["patchDigest"] == verify_requested["patchDigest"]
assert source.read_text() == "fixed\n"
replayed_verify = cancel_remediation_request(
state_dir, occurrence_id, request_id, verify_token
)["scan"]["findings"][0]["remediationState"]
replayed_verify = request.cancel(verify_token)["scan"]["findings"][0]["remediationState"]
assert replayed_verify == restored_after_verify
stale_update = set_remediation(
state_dir,
occurrence_id,
request_id,
verify_token,
str(verify_requested["version"]),
"failed",
check=False,
stale_update = request.update(
verify_token, str(verify_requested["version"]), "failed", check=False
)
assert stale_update["returncode"] != 0
assert "This remediation request changed" in stale_update["stderr"]
retried_verify = request_remediation_action(
state_dir,
occurrence_id,
request_id,
str(restored_after_verify["version"]),
"verify",
str(uuid.uuid4()),
retried_verify = request.request_action(
str(restored_after_verify["version"]), "verify", str(uuid.uuid4())
)["scan"]["findings"][0]["remediationState"]
assert retried_verify["pendingAction"] == "verify"
@@ -8,14 +8,9 @@ from pathlib import Path
from typing import Any
from workbench_test_support import (
cancel_remediation_request,
claim_remediation_resend,
RemediationRequest,
empty_target_paths,
mark_remediation_delivered,
request_remediation,
request_remediation_action,
scan_command,
set_remediation,
set_triage,
start_saved_scan,
write_completed_contract,
@@ -24,17 +19,9 @@ from workbench_test_support import (
def update_remediation(
state_dir: Path,
occurrence_id: str,
request_id: str,
action_token: str,
expected_version: int,
state: str,
*extra: str,
request: RemediationRequest, action_token: str, expected_version: int, state: str, *extra: str
) -> dict[str, Any]:
result = set_remediation(
state_dir, occurrence_id, request_id, action_token, str(expected_version), state, *extra
)
result = request.update(action_token, str(expected_version), state, *extra)
return result["scan"]["findings"][0]["remediationState"]
@@ -47,14 +34,12 @@ def test_failed_remediation_steps_can_retry_or_regenerate(tmp_path: Path) -> Non
completed = scan_command(state_dir, "complete-scan", scan_id)["scan"]
occurrence_id = str(completed["findings"][0]["occurrenceId"])
request_id = str(uuid.uuid4())
request = RemediationRequest(state_dir, occurrence_id)
action_token = str(uuid.uuid4())
request_remediation(state_dir, occurrence_id, request_id, action_token)
mark_remediation_delivered(state_dir, occurrence_id, request_id, action_token)
request.start(action_token)
request.mark_delivered(action_token)
failed = update_remediation(
state_dir,
occurrence_id,
request_id,
request,
action_token,
1,
"failed",
@@ -78,30 +63,24 @@ def test_failed_remediation_steps_can_retry_or_regenerate(tmp_path: Path) -> Non
set_triage(state_dir, occurrence_id, "open")
resend_token = str(uuid.uuid4())
resent = claim_remediation_resend(state_dir, occurrence_id, request_id, resend_token)["scan"]
resent = request.claim_resend(resend_token)["scan"]
assert resent["findings"][0]["remediationState"]["actionClaimToken"] == resend_token
delivered = mark_remediation_delivered(state_dir, occurrence_id, request_id, resend_token)[
"scan"
]
delivered = request.mark_delivered(resend_token)["scan"]
assert delivered["findings"][0]["remediationState"]["actionDeliveredAt"]
canceled = cancel_remediation_request(state_dir, occurrence_id, request_id, resend_token)[
"scan"
]["findings"][0]["remediationState"]
canceled = request.cancel(resend_token)["scan"]["findings"][0]["remediationState"]
assert canceled["state"] == "failed"
assert canceled["pendingAction"] == "generate"
assert canceled["actionClaimToken"] is None
replayed = cancel_remediation_request(state_dir, occurrence_id, request_id, resend_token)[
"scan"
]["findings"][0]["remediationState"]
replayed = request.cancel(resend_token)["scan"]["findings"][0]["remediationState"]
assert replayed == canceled
resend_token = str(uuid.uuid4())
claim_remediation_resend(state_dir, occurrence_id, request_id, resend_token)
request.claim_resend(resend_token)
failed_request_id = request_id
request_id = str(uuid.uuid4())
failed_request_id = request.id
request = RemediationRequest(state_dir, occurrence_id)
action_token = str(uuid.uuid4())
blocked = request_remediation(state_dir, occurrence_id, request_id, action_token, check=False)
blocked = request.start(action_token, check=False)
assert blocked["returncode"] != 0
with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
connection.execute(
@@ -112,18 +91,14 @@ def test_failed_remediation_steps_can_retry_or_regenerate(tmp_path: Path) -> Non
""",
("2000-01-01T00:00:00Z", failed_request_id),
)
regenerated = request_remediation(state_dir, occurrence_id, request_id, action_token)["scan"][
"findings"
][0]["remediationState"]
regenerated = request.start(action_token)["scan"]["findings"][0]["remediationState"]
assert regenerated["state"] == "requested"
patch_path = scan_dir / "remediation.patch"
write_remediation_patch(patch_path)
patch_digest = f"sha256:{hashlib.sha256(patch_path.read_bytes()).hexdigest()}"
update_remediation(
state_dir,
occurrence_id,
request_id,
request,
action_token,
1,
"generated",
@@ -134,12 +109,10 @@ def test_failed_remediation_steps_can_retry_or_regenerate(tmp_path: Path) -> Non
)
apply_token = str(uuid.uuid4())
request_remediation_action(state_dir, occurrence_id, request_id, "2", "apply", apply_token)
request.request_action("2", "apply", apply_token)
subprocess.run(["git", "apply", "--no-index", str(patch_path)], cwd=target, check=True)
failed = update_remediation(
state_dir,
occurrence_id,
request_id,
request,
apply_token,
3,
"failed",
@@ -148,37 +121,19 @@ def test_failed_remediation_steps_can_retry_or_regenerate(tmp_path: Path) -> Non
)
assert failed["pendingAction"] == "apply"
apply_retry_token = str(uuid.uuid4())
claim_remediation_resend(state_dir, occurrence_id, request_id, apply_retry_token)
request.claim_resend(apply_retry_token)
applied = update_remediation(
state_dir,
occurrence_id,
request_id,
apply_retry_token,
4,
"applied",
"--base-revision",
"unversioned",
request, apply_retry_token, 4, "applied", "--base-revision", "unversioned"
)
assert applied["state"] == "applied"
assert applied["summary"] is None
verify_token = str(uuid.uuid4())
request_remediation_action(state_dir, occurrence_id, request_id, "5", "verify", verify_token)
mark_remediation_delivered(state_dir, occurrence_id, request_id, verify_token)
update_remediation(
state_dir,
occurrence_id,
request_id,
verify_token,
6,
"verifying",
"--base-revision",
"unversioned",
)
request.request_action("5", "verify", verify_token)
request.mark_delivered(verify_token)
update_remediation(request, verify_token, 6, "verifying", "--base-revision", "unversioned")
failed = update_remediation(
state_dir,
occurrence_id,
request_id,
request,
verify_token,
7,
"failed",
@@ -188,19 +143,15 @@ def test_failed_remediation_steps_can_retry_or_regenerate(tmp_path: Path) -> Non
assert failed["pendingAction"] == "verify"
assert failed["actionClaimToken"] is None
assert failed["actionDeliveredAt"] is None
canceled = cancel_remediation_request(state_dir, occurrence_id, request_id, verify_token)[
"scan"
]["findings"][0]["remediationState"]
canceled = request.cancel(verify_token)["scan"]["findings"][0]["remediationState"]
assert canceled == failed
verify_retry_token = str(uuid.uuid4())
claim_remediation_resend(state_dir, occurrence_id, request_id, verify_retry_token)
delivered = mark_remediation_delivered(
state_dir, occurrence_id, request_id, verify_retry_token
)["scan"]["findings"][0]["remediationState"]
request.claim_resend(verify_retry_token)
delivered = request.mark_delivered(verify_retry_token)["scan"]["findings"][0][
"remediationState"
]
assert delivered["actionDeliveredAt"]
canceled = cancel_remediation_request(state_dir, occurrence_id, request_id, verify_retry_token)[
"scan"
]["findings"][0]["remediationState"]
canceled = request.cancel(verify_retry_token)["scan"]["findings"][0]["remediationState"]
assert canceled["state"] == "failed"
assert canceled["pendingAction"] == "verify"
assert canceled["summary"] == failed["summary"]
@@ -209,11 +160,9 @@ def test_failed_remediation_steps_can_retry_or_regenerate(tmp_path: Path) -> Non
assert canceled["actionClaimedAt"] is None
assert canceled["actionDeliveredAt"] is None
verify_retry_token = str(uuid.uuid4())
claim_remediation_resend(state_dir, occurrence_id, request_id, verify_retry_token)
request.claim_resend(verify_retry_token)
verified = update_remediation(
state_dir,
occurrence_id,
request_id,
request,
verify_retry_token,
8,
"verified",
@@ -7,7 +7,7 @@ import sys
from pathlib import Path
import pytest
from test_workbench_checkpoint_heads import drafts, select
from test_workbench_checkpoint_heads import drafts
from test_workbench_standard_deep_results import (
accepted_standard_worker,
deep_scan_fixture,
@@ -22,7 +22,9 @@ from workbench_test_support import (
saved_discovery_worker,
saved_draft,
scan_command,
select_checkpoint,
write_checkpoint,
write_result_draft,
)
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
@@ -74,11 +76,9 @@ def test_failed_publication_keeps_order_after_identical_result_rewrite(
worker_id, result = accepted_standard_worker(state, codex_home, scan_dir, scan_id)
pending, closed = drafts(scan_id)
old, latest = (closed, pending) if latest_pending else (pending, closed)
result.write_text(json.dumps(old))
os.utime(result, ns=(100, 100))
checkpoint = write_checkpoint(result.parent / "checkpoints", latest)
os.utime(checkpoint, ns=(200, 200))
select(result.parent, checkpoint, 200)
write_result_draft(result, old, mtime_ns=100)
checkpoint = write_checkpoint(result.parent / "checkpoints", latest, mtime_ns=200)
select_checkpoint(result.parent, checkpoint, mtime_ns=200)
def fail_publication(*args, **kwargs):
raise OSError("injected publication failure")
@@ -193,12 +193,10 @@ def test_head_capture_includes_checkpoint_published_after_enumeration(
state, codex_home, _, scan_dir, scan_id = deep_scan_fixture(tmp_path)
worker_id, result = accepted_standard_worker(state, codex_home, scan_dir, scan_id)
pending, closed = drafts(scan_id)
result.write_text(json.dumps(closed))
os.utime(result, ns=(100, 100))
write_result_draft(result, closed, mtime_ns=100)
output = scan_dir if layout == "parent" else result.parent
original = write_checkpoint(output / "checkpoints", closed)
os.utime(original, ns=(100, 100))
select(output, original, 100)
original = write_checkpoint(output / "checkpoints", closed, mtime_ns=100)
select_checkpoint(output, original, mtime_ns=100)
if explicit_recovery:
fail_deep_scan(state, codex_home, scan_id, deep_status="failed")
result.write_bytes(result.read_bytes())
@@ -210,9 +208,8 @@ def test_head_capture_includes_checkpoint_published_after_enumeration(
def publish_after_listing(root, relative):
names = children(root, relative)
if relative == directory and not published:
checkpoint = write_checkpoint(output / "checkpoints", pending)
os.utime(checkpoint, ns=(200, 200))
select(output, checkpoint, 200)
checkpoint = write_checkpoint(output / "checkpoints", pending, mtime_ns=200)
select_checkpoint(output, checkpoint, mtime_ns=200)
published.append(checkpoint)
return names
@@ -262,10 +259,8 @@ def test_frozen_times_cover_sources_without_checkpoint_heads(
output = tmp_path / "worker"
output.mkdir()
result = output / "result.json"
result.write_text(json.dumps(closed))
os.utime(result, ns=(100, 100))
checkpoint = write_checkpoint(output / "checkpoints", pending)
os.utime(checkpoint, ns=(200, 200))
write_result_draft(result, closed, mtime_ns=100)
checkpoint = write_checkpoint(output / "checkpoints", pending, mtime_ns=200)
workers = [saved_discovery_worker(output, "worker", 1)]
binding = saved_binding("deep_repository", repository="synthetic")
@@ -351,12 +346,11 @@ def test_restored_head_uses_its_captured_observation(tmp_path: Path, head_time:
]
for checkpoint, observed in zip(checkpoints, (300, 400)):
os.utime(checkpoint, ns=(50, 50))
select(output, checkpoint, observed)
select_checkpoint(output, checkpoint, mtime_ns=observed)
saved._capture_saved_source(tmp_path, "worker/checkpoint-head.json", scan_id)
result = output / "result.json"
result.write_text(json.dumps(reported))
os.utime(result, ns=(200, 200))
select(output, checkpoints[0], head_time)
write_result_draft(result, reported, mtime_ns=200)
select_checkpoint(output, checkpoints[0], mtime_ns=head_time)
original = {path: path.read_bytes() for path in (result, *checkpoints)}
workers = [saved_discovery_worker(output)]
binding = saved_binding("deep_repository", repository="synthetic")
@@ -402,10 +396,9 @@ def test_first_stop_freezes_sources_before_report_preparation(
}
],
)
result.write_text(json.dumps(reported))
os.utime(result, ns=(100, 100))
write_result_draft(result, reported, mtime_ns=100)
checkpoint = write_checkpoint(result.parent / "checkpoints", reported)
select(result.parent, checkpoint, 100)
select_checkpoint(result.parent, checkpoint, mtime_ns=100)
report = scan_dir / "report.md"
report.mkdir()
environment = {"CODEX_HOME": str(codex_home)}
@@ -435,7 +428,7 @@ def test_first_stop_freezes_sources_before_report_preparation(
complete=True,
)
latest = write_checkpoint(result.parent / "checkpoints", rejection)
select(result.parent, latest, 300)
select_checkpoint(result.parent, latest, mtime_ns=300)
preserved = preserve_scan_results(
state, scan_id, "standard-worker-thread", environment=environment
)["scan"]
@@ -453,7 +446,7 @@ def test_invalid_explicit_recovery_does_not_replace_first_selection(tmp_path: Pa
initial = json.loads(result.read_text())
os.utime(result, ns=(100, 100))
checkpoint = write_checkpoint(result.parent / "checkpoints", initial)
select(result.parent, checkpoint, 100)
select_checkpoint(result.parent, checkpoint, mtime_ns=100)
fail_deep_scan(state, codex_home, scan_id, deep_status="failed")
artifacts = {
name: (scan_dir / name).read_bytes()
@@ -469,7 +462,7 @@ def test_invalid_explicit_recovery_does_not_replace_first_selection(tmp_path: Pa
checkpoint.write_text(json.dumps({**initial, "scanId": "other-scan"}))
valid = {**initial, "complete": True, "threatModel": {"summary": "Completed review."}}
later = write_checkpoint(result.parent / "checkpoints", valid)
select(result.parent, later, 200)
select_checkpoint(result.parent, later, mtime_ns=200)
environment = {"CODEX_HOME": str(codex_home)}
failed = scan_command(
state, "recover-scan-results", scan_id, environment=environment, check=False
@@ -40,9 +40,7 @@ FINALIZER = SCRIPT.with_name("finalize_scan_contract.py")
def test_rename_persists_without_changing_scan_results(
tmp_path: Path, complete: bool, upgrade: bool
) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
scan = create_cli_scan(state_dir, tmp_path / "scans", repository, complete=complete)
before = run_workbench(state_dir, "get-scan", "--scan-id", scan["scanId"])["scan"]
if upgrade:
@@ -64,9 +62,7 @@ def test_rename_persists_without_changing_scan_results(
def test_rename_rejects_blank_names(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
scan = create_cli_scan(state_dir, tmp_path / "scans", repository, complete=False)
blank = run_workbench(
@@ -97,9 +93,7 @@ def test_scan_history_search_casefolds_displayed_fields(tmp_path: Path) -> None:
def test_rename_does_not_reorder_scan_history(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
older = create_cli_scan(state_dir, tmp_path / "scans", repository)
newer = create_cli_scan(state_dir, tmp_path / "scans", repository)
with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
@@ -124,6 +118,12 @@ def test_rename_does_not_reorder_scan_history(tmp_path: Path) -> None:
assert after == [before[0], {**before[1], "name": "Release audit"}]
def empty_history_paths(tmp_path: Path) -> tuple[Path, Path]:
repository = tmp_path / "repository"
repository.mkdir()
return tmp_path / "state", repository
def compare_scan_pair(
state_dir: Path,
before: dict[str, Any],
@@ -270,9 +270,7 @@ def create_cli_scan(
def test_get_scan_reads_pinned_coverage_independently_of_unrelated_artifacts(
tmp_path: Path, artifact: str, mutation: str
) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
scan = create_cli_scan(state_dir, tmp_path / "results", repository, finding=True)
scan_dir = Path(scan["scanDir"])
before = get_scan(state_dir, scan["scanId"])["scan"]
@@ -297,9 +295,7 @@ def test_get_scan_reads_pinned_coverage_independently_of_unrelated_artifacts(
def test_get_scan_reads_legacy_sealed_history_coverage_without_writes(
tmp_path: Path, finding: bool, follow_up: bool
) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
scan = create_cli_scan(
state_dir, tmp_path / "results", repository, finding=finding, follow_up=follow_up
)
@@ -334,9 +330,7 @@ def test_get_scan_reads_legacy_sealed_history_coverage_without_writes(
def test_get_scan_rejects_unverifiable_legacy_sealed_history_coverage(
tmp_path: Path, corruption: str
) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
scan = create_cli_scan(state_dir, tmp_path / "results", repository, finding=False)
scan_dir = Path(scan["scanDir"])
with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
@@ -428,9 +422,7 @@ def test_cli_scan_lifecycle_persists_recipes_lineage_and_filtered_history(tmp_pa
def test_cli_scan_persists_its_continuation_thread(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
scan = create_cli_scan(state_dir, tmp_path / "results", repository, complete=False)
initial = get_scan(state_dir, scan["scanId"])["scan"]
assert initial["threadIds"] == []
@@ -586,9 +578,7 @@ def test_cli_scan_preserves_original_revision_when_head_moves(tmp_path: Path) ->
@pytest.mark.parametrize("context_reporting", ["bounded", "unknown_upper", "legacy"])
def test_cli_scan_history_persists_per_scan_cost(tmp_path: Path, context_reporting: str) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
cost = {
"model": "gpt-5.6-sol",
"inputTokens": 1250,
@@ -635,9 +625,7 @@ def test_cli_scan_history_persists_per_scan_cost(tmp_path: Path, context_reporti
def test_cli_scan_completion_persists_authoritative_cost_after_plugin_completion(
tmp_path: Path,
) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
scan = create_cli_scan(state_dir, tmp_path / "results", repository)
cost = {
"model": "gpt-5.6-sol",
@@ -674,9 +662,7 @@ def test_cli_scan_completion_persists_authoritative_cost_after_plugin_completion
def test_failed_cli_scan_history_persists_measured_cost(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
cost = {
"model": "gpt-5.6-terra",
"inputTokens": 1250,
@@ -702,9 +688,7 @@ def test_failed_cli_scan_history_persists_measured_cost(tmp_path: Path) -> None:
def test_scan_failure_rejects_invalid_cost_without_stopping_the_scan(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
scan = create_cli_scan(state_dir, tmp_path / "results", repository, complete=False)
rejected = fail_scan(
@@ -717,9 +701,7 @@ def test_scan_failure_rejects_invalid_cost_without_stopping_the_scan(tmp_path: P
def test_scan_completion_rejects_invalid_cost_without_overwriting_history(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
scan = create_cli_scan(state_dir, tmp_path / "results", repository)
invalid = [
"null",
@@ -749,9 +731,7 @@ def test_scan_completion_rejects_invalid_cost_without_overwriting_history(tmp_pa
def test_scan_history_resolves_unique_prefixes_and_rejects_ambiguity(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
root = tmp_path / "results"
scan = create_cli_scan(state_dir, root, repository)
after = create_cli_scan(state_dir, root, repository)
@@ -917,9 +897,7 @@ def test_scan_list_includes_related_git_worktrees_and_clones(tmp_path: Path) ->
def test_cli_scan_comparison_tracks_stable_findings_without_copying_triage(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
root = tmp_path / "results"
before = create_cli_scan(state_dir, root, repository)
after = create_cli_scan(state_dir, root, repository, parent_scan_id=before["scanId"])
@@ -1025,9 +1003,7 @@ def test_finding_occurrence_history_uses_start_instants(
def test_scan_comparison_requires_saved_matches_and_remains_read_only(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
root = tmp_path / "results"
before = create_cli_scan(state_dir, root, repository)
after = create_cli_scan(state_dir, root, repository)
@@ -1076,9 +1052,7 @@ def test_scan_comparison_requires_saved_matches_and_remains_read_only(tmp_path:
def test_list_unmatched_scan_pairs_groups_pending_pairs_and_skips_saved_results(
tmp_path: Path,
) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
root = tmp_path / "results"
first, second, third = (create_cli_scan(state_dir, root, repository) for _ in range(3))
save_scan_matches(state_dir, first, second)
@@ -1147,9 +1121,7 @@ def test_automatic_matching_orders_instants_and_preserves_directed_cache(
def test_automatic_matching_keeps_unavailable_history_without_future_links(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
earlier, unavailable, current, future = (
create_cli_scan(
state_dir, tmp_path / "results", repository, identity_anchor=f"archive-check-{index}"
@@ -1204,9 +1176,7 @@ def test_automatic_matching_keeps_unavailable_history_without_future_links(tmp_p
def test_list_unmatched_scan_pairs_skips_unavailable_scan_artifacts(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
root = tmp_path / "results"
first, unavailable, last = (create_cli_scan(state_dir, root, repository) for _ in range(3))
save_scan_matches(state_dir, first, last)
@@ -1232,9 +1202,7 @@ def test_list_unmatched_scan_pairs_skips_unavailable_scan_artifacts(tmp_path: Pa
def test_semantic_scan_comparison_caches_matches_and_exposes_related_findings(
tmp_path: Path,
) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
root = tmp_path / "results"
before = create_cli_scan(state_dir, root, repository)
after = create_cli_scan(
@@ -1408,9 +1376,7 @@ def test_explicit_comparison_uses_chronological_matching_cutoff(
def test_semantic_scan_matching_backfills_legacy_finding_details(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
root = tmp_path / "results"
before = create_cli_scan(state_dir, root, repository)
after = create_cli_scan(state_dir, root, repository)
@@ -1439,9 +1405,7 @@ def test_semantic_scan_matching_backfills_legacy_finding_details(tmp_path: Path)
def test_semantic_scan_comparison_supports_one_to_many_without_copying_triage(
tmp_path: Path,
) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
root = tmp_path / "results"
before = create_cli_scan(state_dir, root, repository)
after = create_cli_scan(
@@ -1498,9 +1462,7 @@ def test_semantic_scan_comparison_supports_one_to_many_without_copying_triage(
def test_uncertain_semantic_scan_matches_stay_separate(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
root = tmp_path / "results"
before = create_cli_scan(state_dir, root, repository)
after = create_cli_scan(
@@ -1536,9 +1498,7 @@ def test_uncertain_semantic_scan_matches_stay_separate(tmp_path: Path) -> None:
def test_semantic_scan_comparison_replaces_cached_matches_atomically(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
root = tmp_path / "results"
before = create_cli_scan(state_dir, root, repository)
after = create_cli_scan(
@@ -1676,9 +1636,7 @@ def test_semantic_scan_comparison_accepts_matching_git_origins(tmp_path: Path) -
def test_semantic_scan_comparison_rejects_unknown_overlapping_and_uncertain_groups(
tmp_path: Path,
) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
root = tmp_path / "results"
before = create_cli_scan(state_dir, root, repository)
after = create_cli_scan(state_dir, root, repository)
@@ -1748,9 +1706,7 @@ def test_cli_scan_comparison_distinguishes_absence_from_out_of_scope(tmp_path: P
def test_cli_scan_reruns_reject_other_repository_parents(tmp_path: Path) -> None:
state_dir = tmp_path / "state"
repository = tmp_path / "repository"
repository.mkdir()
state_dir, repository = empty_history_paths(tmp_path)
parent = create_cli_scan(state_dir, tmp_path / "results", repository)
other = tmp_path / "other"
other.mkdir()
@@ -42,6 +42,23 @@ class ScanFixture:
mode: str = "standard"
diff_target: dict[str, Any] | None = None
def write_parent_rollout(
self, events: list[dict[str, Any]], *, originator: str | None = None
) -> Path:
rollout = _rollout(self.target.parent, "scan-parent", events, originator=originator)
_state_graph(self.environment, {"scan-parent": rollout}, [])
return rollout
def command(self, name: str, *arguments: str, check: bool = True) -> dict[str, Any]:
return scan_command(
self.state_dir,
name,
self.scan_id,
*arguments,
check=check,
environment=self.environment,
)
def _start_scan(tmp_path: Path, *, mode: str = "standard") -> ScanFixture:
state_dir = tmp_path / "workbench-state"
@@ -92,12 +109,11 @@ def _start_scan(tmp_path: Path, *, mode: str = "standard") -> ScanFixture:
started = start_delivered_scan(
state_dir,
"--workspace-id",
workspace_id,
"--scan-root",
str(tmp_path / "scans"),
environment=environment,
)["results"]
)
if mode == "deep":
begin_deep_scan(
state_dir,
@@ -219,6 +235,24 @@ def _rollout(
return rollout.resolve()
def _measure_rollout(
scan_usage,
path: Path,
started_at: datetime,
completed_at: datetime,
*,
thread_id: str = "scan-parent",
parent_id: str | None = None,
**options: str | None,
):
return scan_usage._read_rollout_usage(
scan_usage.RolloutSession(thread_id, parent_id, path),
started_at=started_at,
completed_at=completed_at,
**options,
)
def _allowance_event(timestamp: datetime, percent: int, limit: str = "codex") -> dict[str, Any]:
return _event(
timestamp,
@@ -336,13 +370,7 @@ def _complete_scan(fixture: ScanFixture, *arguments: str) -> dict[str, Any]:
fixture.target,
**options,
)
return scan_command(
fixture.state_dir,
"complete-scan",
fixture.scan_id,
*arguments,
environment=fixture.environment,
)
return fixture.command("complete-scan", *arguments)
@pytest.mark.parametrize(
@@ -361,8 +389,7 @@ def test_completion_preserves_usage_record_warnings(
event["payload"]["info"] = None
elif info == "invalid":
event["payload"]["info"] = {}
parent = _rollout(tmp_path, "scan-parent", [event, _token_event(counted, 20, 10)])
_state_graph(fixture.environment, {"scan-parent": parent}, [])
fixture.write_parent_rollout([event, _token_event(counted, 20, 10)])
usage = _complete_scan(fixture)["scan"]["usage"]
@@ -377,9 +404,7 @@ def test_completion_counts_native_responses_and_compaction_without_legacy_duplic
fixture = _start_scan(tmp_path)
counted = fixture.started_at + timedelta(microseconds=1)
compaction = _response_event(counted, "scan-parent", "compaction", 40, 3, turn_usage=(60, 5))
parent = _rollout(
tmp_path,
"scan-parent",
fixture.write_parent_rollout(
[
_token_event(fixture.started_at - timedelta(seconds=1), 100, 10),
_token_event(counted, 150, 15),
@@ -400,9 +425,8 @@ def test_completion_counts_native_responses_and_compaction_without_legacy_duplic
compaction,
_response_event(counted, "scan-parent", "last", 30, 4, turn_usage=(90, 9)),
_event(counted, "event_msg", {"type": "task_complete"}),
],
]
)
_state_graph(fixture.environment, {"scan-parent": parent}, [])
assert (
_complete_scan(fixture)["scan"]["usage"].items()
@@ -452,17 +476,16 @@ def test_legacy_compaction_usage_is_unverifiable_only_inside_scan_window(
events.append(_event(completed, "event_msg", {"type": "task_complete"}))
parent = _rollout(tmp_path, "scan-parent", events)
measurement = scan_usage._read_rollout_usage(
scan_usage.RolloutSession("scan-parent", None, parent),
started_at=started,
completed_at=completed,
usage = _measure_rollout(
scan_usage,
parent,
started,
completed,
completed_turn_id="turn-scan-parent" if scope == "completion_turn" else None,
)
usage = measurement.tokens
warnings = measurement.warnings
assert usage == _counts(10, 0, 1)
assert warnings == ({"compaction_usage_unavailable"} if expected_warning else set())
assert usage.tokens == _counts(10, 0, 1)
assert usage.warnings == ({"compaction_usage_unavailable"} if expected_warning else set())
def test_legacy_compaction_warning_survives_a_later_native_turn(scan_usage, tmp_path: Path) -> None:
@@ -479,16 +502,10 @@ def test_legacy_compaction_warning_survives_a_later_native_turn(scan_usage, tmp_
],
)
measurement = scan_usage._read_rollout_usage(
scan_usage.RolloutSession("scan-parent", None, parent),
started_at=started,
completed_at=started,
)
usage = measurement.tokens
warnings = measurement.warnings
usage = _measure_rollout(scan_usage, parent, started, started)
assert usage == _counts(30, 0, 3)
assert warnings == {"compaction_usage_unavailable"}
assert usage.tokens == _counts(30, 0, 3)
assert usage.warnings == {"compaction_usage_unavailable"}
def test_native_usage_respects_scan_window_and_preserves_cache_details(
@@ -524,16 +541,10 @@ def test_native_usage_respects_scan_window_and_preserves_cache_details(
],
)
measurement = scan_usage._read_rollout_usage(
scan_usage.RolloutSession("scan-parent", None, parent),
started_at=started,
completed_at=completed,
)
usage = measurement.tokens
warnings = measurement.warnings
usage = _measure_rollout(scan_usage, parent, started, completed)
assert usage == _counts(20, 3, 2, cache_write_input_tokens=4)
assert warnings == set()
assert usage.tokens == _counts(20, 3, 2, cache_write_input_tokens=4)
assert usage.warnings == set()
def test_native_worker_usage_excludes_inherited_totals_and_survives_resume(
@@ -566,16 +577,12 @@ def test_native_worker_usage_excludes_inherited_totals_and_survives_resume(
copied_events=[inherited, _token_event(started, 1_000, 100)],
)
measurement = scan_usage._read_rollout_usage(
scan_usage.RolloutSession("scan-worker", "scan-parent", worker),
started_at=started,
completed_at=started,
usage = _measure_rollout(
scan_usage, worker, started, started, thread_id="scan-worker", parent_id="scan-parent"
)
usage = measurement.tokens
warnings = measurement.warnings
assert usage == _counts(60, 0, 6)
assert warnings == set()
assert usage.tokens == _counts(60, 0, 6)
assert usage.warnings == set()
@pytest.mark.parametrize("gap", ["before", "after", "inside"])
@@ -611,16 +618,10 @@ def test_native_usage_only_marks_receipt_gaps_inside_scan_window(
],
)
measurement = scan_usage._read_rollout_usage(
scan_usage.RolloutSession("scan-parent", None, parent),
started_at=started,
completed_at=started,
)
usage = measurement.tokens
warnings = measurement.warnings
usage = _measure_rollout(scan_usage, parent, started, started)
assert usage == _counts(30, 0, 0)
assert warnings == ({"token_record_incomplete"} if gap == "inside" else set())
assert usage.tokens == _counts(30, 0, 0)
assert usage.warnings == ({"token_record_incomplete"} if gap == "inside" else set())
def test_native_usage_continues_cumulative_baseline_when_recovering_same_turn(
@@ -645,16 +646,10 @@ def test_native_usage_continues_cumulative_baseline_when_recovering_same_turn(
],
)
measurement = scan_usage._read_rollout_usage(
scan_usage.RolloutSession("scan-parent", None, parent),
started_at=started,
completed_at=started,
)
usage = measurement.tokens
warnings = measurement.warnings
usage = _measure_rollout(scan_usage, parent, started, started)
assert usage == _counts(30, 0, 3)
assert warnings == set()
assert usage.tokens == _counts(30, 0, 3)
assert usage.warnings == set()
@pytest.mark.parametrize(
@@ -694,16 +689,12 @@ def test_native_usage_preserves_partial_measurement_warnings(
if failure == "truncated":
parent.write_bytes(parent.read_bytes().removesuffix(b"\n"))
measurement = scan_usage._read_rollout_usage(
scan_usage.RolloutSession("scan-parent", None, parent),
started_at=started,
completed_at=started,
)
usage = measurement.tokens
warnings = measurement.warnings
usage = _measure_rollout(scan_usage, parent, started, started)
assert usage == (_counts(20, 0, 2) if failure == "missing_receipt" else _counts(10, 0, 1))
assert warnings == {
assert usage.tokens == (
_counts(20, 0, 2) if failure == "missing_receipt" else _counts(10, 0, 1)
)
assert usage.warnings == {
"token_record_incomplete"
if failure == "missing_receipt"
else "rollout_record_incomplete"
@@ -912,8 +903,7 @@ def test_completion_includes_cached_and_cache_write_tokens(
reported = event["payload"]["info"]["total_token_usage"]
reported.pop("cache_write_input_tokens")
reported[cache_write_field] = 12
parent = _rollout(tmp_path, "scan-parent", [event])
_state_graph(fixture.environment, {"scan-parent": parent}, [])
fixture.write_parent_rollout([event])
usage = _complete_scan(fixture)["scan"]["usage"]
@@ -1112,11 +1102,7 @@ def test_completion_distinguishes_missing_usage_from_observed_zero(
_response_event(counted, "scan-parent", "zero-response", 0, 0),
_event(counted, "event_msg", {"type": "task_complete", "turn_id": "turn-scan-parent"}),
]
_state_graph(
fixture.environment,
{"scan-parent": _rollout(tmp_path, "scan-parent", events)},
[],
)
fixture.write_parent_rollout(events)
usage = _complete_scan(fixture)["scan"]["usage"]
@@ -1330,22 +1316,12 @@ def test_completion_preserves_explicit_legacy_cost(
) -> None:
fixture = _start_scan(tmp_path)
counted = fixture.started_at + timedelta(microseconds=1)
_state_graph(
fixture.environment,
{
"scan-parent": _rollout(
tmp_path,
"scan-parent",
[
_token_event(fixture.started_at - timedelta(seconds=1), 100, 0),
_token_event(
counted, 115, 6, cached_input_tokens=100 if delayed_cache_counts else 0
),
_allowance_event(counted, 6),
],
)
},
[],
fixture.write_parent_rollout(
[
_token_event(fixture.started_at - timedelta(seconds=1), 100, 0),
_token_event(counted, 115, 6, cached_input_tokens=100 if delayed_cache_counts else 0),
_allowance_event(counted, 6),
]
)
cost = {
"model": "gpt-5.6-sol",
@@ -1358,14 +1334,7 @@ def test_completion_preserves_explicit_legacy_cost(
write_completed_contract(
fixture.scan_dir, fixture.scan_id, fixture.target, relative_path="app.py"
)
completed = scan_command(
fixture.state_dir,
"complete-scan",
fixture.scan_id,
"--cost-json",
json.dumps(cost),
environment=fixture.environment,
)["scan"]
completed = fixture.command("complete-scan", "--cost-json", json.dumps(cost))["scan"]
assert completed["cost"] == cost
assert completed["usage"]["accountRateLimits"][0]["primary"]["usedPercent"] == 6
if delayed_cache_counts:
@@ -1444,9 +1413,7 @@ def test_completion_persists_direct_control_zero_without_hiding_missing_workers(
"threadCount": 1 if measured_worker else 0,
}
assert "cost" not in completed
repeated = scan_command(
fixture.state_dir, "complete-scan", fixture.scan_id, environment=fixture.environment
)["scan"]
repeated = fixture.command("complete-scan")["scan"]
assert repeated["usage"] == usage
assert "cost" not in repeated
with sqlite3.connect(fixture.state_dir / "workbench.sqlite3") as connection:
@@ -1516,11 +1483,7 @@ def test_metadata_only_deep_owner_requires_direct_control_originator(
tmp_path: Path, originator: str | None
) -> None:
fixture = _start_scan(tmp_path, mode="deep")
_state_graph(
fixture.environment,
{"scan-parent": _rollout(tmp_path, "scan-parent", [], originator=originator)},
[],
)
fixture.write_parent_rollout([], originator=originator)
assert _complete_scan(fixture)["scan"]["usage"] == {
"coverage": "unavailable",
@@ -1599,32 +1562,18 @@ def test_host_finalizes_exact_completion_turn_without_changing_artifacts(
)
with parent.open("a", encoding="utf-8") as output:
output.writelines(f"{json.dumps(event)}\n" for event in final_events)
mismatched = scan_command(
fixture.state_dir,
mismatched = fixture.command(
"finalize-scan-usage",
fixture.scan_id,
"--thread-id",
"scan-parent",
"--turn-id",
"another-turn",
environment=fixture.environment,
check=False,
)
assert mismatched["returncode"] != 0
assert (
scan_command(
fixture.state_dir, "get-scan", fixture.scan_id, environment=fixture.environment
)["scan"]["usage"]
== initial["usage"]
)
assert fixture.command("get-scan")["scan"]["usage"] == initial["usage"]
arguments = ("--thread-id", "scan-parent", "--turn-id", turn_id)
finalized = scan_command(
fixture.state_dir,
"finalize-scan-usage",
fixture.scan_id,
*arguments,
environment=fixture.environment,
)["scan"]
finalized = fixture.command("finalize-scan-usage", *arguments)["scan"]
assert (
finalized["usage"].items()
>= {
@@ -1646,26 +1595,16 @@ def test_host_finalizes_exact_completion_turn_without_changing_artifacts(
]
with parent.open("a", encoding="utf-8") as output:
output.writelines(f"{json.dumps(event)}\n" for event in later_events)
measurement = scan_usage._read_rollout_usage(
scan_usage.RolloutSession("scan-parent", None, parent),
started_at=fixture.started_at,
completed_at=datetime.fromisoformat(stopped_at.replace("Z", "+00:00")),
usage = _measure_rollout(
scan_usage,
parent,
fixture.started_at,
datetime.fromisoformat(stopped_at.replace("Z", "+00:00")),
completed_turn_id=turn_id,
)
measured = measurement.tokens
warnings = measurement.warnings
assert measured == _counts(90, 0, 11)
assert warnings == set()
assert (
scan_command(
fixture.state_dir,
"finalize-scan-usage",
fixture.scan_id,
*arguments,
environment=fixture.environment,
)["scan"]["usage"]
== finalized["usage"]
)
assert usage.tokens == _counts(90, 0, 11)
assert usage.warnings == set()
assert fixture.command("finalize-scan-usage", *arguments)["scan"]["usage"] == finalized["usage"]
assert {name: (fixture.scan_dir / name).read_bytes() for name in sealed_files} == sealed_files
@@ -1689,17 +1628,14 @@ def test_host_final_usage_preserves_missing_worker_warning(
[("scan-parent", "scan-worker")],
)
_complete_scan(fixture, "--thread-id", "scan-parent", "--turn-id", turn_id)
usage = scan_command(
fixture.state_dir,
usage = fixture.command(
"finalize-scan-usage",
fixture.scan_id,
"--thread-id",
"scan-parent",
"--turn-id",
turn_id,
"--turn-status",
turn_status,
environment=fixture.environment,
)["scan"]["usage"]
assert (
usage.items()
@@ -1722,12 +1658,7 @@ def test_host_final_usage_retries_a_locked_native_database_without_losing_counts
) -> None:
fixture = _start_scan(tmp_path)
counted = fixture.started_at + timedelta(microseconds=1)
parent = _rollout(
tmp_path,
"scan-parent",
[_response_event(counted, "scan-parent", "first", 10, 2)],
)
_state_graph(fixture.environment, {"scan-parent": parent}, [])
parent = fixture.write_parent_rollout([_response_event(counted, "scan-parent", "first", 10, 2)])
arguments = ("--thread-id", "scan-parent", "--turn-id", "turn-scan-parent")
initial = _complete_scan(fixture, *arguments)["scan"]["usage"]
with parent.open("a", encoding="utf-8") as output:
@@ -1737,24 +1668,12 @@ def test_host_final_usage_retries_a_locked_native_database_without_losing_counts
Path(fixture.environment["CODEX_SQLITE_HOME"]) / "state_5.sqlite"
) as native_database:
native_database.execute("BEGIN EXCLUSIVE")
pending = scan_command(
fixture.state_dir,
"finalize-scan-usage",
fixture.scan_id,
*arguments,
environment=fixture.environment,
)["scan"]["usage"]
pending = fixture.command("finalize-scan-usage", *arguments)["scan"]["usage"]
assert pending == initial
assert pending["totalTokens"] == 12
assert pending["completion"]["finalized"] is False
finalized = scan_command(
fixture.state_dir,
"finalize-scan-usage",
fixture.scan_id,
*arguments,
environment=fixture.environment,
)["scan"]["usage"]
finalized = fixture.command("finalize-scan-usage", *arguments)["scan"]["usage"]
assert (
finalized.items()
>= {
@@ -1773,34 +1692,11 @@ def test_host_final_usage_recovers_initially_unavailable_records(tmp_path: Path)
initial = _complete_scan(fixture, *arguments)["scan"]["usage"]
assert initial["coverage"] == "unavailable"
assert initial["completion"]["finalized"] is False
assert (
scan_command(
fixture.state_dir,
"finalize-scan-usage",
fixture.scan_id,
*arguments,
environment=fixture.environment,
)["scan"]["usage"]
== initial
assert fixture.command("finalize-scan-usage", *arguments)["scan"]["usage"] == initial
fixture.write_parent_rollout(
[_response_event(fixture.started_at, "scan-parent", "final-response", 10, 2)]
)
_state_graph(
fixture.environment,
{
"scan-parent": _rollout(
tmp_path,
"scan-parent",
[_response_event(fixture.started_at, "scan-parent", "final-response", 10, 2)],
)
},
[],
)
finalized = scan_command(
fixture.state_dir,
"finalize-scan-usage",
fixture.scan_id,
*arguments,
environment=fixture.environment,
)["scan"]["usage"]
finalized = fixture.command("finalize-scan-usage", *arguments)["scan"]["usage"]
assert finalized["coverage"] == "complete"
assert finalized["totalTokens"] == 12
assert finalized["completion"]["finalized"] is True
@@ -1809,28 +1705,14 @@ def test_host_final_usage_recovers_initially_unavailable_records(tmp_path: Path)
def test_host_final_usage_does_not_invent_an_unrecorded_completion_turn(tmp_path: Path) -> None:
fixture = _start_scan(tmp_path)
arguments = ("--thread-id", "scan-parent", "--turn-id", "unrecorded-turn")
_state_graph(
fixture.environment,
{
"scan-parent": _rollout(
tmp_path,
"scan-parent",
[
_response_event(fixture.started_at, "scan-parent", "earlier-response", 10, 2),
_event(fixture.started_at, "event_msg", {"type": "task_complete"}),
],
)
},
[],
fixture.write_parent_rollout(
[
_response_event(fixture.started_at, "scan-parent", "earlier-response", 10, 2),
_event(fixture.started_at, "event_msg", {"type": "task_complete"}),
]
)
_complete_scan(fixture, *arguments)
finalized = scan_command(
fixture.state_dir,
"finalize-scan-usage",
fixture.scan_id,
*arguments,
environment=fixture.environment,
)["scan"]["usage"]
finalized = fixture.command("finalize-scan-usage", *arguments)["scan"]["usage"]
assert finalized["coverage"] == "partial"
assert finalized["totalTokens"] == 12
assert finalized["warnings"] == ["completion_turn_unavailable"]
@@ -1840,11 +1722,7 @@ def test_host_final_usage_does_not_invent_an_unrecorded_completion_turn(tmp_path
def test_failed_scan_preserves_legacy_failure_behavior(tmp_path: Path) -> None:
fixture = _start_scan(tmp_path)
counted = fixture.started_at + timedelta(microseconds=1)
_state_graph(
fixture.environment,
{"scan-parent": _rollout(tmp_path, "scan-parent", [_token_event(counted, 21, 8)])},
[],
)
fixture.write_parent_rollout([_token_event(counted, 21, 8)])
failed = fail_scan(
fixture.state_dir, fixture.scan_id, "Fixture failure.", environment=fixture.environment
)["scan"]
@@ -2115,12 +1993,7 @@ def test_completion_uses_latest_account_snapshot_across_owned_sessions(
"secondary": None,
}
assert limits["another-limit"]["primary"]["usedPercent"] == 2
assert (
scan_command(
fixture.state_dir, "get-scan", fixture.scan_id, environment=fixture.environment
)["scan"]["usage"]
== usage
)
assert fixture.command("get-scan")["scan"]["usage"] == usage
@pytest.mark.parametrize("terminal_status", ["complete", "failed"])
@@ -2160,9 +2033,7 @@ def test_large_usage_persists_with_terminal_scan_state(
assert terminal["progress"]["status"] == terminal_status
assert terminal["usage"] == usage
stored = scan_command(
fixture.state_dir, "get-scan", fixture.scan_id, environment=fixture.environment
)["scan"]
stored = fixture.command("get-scan")["scan"]
assert stored["progress"]["status"] == terminal_status
assert stored["usage"] == usage
@@ -2171,15 +2042,12 @@ def test_completion_collects_large_usage_from_owned_rollouts(tmp_path: Path) ->
fixture = _start_scan(tmp_path)
counted = fixture.started_at + timedelta(microseconds=1)
limit_ids = {f"fixture-limit-{index}" for index in range(60)}
parent = _rollout(
tmp_path,
"scan-parent",
fixture.write_parent_rollout(
[
_token_event(counted, 120, 15, cached_input_tokens=30),
*[_allowance_event(counted, 6, limit_id) for limit_id in sorted(limit_ids)],
],
]
)
_state_graph(fixture.environment, {"scan-parent": parent}, [])
completed = _complete_scan(fixture)["scan"]
@@ -2190,53 +2058,26 @@ def test_completion_collects_large_usage_from_owned_rollouts(tmp_path: Path) ->
assert usage["threadCount"] == 1
assert usage.items() >= _counts(120, 30, 15).items()
assert {limit["limitId"] for limit in usage["accountRateLimits"]} == limit_ids
assert (
scan_command(
fixture.state_dir, "get-scan", fixture.scan_id, environment=fixture.environment
)["scan"]["usage"]
== usage
)
assert fixture.command("get-scan")["scan"]["usage"] == usage
def test_host_final_usage_saves_allowances_before_token_receipts(tmp_path: Path) -> None:
fixture = _start_scan(tmp_path)
arguments = ("--thread-id", "scan-parent", "--turn-id", "turn-scan-parent")
initial = _complete_scan(fixture, *arguments)["scan"]["usage"]
parent = _rollout(
tmp_path,
"scan-parent",
[_allowance_event(fixture.started_at, 6)],
)
_state_graph(fixture.environment, {"scan-parent": parent}, [])
parent = fixture.write_parent_rollout([_allowance_event(fixture.started_at, 6)])
pending = scan_command(
fixture.state_dir,
"finalize-scan-usage",
fixture.scan_id,
*arguments,
environment=fixture.environment,
)["scan"]["usage"]
pending = fixture.command("finalize-scan-usage", *arguments)["scan"]["usage"]
assert pending["coverage"] == "unavailable"
assert pending["completion"] == initial["completion"]
assert not set(_counts(0, 0, 0)).intersection(pending)
assert pending["accountRateLimits"][0]["primary"]["usedPercent"] == 6
assert (
scan_command(
fixture.state_dir, "get-scan", fixture.scan_id, environment=fixture.environment
)["scan"]["usage"]
== pending
)
assert fixture.command("get-scan")["scan"]["usage"] == pending
with parent.open("a", encoding="utf-8") as output:
receipt = _response_event(fixture.started_at, "scan-parent", "final-response", 10, 2)
output.write(f"{json.dumps(receipt)}\n")
finalized = scan_command(
fixture.state_dir,
"finalize-scan-usage",
fixture.scan_id,
*arguments,
environment=fixture.environment,
)["scan"]["usage"]
finalized = fixture.command("finalize-scan-usage", *arguments)["scan"]["usage"]
assert finalized["totalTokens"] == 12
assert finalized["completion"]["finalized"] is True
assert finalized["accountRateLimits"] == pending["accountRateLimits"]
@@ -2253,14 +2094,8 @@ def test_completion_validates_account_snapshots_without_token_usage(
"threadCount": 0,
"accountRateLimits": limits,
}
rejected = scan_command(
fixture.state_dir,
"complete-scan",
fixture.scan_id,
"--cost-json",
json.dumps({"usage": usage}),
environment=fixture.environment,
check=False,
rejected = fixture.command(
"complete-scan", "--cost-json", json.dumps({"usage": usage}), check=False
)
assert rejected["returncode"] != 0
assert "invalid measured token usage" in rejected["stderr"]
@@ -2305,16 +2140,13 @@ def test_completion_marks_in_flight_usage_partial_even_with_earlier_receipts(
) -> None:
fixture = _start_scan(tmp_path)
counted = fixture.started_at + timedelta(microseconds=1)
parent = _rollout(
tmp_path,
"scan-parent",
fixture.write_parent_rollout(
[
_event(counted, "event_msg", {"type": "task_started", "turn_id": "scan-turn"}),
_token_event(counted, 12, 3),
_event(counted + timedelta(days=1), "event_msg", {"type": "task_complete"}),
],
]
)
_state_graph(fixture.environment, {"scan-parent": parent}, [])
usage = _complete_scan(fixture)["scan"]["usage"]
assert usage["coverage"] == "partial"
assert usage["totalTokens"] == 15
@@ -2395,14 +2227,13 @@ def test_closed_turn_coverage_survives_later_success(
rollout = _rollout(
tmp_path, thread_id, events, parent_thread_id=parent_id, include_task_start=False
)
measurement = scan_usage._read_rollout_usage(
scan_usage.RolloutSession(thread_id, parent_id, rollout),
started_at=started,
completed_at=started,
usage = _measure_rollout(
scan_usage, rollout, started, started, thread_id=thread_id, parent_id=parent_id
)
usage, warnings = measurement.tokens, measurement.warnings
assert usage == (_counts(30, 0, 5) if receipt in {"native", "legacy"} else _counts(10, 0, 2))
assert warnings == ({"token_record_missing"} if receipt == "none" else set()) | (
assert usage.tokens == (
_counts(30, 0, 5) if receipt in {"native", "legacy"} else _counts(10, 0, 2)
)
assert usage.warnings == ({"token_record_missing"} if receipt == "none" else set()) | (
{"turn_interrupted"} if terminal == "turn_aborted" else set()
)
@@ -2429,14 +2260,9 @@ def test_closed_turn_coverage_retains_before_window_receipt_evidence(
]
)
rollout = _rollout(tmp_path, "scan-parent", events)
measurement = scan_usage._read_rollout_usage(
scan_usage.RolloutSession("scan-parent", None, rollout),
started_at=started,
completed_at=started,
)
usage, warnings = measurement.tokens, measurement.warnings
assert usage == _counts(10, 0, 2)
assert warnings == (set() if receipt else {"token_record_missing"})
usage = _measure_rollout(scan_usage, rollout, started, started)
assert usage.tokens == _counts(10, 0, 2)
assert usage.warnings == (set() if receipt else {"token_record_missing"})
def test_closed_turn_coverage_accepts_delayed_receipt_for_same_turn(
@@ -2452,14 +2278,9 @@ def test_closed_turn_coverage_accepts_delayed_receipt_for_same_turn(
_response_event(started, "scan-parent", "late", 10, 2, turn_id="first"),
],
)
measurement = scan_usage._read_rollout_usage(
scan_usage.RolloutSession("scan-parent", None, rollout),
started_at=started,
completed_at=started,
)
usage, warnings = measurement.tokens, measurement.warnings
assert usage == _counts(10, 0, 2)
assert warnings == set()
usage = _measure_rollout(scan_usage, rollout, started, started)
assert usage.tokens == _counts(10, 0, 2)
assert usage.warnings == set()
def test_closed_turn_coverage_preserves_interruption_after_same_turn_resumes(
@@ -2478,14 +2299,9 @@ def test_closed_turn_coverage_preserves_interruption_after_same_turn_resumes(
_event(started, "event_msg", {"type": "task_complete", "turn_id": "same-turn"}),
],
)
measurement = scan_usage._read_rollout_usage(
scan_usage.RolloutSession("scan-parent", None, rollout),
started_at=started,
completed_at=started,
)
usage, warnings = measurement.tokens, measurement.warnings
assert usage == _counts(10, 0, 2)
assert warnings == {"turn_interrupted"}
usage = _measure_rollout(scan_usage, rollout, started, started)
assert usage.tokens == _counts(10, 0, 2)
assert usage.warnings == {"turn_interrupted"}
def test_closed_turn_coverage_ignores_inherited_and_outside_window_interruptions(
@@ -2509,31 +2325,25 @@ def test_closed_turn_coverage_ignores_inherited_and_outside_window_interruptions
_event(before, "event_msg", {"type": "turn_aborted", "turn_id": "inherited"}),
],
)
measurement = scan_usage._read_rollout_usage(
scan_usage.RolloutSession("worker", "scan-parent", rollout),
started_at=started,
completed_at=started,
usage = _measure_rollout(
scan_usage, rollout, started, started, thread_id="worker", parent_id="scan-parent"
)
usage, warnings = measurement.tokens, measurement.warnings
assert usage == _counts(10, 0, 2)
assert warnings == set()
assert usage.tokens == _counts(10, 0, 2)
assert usage.warnings == set()
def test_completion_marks_closed_turn_without_receipt_partial(tmp_path: Path) -> None:
fixture = _start_scan(tmp_path)
counted = fixture.started_at + timedelta(microseconds=1)
parent = _rollout(
tmp_path,
"scan-parent",
fixture.write_parent_rollout(
[
_event(counted, "event_msg", {"type": "task_started", "turn_id": "empty"}),
_event(counted, "event_msg", {"type": "task_complete", "turn_id": "empty"}),
_event(counted, "event_msg", {"type": "task_started", "turn_id": "measured"}),
_response_event(counted, "scan-parent", "response", 10, 2, turn_id="measured"),
_event(counted, "event_msg", {"type": "task_complete", "turn_id": "measured"}),
],
]
)
_state_graph(fixture.environment, {"scan-parent": parent}, [])
assert (
_complete_scan(fixture)["scan"]["usage"].items()
>= {
@@ -7,15 +7,23 @@ from contextlib import closing
from pathlib import Path
import pytest
from test_workbench_scan_history import create_cli_scan, run_workbench
from workbench_test_support import initialize_git_repository
from test_workbench_scan_history import create_cli_scan
from workbench_test_support import get_scan, initialize_git_repository
def start_validation_scan(
tmp_path: Path, repository: Path, *, target: dict[str, object] | None = None
) -> tuple[Path, str]:
state_dir = tmp_path / "state"
results = tmp_path / "results"
results.mkdir(mode=0o700)
scan = create_cli_scan(state_dir, results, repository, complete=False, target=target)
return state_dir, scan["scanId"]
@pytest.mark.parametrize("kind", ["directory", "git", "dirty", "working_tree", "refs"])
def test_check_scan_target_matches_recorded_contents(tmp_path: Path, kind: str) -> None:
repository = tmp_path / "repository"
state_dir = tmp_path / "state"
(tmp_path / "results").mkdir(mode=0o700)
if kind == "directory":
repository.mkdir()
(repository / "README.md").write_text("fixture\n")
@@ -28,35 +36,30 @@ def test_check_scan_target_matches_recorded_contents(tmp_path: Path, kind: str)
source.write_text("committed changes\n")
subprocess.run(["git", "commit", "-qam", "Scanned revision"], cwd=repository, check=True)
original = source.read_bytes()
scan = create_cli_scan(
state_dir,
tmp_path / "results",
state_dir, scan_id = start_validation_scan(
tmp_path,
repository,
complete=False,
target=(
{
"kind": kind,
"paths": [],
"base": "HEAD^" if kind == "refs" else "HEAD",
"head": "HEAD",
}
if kind in {"working_tree", "refs"}
else None
),
target={
"kind": kind,
"paths": [],
"base": "HEAD^" if kind == "refs" else "HEAD",
"head": "HEAD",
}
if kind in {"working_tree", "refs"}
else None,
)
command = ("get-scan", "--scan-id", scan["scanId"])
checked = run_workbench(state_dir, *command, "--check-target")
checked = get_scan(state_dir, scan_id, "--check-target")
assert checked["scan"]["targetPath"] == str(repository.resolve())
source.write_text("changed after scan\n")
# Ordinary history remains readable after the checkout changes.
assert run_workbench(state_dir, *command)["scan"]["scanId"] == scan["scanId"]
changed = run_workbench(state_dir, *command, "--check-target", check=False)
assert get_scan(state_dir, scan_id)["scan"]["scanId"] == scan_id
changed = get_scan(state_dir, scan_id, "--check-target", check=False)
assert changed["returncode"] != 0
assert "Scan target contents changed" in changed["stderr"]
source.write_bytes(original)
assert run_workbench(state_dir, *command, "--check-target")["scan"]["scanId"] == scan["scanId"]
assert get_scan(state_dir, scan_id, "--check-target")["scan"]["scanId"] == scan_id
@pytest.mark.parametrize("kind", ["repository", "refs"])
@@ -65,33 +68,23 @@ def test_check_scan_target_rejects_changed_revision(
) -> None:
repository = tmp_path / "repository"
initialize_git_repository(repository)
state_dir = tmp_path / "state"
(tmp_path / "results").mkdir(mode=0o700)
scan = create_cli_scan(
state_dir,
tmp_path / "results",
state_dir, scan_id = start_validation_scan(
tmp_path,
repository,
complete=False,
target=(
{"kind": "refs", "paths": [], "base": "HEAD", "head": "HEAD"}
if kind == "refs"
else None
),
target={"kind": "refs", "paths": [], "base": "HEAD", "head": "HEAD"}
if kind == "refs"
else None,
)
subprocess.run(
["git", "commit", "--allow-empty", "-qm", "New revision"], cwd=repository, check=True
)
changed = run_workbench(
state_dir, "get-scan", "--scan-id", scan["scanId"], "--check-target", check=False
)
changed = get_scan(state_dir, scan_id, "--check-target", check=False)
assert changed["returncode"] != 0
assert "Repository HEAD changed" in changed["stderr"]
assert "new scan" in changed["stderr"].lower()
with closing(sqlite3.connect(state_dir / "workbench.sqlite3")) as connection:
connection.row_factory = sqlite3.Row
stored_scan = connection.execute(
"SELECT * FROM scans WHERE id = ?", (scan["scanId"],)
).fetchone()
stored_scan = connection.execute("SELECT * FROM scans WHERE id = ?", (scan_id,)).fetchone()
with pytest.raises(SystemExit, match="Regenerate the remediation patch"):
workbench_api["remediation_checkout_snapshot"](stored_scan)
@@ -104,17 +97,10 @@ def test_check_committed_diff_target_rejects_sparse_checkout_after_scan(tmp_path
source.write_text("pass\n")
subprocess.run(["git", "add", "src/source.py"], cwd=repository, check=True)
subprocess.run(["git", "commit", "-qm", "Add source"], cwd=repository, check=True)
state_dir = tmp_path / "state"
(tmp_path / "results").mkdir(mode=0o700)
scan = create_cli_scan(
state_dir,
tmp_path / "results",
repository,
complete=False,
target={"kind": "refs", "paths": [], "base": "HEAD^", "head": "HEAD"},
state_dir, scan_id = start_validation_scan(
tmp_path, repository, target={"kind": "refs", "paths": [], "base": "HEAD^", "head": "HEAD"}
)
command = ("get-scan", "--scan-id", scan["scanId"])
assert run_workbench(state_dir, *command, "--check-target")["scan"]["scanId"] == scan["scanId"]
assert get_scan(state_dir, scan_id, "--check-target")["scan"]["scanId"] == scan_id
subprocess.run(
["git", "sparse-checkout", "set", "--no-cone", "/README.md"],
@@ -123,30 +109,26 @@ def test_check_committed_diff_target_rejects_sparse_checkout_after_scan(tmp_path
)
assert not source.exists()
subprocess.run(["git", "diff", "--quiet", "HEAD"], cwd=repository, check=True)
assert run_workbench(state_dir, *command)["scan"]["scanId"] == scan["scanId"]
changed = run_workbench(state_dir, *command, "--check-target", check=False)
assert get_scan(state_dir, scan_id)["scan"]["scanId"] == scan_id
changed = get_scan(state_dir, scan_id, "--check-target", check=False)
assert changed["returncode"] != 0
assert "full repository checkout" in changed["stderr"]
subprocess.run(["git", "sparse-checkout", "disable"], cwd=repository, check=True)
assert source.read_text() == "pass\n"
assert run_workbench(state_dir, *command, "--check-target")["scan"]["scanId"] == scan["scanId"]
assert get_scan(state_dir, scan_id, "--check-target")["scan"]["scanId"] == scan_id
def test_check_scan_target_rejects_replaced_checkout(tmp_path: Path) -> None:
repository = tmp_path / "repository"
repository.mkdir()
(repository / "source.py").write_text("pass\n")
state_dir = tmp_path / "state"
(tmp_path / "results").mkdir(mode=0o700)
scan = create_cli_scan(state_dir, tmp_path / "results", repository, complete=False)
state_dir, scan_id = start_validation_scan(tmp_path, repository)
repository.rename(tmp_path / "original")
repository.mkdir()
(repository / "source.py").write_text("pass\n")
changed = run_workbench(
state_dir, "get-scan", "--scan-id", scan["scanId"], "--check-target", check=False
)
changed = get_scan(state_dir, scan_id, "--check-target", check=False)
assert changed["returncode"] != 0
assert "checkout path was replaced" in changed["stderr"]
@@ -162,28 +144,25 @@ def test_check_scan_target_accepts_legacy_revision_only_git_scan(tmp_path: Path)
check=True,
)
subprocess.run(["git", "commit", "-qm", "Add submodule"], cwd=repository, check=True)
state_dir = tmp_path / "state"
(tmp_path / "results").mkdir(mode=0o700)
scan = create_cli_scan(state_dir, tmp_path / "results", repository, complete=False)
state_dir, scan_id = start_validation_scan(tmp_path, repository)
with closing(sqlite3.connect(state_dir / "workbench.sqlite3")) as connection:
connection.execute(
"UPDATE scans SET target_snapshot_digest = NULL WHERE id = ?", (scan["scanId"],)
"UPDATE scans SET target_snapshot_digest = NULL WHERE id = ?", (scan_id,)
)
connection.commit()
command = ("get-scan", "--scan-id", scan["scanId"], "--check-target")
assert run_workbench(state_dir, *command)["scan"]["scanId"] == scan["scanId"]
assert get_scan(state_dir, scan_id, "--check-target")["scan"]["scanId"] == scan_id
# Revision-only records cannot compare content against an unrecorded digest.
source = repository / "README.md"
original = source.read_bytes()
source.write_text("Changed working-tree content.\n")
assert run_workbench(state_dir, *command)["scan"]["scanId"] == scan["scanId"]
assert get_scan(state_dir, scan_id, "--check-target")["scan"]["scanId"] == scan_id
source.write_bytes(original)
submodule_source = submodule / "README.md"
submodule_original = submodule_source.read_bytes()
submodule_source.write_text("Changed submodule content.\n")
dirty_submodule = run_workbench(state_dir, *command, check=False)
dirty_submodule = get_scan(state_dir, scan_id, "--check-target", check=False)
assert dirty_submodule["returncode"] != 0
assert "Dirty Git submodules" in dirty_submodule["stderr"]
submodule_source.write_bytes(submodule_original)
@@ -191,14 +170,14 @@ def test_check_scan_target_accepts_legacy_revision_only_git_scan(tmp_path: Path)
subprocess.run(
["git", "commit", "--allow-empty", "-qm", "New revision"], cwd=repository, check=True
)
changed = run_workbench(state_dir, *command, check=False)
changed = get_scan(state_dir, scan_id, "--check-target", check=False)
assert changed["returncode"] != 0
assert "Repository HEAD changed" in changed["stderr"]
repository.rename(tmp_path / "original")
repository.mkdir()
source.write_bytes(original)
replaced = run_workbench(state_dir, *command, check=False)
replaced = get_scan(state_dir, scan_id, "--check-target", check=False)
assert replaced["returncode"] != 0
assert "checkout path was replaced" in replaced["stderr"]
@@ -212,32 +191,27 @@ def test_check_legacy_scan_target_does_not_read_unrecorded_contents(
) -> None:
repository = tmp_path / "repository"
initialize_git_repository(repository)
state_dir = tmp_path / "state"
(tmp_path / "results").mkdir(mode=0o700)
scan = create_cli_scan(state_dir, tmp_path / "results", repository, complete=False)
command = ("get-scan", "--scan-id", scan["scanId"])
state_dir, scan_id = start_validation_scan(tmp_path, repository)
entry = repository / "unreadable.txt"
entry.write_text("Synthetic untracked contents.\n")
mode = entry.stat().st_mode
entry.chmod(0)
try:
assert run_workbench(state_dir, *command)["scan"]["scanId"] == scan["scanId"]
recorded = run_workbench(state_dir, *command, "--check-target", check=False)
assert get_scan(state_dir, scan_id)["scan"]["scanId"] == scan_id
recorded = get_scan(state_dir, scan_id, "--check-target", check=False)
assert recorded["returncode"] != 0
assert "Could not read untracked file" in recorded["stderr"]
with closing(sqlite3.connect(state_dir / "workbench.sqlite3")) as connection:
connection.execute(
"UPDATE scans SET target_snapshot_digest = NULL WHERE id = ?", (scan["scanId"],)
"UPDATE scans SET target_snapshot_digest = NULL WHERE id = ?", (scan_id,)
)
connection.commit()
connection.row_factory = sqlite3.Row
stored_scan = connection.execute(
"SELECT * FROM scans WHERE id = ?", (scan["scanId"],)
"SELECT * FROM scans WHERE id = ?", (scan_id,)
).fetchone()
with pytest.raises(SystemExit, match="Could not read untracked file"):
workbench_api["remediation_checkout_snapshot"](stored_scan)
assert (
run_workbench(state_dir, *command, "--check-target")["scan"]["scanId"] == scan["scanId"]
)
assert get_scan(state_dir, scan_id, "--check-target")["scan"]["scanId"] == scan_id
finally:
entry.chmod(mode)
@@ -183,6 +183,52 @@ def create_historical_database(
return connection, apply_migrations
def insert_historical_row(
connection: sqlite3.Connection, table: str, timestamp: str, **columns: object
) -> None:
columns.update(created_at=timestamp, updated_at=timestamp)
names = ", ".join(columns)
parameters = ", ".join("?" for _ in columns)
connection.execute(
f"INSERT INTO {table} ({names}) VALUES ({parameters})", tuple(columns.values())
)
def insert_legacy_scan(connection: sqlite3.Connection, timestamp: str, **overrides: object) -> None:
columns = {
"id": "legacy-scan",
"workspace_id": "legacy-workspace",
"target_path": "/legacy/target",
"target_revision": "legacy-revision",
"scope": ".",
"mode": "standard",
"scan_dir": "/legacy/scan",
"status": "running",
"phase": "discovery",
"started_at": timestamp,
}
insert_historical_row(connection, "scans", timestamp, **(columns | overrides))
def rename_migration(connection: sqlite3.Connection, version: int, name: str) -> None:
connection.execute("UPDATE schema_migrations SET name = ? WHERE version = ?", (name, version))
def record_migration(
connection: sqlite3.Connection, version: int, name: str, timestamp: str
) -> None:
connection.execute(
"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
(version, name, timestamp),
)
def migration_name_row(connection: sqlite3.Connection, version: int):
return connection.execute(
"SELECT name FROM schema_migrations WHERE version = ?", (version,)
).fetchone()
def create_migration_history(connection: sqlite3.Connection) -> None:
connection.execute(
"""
@@ -203,10 +249,7 @@ def apply_historical_migrations(
for version, name, sql in migrations:
for statement in SCHEMA.sql_statements(sql):
connection.execute(statement)
connection.execute(
"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
(version, name, timestamp),
)
record_migration(connection, version, name, timestamp)
def add_legacy_profile_columns(connection: sqlite3.Connection, *, dynamic: bool) -> tuple[str, str]:
@@ -262,34 +305,25 @@ def insert_legacy_profile_scan(
timestamp: str,
) -> tuple[str, str]:
workspace_id, scan_id = str(uuid.uuid4()), str(uuid.uuid4())
connection.execute(
"""
INSERT INTO workspaces (
id, target_path, default_mode, execution_model, reasoning_effort,
created_at, updated_at
) VALUES (?, ?, 'standard', ?, ?, ?, ?)
""",
(workspace_id, str(tmp_path / "target"), model, effort, timestamp, timestamp),
insert_historical_row(
connection,
"workspaces",
timestamp,
id=workspace_id,
target_path=str(tmp_path / "target"),
default_mode="standard",
execution_model=model,
reasoning_effort=effort,
)
connection.execute(
"""
INSERT INTO scans (
id, workspace_id, target_path, target_revision, scope, mode, scan_dir,
status, phase, started_at, created_at, updated_at, execution_model, reasoning_effort
) VALUES (?, ?, ?, 'legacy-revision', '.', 'standard', ?, 'running',
'discovery', ?, ?, ?, ?, ?)
""",
(
scan_id,
workspace_id,
str(tmp_path / "target"),
str(tmp_path / "legacy-scan"),
timestamp,
timestamp,
timestamp,
model,
effort,
),
insert_legacy_scan(
connection,
timestamp,
id=scan_id,
workspace_id=workspace_id,
target_path=str(tmp_path / "target"),
scan_dir=str(tmp_path / "legacy-scan"),
execution_model=model,
reasoning_effort=effort,
)
return workspace_id, scan_id
@@ -298,15 +332,14 @@ def assert_new_scan_model_is_independent(state_dir: Path, target: Path, scan_roo
current_workspace = create_saved_workspace(state_dir, target)
current_scan = start_delivered_scan(
state_dir,
"--workspace-id",
str(current_workspace["id"]),
"--scan-root",
str(scan_root),
"--model",
"gpt-5.6-sol",
)
current_scan_id = str(current_scan["results"]["scanId"])
assert current_scan["results"]["reasoningEffort"] is None
current_scan_id = str(current_scan["scanId"])
assert current_scan["reasoningEffort"] is None
update_progress(state_dir, current_scan_id, "--reasoning-effort", "high")
with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
assert connection.execute(
@@ -925,6 +958,27 @@ def test_comparison_indexes_upgrade_without_skipping_findings_migrations(
assert connection.execute("PRAGMA foreign_key_check").fetchall() == []
def insert_classified_scan(
connection: sqlite3.Connection, scan_id: str, finding_ids: list[str], timestamp: str
) -> None:
insert_legacy_scan(
connection,
timestamp,
id=scan_id,
workspace_id="workspace",
target_path="/target",
target_revision="revision",
scan_dir=f"/scans/{scan_id}",
status="complete",
phase="reporting",
)
connection.execute(
"INSERT INTO scan_severity_classifications (scan_id, finding_ids_json, assessed_at) "
"VALUES (?, ?, ?)",
(scan_id, json.dumps(finding_ids), timestamp),
)
@pytest.mark.parametrize("indexed", [False, True])
def test_severity_migration_only_copies_assessments_with_matching_scan_occurrences(
indexed: bool,
@@ -933,24 +987,9 @@ def test_severity_migration_only_copies_assessments_with_matching_scan_occurrenc
timestamp = "2026-09-01T00:00:00Z"
with connection:
connection.execute("PRAGMA foreign_keys = ON")
connection.execute(
"INSERT INTO workspaces (id, created_at, updated_at) VALUES (?, ?, ?)",
("workspace", timestamp, timestamp),
)
insert_historical_row(connection, "workspaces", timestamp, id="workspace")
for scan_id in ("first-scan", "second-scan"):
connection.execute(
"""INSERT INTO scans (
id, workspace_id, target_path, target_revision, scope, mode, scan_dir,
status, phase, started_at, created_at, updated_at
) VALUES (?, 'workspace', '/target', 'revision', '.', 'standard', ?,
'complete', 'reporting', ?, ?, ?)""",
(scan_id, f"/scans/{scan_id}", timestamp, timestamp, timestamp),
)
connection.execute(
"""INSERT INTO scan_severity_classifications
(scan_id, finding_ids_json, assessed_at) VALUES (?, '["finding"]', ?)""",
(scan_id, timestamp),
)
insert_classified_scan(connection, scan_id, ["finding"], timestamp)
connection.execute(
"""INSERT INTO findings
(id, fingerprint, rule_id, identity_anchor, created_at, updated_at)
@@ -994,27 +1033,12 @@ def test_severity_migration_scales_with_classified_scans() -> None:
connection, apply_migrations = create_historical_database(43)
with closing(connection):
connection.execute("PRAGMA foreign_keys = ON")
connection.execute(
"INSERT INTO workspaces (id, created_at, updated_at) VALUES ('workspace', ?, ?)",
(timestamp, timestamp),
)
insert_historical_row(connection, "workspaces", timestamp, id="workspace")
scan_count, findings_per_scan = scale, 10
for scan in range(scan_count):
scan_id = f"scan-{scan}"
finding_ids = [f"finding-{scan}-{item}" for item in range(findings_per_scan)]
connection.execute(
"""INSERT INTO scans (
id, workspace_id, target_path, target_revision, scope, mode, scan_dir,
status, phase, started_at, created_at, updated_at
) VALUES (?, 'workspace', '/target', 'revision', '.', 'standard', ?,
'complete', 'reporting', ?, ?, ?)""",
(scan_id, f"/scans/{scan_id}", timestamp, timestamp, timestamp),
)
connection.execute(
"""INSERT INTO scan_severity_classifications
(scan_id, finding_ids_json, assessed_at) VALUES (?, ?, ?)""",
(scan_id, json.dumps(finding_ids), timestamp),
)
insert_classified_scan(connection, scan_id, finding_ids, timestamp)
for finding_id in finding_ids:
occurrence_id = f"occurrence-{finding_id}"
connection.execute(
@@ -1080,32 +1104,8 @@ def test_workbench_backfills_repository_targets_only_during_migration() -> None:
def test_scan_model_migration_preserves_existing_scans() -> None:
connection, apply_migrations = create_historical_database(25)
timestamp = "2026-07-01T00:00:00Z"
connection.execute(
"INSERT INTO workspaces (id, created_at, updated_at) VALUES (?, ?, ?)",
("legacy-workspace", timestamp, timestamp),
)
connection.execute(
"""
INSERT INTO scans (
id, workspace_id, target_path, target_revision, scope, mode, scan_dir,
status, phase, started_at, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
"legacy-scan",
"legacy-workspace",
"/legacy/target",
"legacy-revision",
".",
"standard",
"/legacy/scan",
"running",
"discovery",
timestamp,
timestamp,
timestamp,
),
)
insert_historical_row(connection, "workspaces", timestamp, id="legacy-workspace")
insert_legacy_scan(connection, timestamp)
connection.commit()
apply_migrations(connection)
@@ -1135,27 +1135,15 @@ def test_deep_scan_failure_counter_migration_backfills_existing_thresholds(
timestamp = "2026-07-01T00:00:00Z"
for scan_id, stop_after_no_new in (("legacy-scan-a", 2), ("legacy-scan-b", 7)):
workspace_id = f"workspace-{scan_id}"
connection.execute(
"INSERT INTO workspaces (id, created_at, updated_at) VALUES (?, ?, ?)",
(workspace_id, timestamp, timestamp),
)
connection.execute(
"""
INSERT INTO scans (
id, workspace_id, target_path, target_revision, scope, mode, scan_dir,
status, phase, started_at, created_at, updated_at
) VALUES (?, ?, ?, 'legacy-revision', '.', 'deep', ?,
'running', 'discovery', ?, ?, ?)
""",
(
scan_id,
workspace_id,
f"/legacy/{scan_id}",
f"/legacy/scans/{scan_id}",
timestamp,
timestamp,
timestamp,
),
insert_historical_row(connection, "workspaces", timestamp, id=workspace_id)
insert_legacy_scan(
connection,
timestamp,
id=scan_id,
workspace_id=workspace_id,
target_path=f"/legacy/{scan_id}",
mode="deep",
scan_dir=f"/legacy/scans/{scan_id}",
)
connection.execute(
"""
@@ -1170,10 +1158,7 @@ def test_deep_scan_failure_counter_migration_backfills_existing_thresholds(
connection.execute("ALTER TABLE deep_scan_runs ADD COLUMN coordinator_owner_id TEXT")
connection.execute("ALTER TABLE deep_scan_runs ADD COLUMN coordinator_heartbeat_at TEXT")
if legacy_name is not None:
connection.execute(
"INSERT INTO schema_migrations (version, name, applied_at) VALUES (27, ?, ?)",
(legacy_name, timestamp),
)
record_migration(connection, 27, legacy_name, timestamp)
connection.commit()
apply_migrations(connection)
assert [
@@ -1196,9 +1181,9 @@ def test_deep_scan_failure_counter_migration_backfills_existing_thresholds(
"FROM deep_scan_runs ORDER BY scan_id"
)
] == [(9, 3), (9, 3)]
assert connection.execute("SELECT name FROM schema_migrations WHERE version = 27").fetchone()[
"name"
] == (legacy_name or "persist deep scan consecutive discovery failures")
assert migration_name_row(connection, 27)["name"] == (
legacy_name or "persist deep scan consecutive discovery failures"
)
if has_owner_columns:
assert {"coordinator_owner_id", "coordinator_heartbeat_at"} <= {
row[1] for row in connection.execute("PRAGMA table_info(deep_scan_runs)")
@@ -1213,20 +1198,8 @@ def test_deep_scan_time_limit_migration_backfills_and_repairs_existing_runs(
connection, apply_migrations = create_historical_database(28)
timestamp = "2026-07-01T00:00:00Z"
connection.execute(
"INSERT INTO workspaces (id, created_at, updated_at) VALUES (?, ?, ?)",
("legacy-workspace", timestamp, timestamp),
)
connection.execute(
"""
INSERT INTO scans (
id, workspace_id, target_path, target_revision, scope, mode, scan_dir,
status, phase, started_at, created_at, updated_at
) VALUES (?, ?, '/legacy/target', 'legacy-revision', '.', 'deep',
'/legacy/scan', 'running', 'discovery', ?, ?, ?)
""",
("legacy-scan", "legacy-workspace", timestamp, timestamp, timestamp),
)
insert_historical_row(connection, "workspaces", timestamp, id="legacy-workspace")
insert_legacy_scan(connection, timestamp, mode="deep")
connection.execute(
"""
INSERT INTO deep_scan_runs (
@@ -1237,10 +1210,7 @@ def test_deep_scan_time_limit_migration_backfills_and_repairs_existing_runs(
("legacy-scan", timestamp, timestamp),
)
if migration_recorded:
connection.execute(
"INSERT INTO schema_migrations (version, name, applied_at) VALUES (28, ?, ?)",
("persist deep scan discovery time limit", timestamp),
)
record_migration(connection, 28, "persist deep scan discovery time limit", timestamp)
connection.commit()
apply_migrations(connection)
@@ -1252,10 +1222,7 @@ def test_deep_scan_time_limit_migration_backfills_and_repairs_existing_runs(
apply_migrations(connection)
assert connection.execute("SELECT max_time_hours FROM deep_scan_runs").fetchone()[0] == 2.5
assert (
connection.execute("SELECT name FROM schema_migrations WHERE version = 28").fetchone()[0]
== "persist deep scan discovery time limit"
)
assert migration_name_row(connection, 28)[0] == "persist deep scan discovery time limit"
def test_workbench_reconciles_monorepo_migration_lineage() -> None:
@@ -1559,15 +1526,11 @@ def test_workbench_repairs_recorded_deep_scan_migration(
assert connection.execute(
"SELECT deep_scan_owner_thread_id, status FROM scans WHERE id = ?", (scan_id,)
).fetchone() == (expected_owner, "running")
assert connection.execute(
"SELECT name FROM schema_migrations WHERE version = 11"
).fetchone() == ("deep scan orchestration state",)
assert connection.execute(
"SELECT name FROM schema_migrations WHERE version = 27"
).fetchone() == ("persist deep scan consecutive discovery failures",)
assert connection.execute(
"SELECT name FROM schema_migrations WHERE version = 28"
).fetchone() == ("persist deep scan discovery time limit",)
assert migration_name_row(connection, 11) == ("deep scan orchestration state",)
assert migration_name_row(connection, 27) == (
"persist deep scan consecutive discovery failures",
)
assert migration_name_row(connection, 28) == ("persist deep scan discovery time limit",)
assert {"max_time_hours", "terminal_reviewed_surface_count"} <= {
row[1] for row in connection.execute("PRAGMA table_info(deep_scan_runs)")
}
@@ -1668,31 +1631,27 @@ def test_workbench_repairs_pre_release_scan_continuation_migration(tmp_path: Pat
connection.execute("PRAGMA foreign_keys = ON")
create_migration_history(connection)
apply_historical_migrations(connection, (*migrations[:10], *legacy_migrations), timestamp)
connection.execute(
"""
INSERT INTO workspaces (
id, target_path, target_title, default_mode, submitted, thread_id,
created_at, updated_at
) VALUES (?, ?, ?, 'deep', 1, ?, ?, ?)
""",
(workspace_id, str(target), "Legacy target", thread_id, timestamp, timestamp),
insert_historical_row(
connection,
"workspaces",
timestamp,
id=workspace_id,
target_path=str(target),
target_title="Legacy target",
default_mode="deep",
submitted=1,
thread_id=thread_id,
)
connection.execute(
"""
INSERT INTO scans (
id, workspace_id, target_path, target_revision, scope, mode, scan_dir,
status, phase, started_at, created_at, updated_at
) VALUES (?, ?, ?, 'unversioned', '.', 'deep', ?, 'running', 'preflight', ?, ?, ?)
""",
(
scan_id,
workspace_id,
str(target),
str(tmp_path / "scans"),
timestamp,
timestamp,
timestamp,
),
insert_legacy_scan(
connection,
timestamp,
id=scan_id,
workspace_id=workspace_id,
target_path=str(target),
target_revision="unversioned",
mode="deep",
scan_dir=str(tmp_path / "scans"),
phase="preflight",
)
connection.execute(
"INSERT INTO scan_progress (scan_id, updated_at) VALUES (?, ?)",
@@ -1732,10 +1691,7 @@ def test_workbench_repairs_pre_release_scan_continuation_migration(tmp_path: Pat
(scan_id, timestamp, timestamp),
)
first = workspace_command(state_dir, "get-workspace", workspace_id)
second = workspace_command(state_dir, "get-workspace", workspace_id)
assert first == second
first = read_migrated_workspace_twice(state_dir, workspace_id)
assert first["results"]["continuationThreadId"] is None
with sqlite3.connect(database) as connection:
assert connection.execute(
@@ -1776,29 +1732,36 @@ def test_workbench_repairs_pre_release_scan_continuation_migration(tmp_path: Pat
assert connection.execute("PRAGMA foreign_key_check").fetchall() == []
def test_workbench_repairs_recorded_scan_scope_file_count_migration(tmp_path: Path) -> None:
def start_migration_scan(tmp_path: Path) -> tuple[Path, str, str, Path]:
state_dir, target = empty_target_paths(tmp_path)
workspace = create_saved_workspace(state_dir, target)
started = start_scan_command(state_dir, str(workspace["id"]))
scan_id = str(started["results"]["scanId"])
database = state_dir / "workbench.sqlite3"
workspace_id = str(create_saved_workspace(state_dir, target)["id"])
started = start_scan_command(state_dir, workspace_id)
return (
state_dir,
workspace_id,
str(started["results"]["scanId"]),
state_dir / "workbench.sqlite3",
)
def read_migrated_workspace_twice(state_dir: Path, workspace_id: str) -> dict[str, object]:
first = workspace_command(state_dir, "get-workspace", workspace_id)
second = workspace_command(state_dir, "get-workspace", workspace_id)
assert first == second
return first
def test_workbench_repairs_recorded_scan_scope_file_count_migration(tmp_path: Path) -> None:
state_dir, workspace_id, scan_id, database = start_migration_scan(tmp_path)
with sqlite3.connect(database) as connection:
connection.execute("ALTER TABLE scan_progress DROP COLUMN scope_file_count")
connection.execute(
"UPDATE schema_migrations SET name = ? WHERE version = 13",
("linear scan phase enforcement",),
)
rename_migration(connection, 13, "linear scan phase enforcement")
first = workspace_command(state_dir, "get-workspace", str(workspace["id"]))
second = workspace_command(state_dir, "get-workspace", str(workspace["id"]))
assert first == second
first = read_migrated_workspace_twice(state_dir, workspace_id)
assert first["results"]["progress"]["coverage"]["filesTotal"] is None
with sqlite3.connect(database) as connection:
assert connection.execute(
"SELECT name FROM schema_migrations WHERE version = 13"
).fetchone() == ("linear scan phase enforcement",)
assert migration_name_row(connection, 13) == ("linear scan phase enforcement",)
assert connection.execute(
"SELECT scope_file_count FROM scan_progress WHERE scan_id = ?", (scan_id,)
).fetchone() == (None,)
@@ -1822,9 +1785,7 @@ def test_workbench_repairs_shadowed_capability_preflight_migration(
with sqlite3.connect(database) as connection:
connection.execute("ALTER TABLE workspaces DROP COLUMN capability_preflight_json")
connection.execute(
"UPDATE schema_migrations SET name = ? WHERE version = 2", (legacy_name,)
)
rename_migration(connection, 2, legacy_name)
if owns_thread_schema:
connection.execute("DELETE FROM schema_migrations WHERE version = 6")
@@ -1872,32 +1833,24 @@ def test_workbench_upgrades_stable_scan_target_identity_migration(tmp_path: Path
(*migrations[:10], legacy_migration, *migrations[11:15]),
timestamp,
)
connection.execute(
"""
INSERT INTO workspaces (
id, target_path, target_title, default_mode, submitted, created_at, updated_at
) VALUES (?, ?, 'Legacy target', 'standard', 1, ?, ?)
""",
(workspace_id, str(target), timestamp, timestamp),
insert_historical_row(
connection,
"workspaces",
timestamp,
id=workspace_id,
target_path=str(target),
target_title="Legacy target",
default_mode="standard",
submitted=1,
)
connection.execute(
"""
INSERT INTO scans (
id, workspace_id, target_id, target_path, target_revision, scope, mode,
scan_dir, status, phase, started_at, created_at, updated_at
) VALUES (?, ?, ?, ?, 'legacy-revision', '.', 'standard', ?, 'running',
'discovery', ?, ?, ?)
""",
(
scan_id,
workspace_id,
legacy_target_id,
str(target),
str(tmp_path / "scans"),
timestamp,
timestamp,
timestamp,
),
insert_legacy_scan(
connection,
timestamp,
id=scan_id,
workspace_id=workspace_id,
target_id=legacy_target_id,
target_path=str(target),
scan_dir=str(tmp_path / "scans"),
)
connection.execute(
"INSERT INTO scan_progress (scan_id, updated_at) VALUES (?, ?)",
@@ -1948,11 +1901,7 @@ def test_workbench_upgrades_stable_scan_target_identity_migration(tmp_path: Path
def test_workbench_applies_shadowed_delivered_claim_cleanup_once(tmp_path: Path) -> None:
state_dir, target = empty_target_paths(tmp_path)
workspace = create_saved_workspace(state_dir, target)
started = start_scan_command(state_dir, str(workspace["id"]))
scan_id = str(started["results"]["scanId"])
database = state_dir / "workbench.sqlite3"
state_dir, _, scan_id, database = start_migration_scan(tmp_path)
with sqlite3.connect(database) as connection:
connection.execute(
@@ -1960,10 +1909,7 @@ def test_workbench_applies_shadowed_delivered_claim_cleanup_once(tmp_path: Path)
"handoff_claim_token = ? WHERE id = ?",
("2026-06-30T00:00:00Z", "stale-claim", scan_id),
)
connection.execute(
"UPDATE schema_migrations SET name = ? WHERE version = 18",
("scan target summaries",),
)
rename_migration(connection, 18, "scan target summaries")
run_workbench(state_dir, "database-info")
@@ -1971,9 +1917,7 @@ def test_workbench_applies_shadowed_delivered_claim_cleanup_once(tmp_path: Path)
assert connection.execute(
"SELECT handoff_claimed_at, handoff_claim_token FROM scans WHERE id = ?", (scan_id,)
).fetchone() == (None, None)
assert connection.execute(
"SELECT name FROM schema_migrations WHERE version = 18"
).fetchone() == ("clear legacy delivered handoff claims",)
assert migration_name_row(connection, 18) == ("clear legacy delivered handoff claims",)
connection.execute(
"UPDATE scans SET handoff_claimed_at = ?, handoff_claim_token = ? WHERE id = ?",
("2026-07-01T00:00:00Z", "current-claim", scan_id),
@@ -2000,10 +1944,7 @@ def test_workbench_repairs_shadowed_setup_preferences_migration(
with sqlite3.connect(database) as connection:
connection.execute("DROP TABLE setup_preferences")
connection.execute(
"UPDATE schema_migrations SET name = ? WHERE version = 19",
(legacy_name,),
)
rename_migration(connection, 19, legacy_name)
run_workbench(state_dir, "database-info")
with sqlite3.connect(database) as connection:
@@ -2012,9 +1953,7 @@ def test_workbench_repairs_shadowed_setup_preferences_migration(
"skip_setup_ui",
"updated_at",
]
assert connection.execute(
"SELECT name FROM schema_migrations WHERE version = 19"
).fetchone() == ("persist setup workspace preference",)
assert migration_name_row(connection, 19) == ("persist setup workspace preference",)
@pytest.mark.parametrize(
@@ -2024,34 +1963,22 @@ def test_workbench_repairs_shadowed_setup_preferences_migration(
def test_workbench_repairs_shadowed_phase_progress_migration(
tmp_path: Path, legacy_name: str
) -> None:
state_dir, target = empty_target_paths(tmp_path)
workspace = create_saved_workspace(state_dir, target)
started = start_scan_command(state_dir, str(workspace["id"]))
scan_id = str(started["results"]["scanId"])
database = state_dir / "workbench.sqlite3"
state_dir, workspace_id, scan_id, database = start_migration_scan(tmp_path)
with sqlite3.connect(database) as connection:
connection.execute("ALTER TABLE scan_progress DROP COLUMN phase_items_completed")
connection.execute("ALTER TABLE scan_progress DROP COLUMN phase_items_total")
connection.execute("ALTER TABLE scan_progress DROP COLUMN phase_progress_unit")
connection.execute(
"UPDATE schema_migrations SET name = ? WHERE version = 20",
(legacy_name,),
)
rename_migration(connection, 20, legacy_name)
first = workspace_command(state_dir, "get-workspace", str(workspace["id"]))
second = workspace_command(state_dir, "get-workspace", str(workspace["id"]))
assert first == second
read_migrated_workspace_twice(state_dir, workspace_id)
with sqlite3.connect(database) as connection:
assert connection.execute(
"SELECT phase_items_total, phase_items_completed, phase_progress_unit "
"FROM scan_progress WHERE scan_id = ?",
(scan_id,),
).fetchone() == (0, 0, None)
assert connection.execute(
"SELECT name FROM schema_migrations WHERE version = 20"
).fetchone() == ("phase-specific scan progress",)
assert migration_name_row(connection, 20) == ("phase-specific scan progress",)
with pytest.raises(sqlite3.IntegrityError) as invalid_unit:
connection.execute(
"UPDATE scan_progress SET phase_progress_unit = 'invalid' WHERE scan_id = ?",
@@ -2071,11 +1998,7 @@ def test_workbench_repairs_shadowed_phase_progress_migration(
def test_workbench_repairs_shadowed_preflight_progress_migration(
tmp_path: Path, legacy_name: str
) -> None:
state_dir, target = empty_target_paths(tmp_path)
saved = create_saved_workspace(state_dir, target)
started = start_scan_command(state_dir, str(saved["id"]))
scan_id = str(started["results"]["scanId"])
database = state_dir / "workbench.sqlite3"
state_dir, _, scan_id, database = start_migration_scan(tmp_path)
with sqlite3.connect(database) as connection:
connection.execute(
"""
@@ -2086,9 +2009,7 @@ def test_workbench_repairs_shadowed_preflight_progress_migration(
""",
(scan_id,),
)
connection.execute(
"UPDATE schema_migrations SET name = ? WHERE version = 21", (legacy_name,)
)
rename_migration(connection, 21, legacy_name)
connection.execute("ALTER TABLE scan_progress DROP COLUMN preflight_checks_completed")
connection.execute("ALTER TABLE scan_progress DROP COLUMN preflight_checks_total")
connection.execute("ALTER TABLE scan_progress DROP COLUMN preflight_issues_json")
@@ -2104,38 +2025,24 @@ def test_workbench_repairs_shadowed_preflight_progress_migration(
""",
(scan_id,),
).fetchone() == (0, 0, "[]")
assert connection.execute(
"SELECT name FROM schema_migrations WHERE version = 21"
).fetchone() == ("current scan preflight state",)
assert migration_name_row(connection, 21) == ("current scan preflight state",)
def test_workbench_repairs_shadowed_scan_recipe_migration(tmp_path: Path) -> None:
state_dir, target = empty_target_paths(tmp_path)
workspace = create_saved_workspace(state_dir, target)
started = start_scan_command(state_dir, str(workspace["id"]))
scan_id = str(started["results"]["scanId"])
database = state_dir / "workbench.sqlite3"
state_dir, workspace_id, scan_id, database = start_migration_scan(tmp_path)
with sqlite3.connect(database) as connection:
connection.execute("ALTER TABLE scans DROP COLUMN parent_scan_id")
connection.execute("ALTER TABLE scans DROP COLUMN recipe_json")
connection.execute(
"UPDATE schema_migrations SET name = ? WHERE version = 22",
("dynamic scan execution profiles",),
)
rename_migration(connection, 22, "dynamic scan execution profiles")
first = workspace_command(state_dir, "get-workspace", str(workspace["id"]))
second = workspace_command(state_dir, "get-workspace", str(workspace["id"]))
assert first == second
read_migrated_workspace_twice(state_dir, workspace_id)
with sqlite3.connect(database) as connection:
assert connection.execute(
"SELECT recipe_json, parent_scan_id FROM scans WHERE id = ?",
(scan_id,),
).fetchone() == (None, None)
assert connection.execute(
"SELECT name FROM schema_migrations WHERE version = 22"
).fetchone() == ("replayable scan launch recipes",)
assert migration_name_row(connection, 22) == ("replayable scan launch recipes",)
assert any(
row[3] == "parent_scan_id" and row[2] == "scans" and row[6] == "SET NULL"
for row in connection.execute("PRAGMA foreign_key_list(scans)")
@@ -2144,11 +2051,7 @@ def test_workbench_repairs_shadowed_scan_recipe_migration(tmp_path: Path) -> Non
def test_workbench_reconciles_released_completion_warning_version(tmp_path: Path) -> None:
state_dir, target = empty_target_paths(tmp_path)
workspace = create_saved_workspace(state_dir, target)
started = start_scan_command(state_dir, str(workspace["id"]))
scan_id = str(started["results"]["scanId"])
database = state_dir / "workbench.sqlite3"
state_dir, workspace_id, scan_id, database = start_migration_scan(tmp_path)
with sqlite3.connect(database) as connection:
connection.execute(
@@ -2158,15 +2061,9 @@ def test_workbench_reconciles_released_completion_warning_version(tmp_path: Path
connection.execute("DELETE FROM schema_migrations WHERE version = 26")
connection.execute("ALTER TABLE scans DROP COLUMN reasoning_effort")
connection.execute("ALTER TABLE scans DROP COLUMN model")
connection.execute(
"UPDATE schema_migrations SET name = ? WHERE version = 25",
("persist scan completion warnings",),
)
rename_migration(connection, 25, "persist scan completion warnings")
first = workspace_command(state_dir, "get-workspace", str(workspace["id"]))
second = workspace_command(state_dir, "get-workspace", str(workspace["id"]))
assert first == second
read_migrated_workspace_twice(state_dir, workspace_id)
with sqlite3.connect(database) as connection:
assert connection.execute(
"SELECT model, reasoning_effort, completion_warnings_json FROM scans WHERE id = ?",
@@ -2181,32 +2078,20 @@ def test_workbench_reconciles_released_completion_warning_version(tmp_path: Path
def test_workbench_repairs_recorded_completion_warnings_migration(tmp_path: Path) -> None:
state_dir, target = empty_target_paths(tmp_path)
workspace = create_saved_workspace(state_dir, target)
started = start_scan_command(state_dir, str(workspace["id"]))
scan_id = str(started["results"]["scanId"])
database = state_dir / "workbench.sqlite3"
state_dir, workspace_id, scan_id, database = start_migration_scan(tmp_path)
with sqlite3.connect(database) as connection:
connection.execute("ALTER TABLE scans DROP COLUMN completion_warnings_json")
connection.execute("ALTER TABLE scans ADD COLUMN attention_message TEXT")
connection.execute(
"UPDATE schema_migrations SET name = ? WHERE version = 26",
("recoverable scan attention",),
)
rename_migration(connection, 26, "recoverable scan attention")
first = workspace_command(state_dir, "get-workspace", str(workspace["id"]))
second = workspace_command(state_dir, "get-workspace", str(workspace["id"]))
assert first == second
read_migrated_workspace_twice(state_dir, workspace_id)
with sqlite3.connect(database) as connection:
assert connection.execute(
"SELECT completion_warnings_json, attention_message FROM scans WHERE id = ?",
(scan_id,),
).fetchone() == ("[]", None)
assert connection.execute(
"SELECT name FROM schema_migrations WHERE version = 26"
).fetchone() == ("recoverable scan attention",)
assert migration_name_row(connection, 26) == ("recoverable scan attention",)
assert connection.execute("PRAGMA foreign_key_check").fetchall() == []
@@ -2243,10 +2128,7 @@ def test_workbench_reconciles_legacy_execution_profile_migrations(
current_migrations = (*migrations[: legacy_version - 1], *migrations[legacy_version:24])
apply_historical_migrations(connection, current_migrations, timestamp)
legacy_model, legacy_effort = add_legacy_profile_columns(connection, dynamic=dynamic)
connection.execute(
"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
(legacy_version, legacy_name, timestamp),
)
record_migration(connection, legacy_version, legacy_name, timestamp)
if preexisting_model:
connection.execute("ALTER TABLE scans ADD COLUMN model TEXT")
workspace_id, scan_id = insert_legacy_profile_scan(
@@ -2266,9 +2148,7 @@ def test_workbench_reconciles_legacy_execution_profile_migrations(
25: "persist scan model settings",
}.get(legacy_version, legacy_name)
with sqlite3.connect(database) as connection:
assert connection.execute(
"SELECT name FROM schema_migrations WHERE version = ?", (legacy_version,)
).fetchone() == (expected_migration_name,)
assert migration_name_row(connection, legacy_version) == (expected_migration_name,)
assert connection.execute(
"""
SELECT legacy_execution_model, legacy_reasoning_effort, model, reasoning_effort
@@ -2375,9 +2255,7 @@ def test_workbench_upgrades_pre_release_source_scope_migration(
run_workbench(state_dir, "database-info")
with sqlite3.connect(database) as connection:
assert connection.execute(
"SELECT name FROM schema_migrations WHERE version = 34"
).fetchone() == ("associate findings with repositories",)
assert migration_name_row(connection, 34) == ("associate findings with repositories",)
assert connection.execute(
"SELECT version, applied_at FROM schema_migrations WHERE name = ?",
(source_scope[1],),
@@ -2385,9 +2263,7 @@ def test_workbench_upgrades_pre_release_source_scope_migration(
assert connection.execute(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'finding_repositories'"
).fetchone() == ("finding_repositories",)
assert connection.execute(
"SELECT name FROM schema_migrations WHERE version = 43"
).fetchone() == ("preserve severity assessments per scan",)
assert migration_name_row(connection, 43) == ("preserve severity assessments per scan",)
assert connection.execute("SELECT COUNT(*) FROM scan_severity_assessments").fetchone() == (
0,
)
@@ -2489,10 +2365,7 @@ def test_workbench_normalizes_pre_release_migration_numbers(tmp_path: Path) -> N
connection.execute("UPDATE schema_migrations SET version = 2 WHERE version = -3")
connection.execute("UPDATE schema_migrations SET version = 3 WHERE version = -4")
connection.execute("UPDATE schema_migrations SET version = 4 WHERE version = -5")
connection.execute(
"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
(5, "scan target snapshot digests", "2026-06-01T00:00:00Z"),
)
record_migration(connection, 5, "scan target snapshot digests", "2026-06-01T00:00:00Z")
connection.execute("ALTER TABLE workspaces DROP COLUMN capability_preflight_json")
run_workbench(state_dir, "database-info")
@@ -2554,32 +2427,13 @@ def test_workbench_upgrades_public_cli_completion_warning_migration() -> None:
)
timestamp = "2026-07-01T00:00:00Z"
connection.execute(
"INSERT INTO workspaces (id, created_at, updated_at) VALUES (?, ?, ?)",
("legacy-workspace", timestamp, timestamp),
)
connection.execute(
"""
INSERT INTO scans (
id, workspace_id, target_path, target_revision, scope, mode, scan_dir,
status, phase, started_at, created_at, updated_at, completion_warnings_json
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
"legacy-scan",
"legacy-workspace",
"/legacy/target",
"legacy-revision",
".",
"standard",
"/legacy/scan",
"complete",
"reporting",
timestamp,
timestamp,
timestamp,
'["existing warning"]',
),
insert_historical_row(connection, "workspaces", timestamp, id="legacy-workspace")
insert_legacy_scan(
connection,
timestamp,
status="complete",
phase="reporting",
completion_warnings_json='["existing warning"]',
)
connection.commit()
@@ -2644,10 +2498,7 @@ def test_workbench_upgrades_legacy_execution_profile_migrations(
if migration_history == "canonical-metadata":
apply_historical_migrations(connection, migrations[10:24], timestamp)
connection.execute("ALTER TABLE scans ADD COLUMN model TEXT")
connection.execute(
"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
(25, "persist scan model settings", timestamp),
)
record_migration(connection, 25, "persist scan model settings", timestamp)
else:
legacy_migrations = [(11, "scan execution profiles", timestamp)]
if has_dynamic_profile_migration:
@@ -2675,13 +2526,11 @@ def test_workbench_upgrades_legacy_execution_profile_migrations(
connection.execute(
"ALTER TABLE scans ADD COLUMN completion_warnings_json TEXT NOT NULL DEFAULT '[]'"
)
connection.execute(
"INSERT INTO schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
(
26 if migration_history == "canonical-metadata" else 25,
"persist scan completion warnings",
timestamp,
),
record_migration(
connection,
26 if migration_history == "canonical-metadata" else 25,
"persist scan completion warnings",
timestamp,
)
workspace_id, scan_id = insert_legacy_profile_scan(
connection, tmp_path, model, reasoning_effort, timestamp
@@ -33,11 +33,13 @@ from workbench_test_support import (
saved_discovery_worker,
saved_draft,
scan_command,
select_checkpoint,
upsert_deep_worker,
worker_paths,
workspace_command,
write_checkpoint,
write_completed_contract,
write_result_draft,
)
scripts_dir = Path(__file__).resolve().parents[1] / "scripts"
@@ -80,7 +82,7 @@ def test_stopped_deep_scan_ignores_late_worker_checkpoints_without_reducer(
write_checkpoint(checkpoint_dir, revised)
head = max(checkpoint_dir.glob("*.json"))
latest_model = json.loads(head.read_text())["threatModel"]
(result_path.parent / "checkpoint-head.json").write_text(json.dumps({"checkpoint": head.name}))
select_checkpoint(result_path.parent, head)
# The latest incomplete attempt need not be parseable for a saved checkpoint to survive.
result_path.write_text("{incomplete")
with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
@@ -160,7 +162,7 @@ def test_stopped_model_selection_survives_publication_retry(
selected = (max if head_available else min)(checkpoint_dir.glob("*.json"))
head_path = result_path.parent / "checkpoint-head.json"
if head_available:
head_path.write_text(json.dumps({"checkpoint": selected.name}))
select_checkpoint(result_path.parent, selected)
if result_state != "unreadable":
stale = {**checkpoint, "threatModel": {"summary": "The earlier worker model."}}
result_path.write_text(json.dumps(stale))
@@ -234,7 +236,7 @@ def test_stopped_model_selection_survives_publication_retry(
checkpoint["threatModel"] = {"summary": "The later worker model."}
late = write_checkpoint(checkpoint_dir, checkpoint)
head_path.write_text(json.dumps({"checkpoint": late.name}))
select_checkpoint(result_path.parent, late)
environment = {"CODEX_HOME": str(codex_home)}
retried = preserve_scan_results(
state_dir, scan_id, "standard-worker-thread", environment=environment
@@ -1375,9 +1377,7 @@ def test_stopped_rejection_recovers_malformed_parent_surfaces(
"coverage": {**malformed_coverage, "surfaces": []},
},
)
head = scan_dir / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": parent_checkpoint.name}))
os.utime(head, ns=(200, 200))
select_checkpoint(scan_dir, parent_checkpoint, mtime_ns=200)
os.utime(scan_dir / "coverage.json", ns=(200, 200))
current = json.loads(result_path.read_text())
checkpoint = copy.deepcopy(current)
@@ -1508,8 +1508,7 @@ def test_complete_worker_model_uses_latest_terminal_source(
checkpoint["complete"] = True
checkpoint["threatModel"] = {"summary": "The revised completed worker model."}
head = write_checkpoint(result_path.parent / "checkpoints", checkpoint)
head_path = result_path.parent / "checkpoint-head.json"
head_path.write_text(json.dumps({"checkpoint": head.name}))
head_path = select_checkpoint(result_path.parent, head)
# Timestamp ordering represents an interruption between head and result publication,
# or a successfully replaced result whose older head remains available.
os.utime(result_path, ns=(2_000_000_000, 2_000_000_000))
@@ -1563,7 +1562,7 @@ def test_complete_worker_supersedes_obsolete_checkpoint_coverage(tmp_path: Path)
}
checkpoints = result_path.parent / "checkpoints"
head = write_checkpoint(checkpoints, checkpoint)
(result_path.parent / "checkpoint-head.json").write_text(json.dumps({"checkpoint": head.name}))
select_checkpoint(result_path.parent, head)
# This accepted checkpoint predates the successful result; a newer head reopens work.
for path in (head, result_path.parent / "checkpoint-head.json"):
@@ -2333,10 +2332,9 @@ def test_recovery_retains_generic_closures_without_a_canonical_write(
}
(scan_dir / "coverage.json").write_text(json.dumps(canonical_coverage))
os.utime(scan_dir / "coverage.json", ns=(100, 100))
original = write_checkpoint(scan_dir / "checkpoints", initial)
os.utime(original, ns=(100, 100))
original = write_checkpoint(scan_dir / "checkpoints", initial, mtime_ns=100)
original_bytes = original.read_bytes()
terminal = write_checkpoint(
write_checkpoint(
scan_dir / "checkpoints",
{
**initial,
@@ -2347,8 +2345,8 @@ def test_recovery_retains_generic_closures_without_a_canonical_write(
"resolvedDeferred": [closure],
},
},
mtime_ns=200,
)
os.utime(terminal, ns=(200, 200))
if canonical_state == "reopened":
os.utime(scan_dir / "coverage.json", ns=(300, 300))
if canonical_state == "checkpoint_reopened":
@@ -2416,11 +2414,10 @@ def test_recovered_generic_closure_cannot_close_another_workers_same_id(
draft = saved_draft(
scan_id, deferred=[{"id": "shared-review", "reason": f"Pending in {worker_id}."}]
)
pending = write_checkpoint(output / "checkpoints", draft)
os.utime(pending, ns=(100, 100))
write_checkpoint(output / "checkpoints", draft, mtime_ns=100)
if worker_id == "worker-one":
# Recover the accepted final checkpoint after an interrupted result write.
terminal = write_checkpoint(
write_checkpoint(
output / "checkpoints",
{
**draft,
@@ -2433,8 +2430,8 @@ def test_recovered_generic_closure_cannot_close_another_workers_same_id(
],
},
},
mtime_ns=closure_time,
)
os.utime(terminal, ns=(closure_time, closure_time))
else:
(output / "result.json").write_text(json.dumps(draft))
binding = saved_binding("deep_repository")
@@ -2485,7 +2482,7 @@ def test_recovery_keeps_latest_generic_closure_reason(tmp_path: Path, canonical_
(scan_dir / "findings.json").write_text(json.dumps({"findings": []}))
(scan_dir / "coverage.json").write_text(json.dumps(coverage))
os.utime(scan_dir / "coverage.json", ns=(canonical_time, canonical_time))
previous = write_checkpoint(
write_checkpoint(
scan_dir / "checkpoints",
{
"scanId": scan_id,
@@ -2496,8 +2493,8 @@ def test_recovery_keeps_latest_generic_closure_reason(tmp_path: Path, canonical_
"resolvedDeferred": [{**closure, "reason": "Initial review completed."}],
},
},
mtime_ns=200,
)
os.utime(previous, ns=(200, 200))
binding = saved_binding()
result = workbench_saved_results.merge_saved_results(
scan_dir, scan_id, binding, [], [], stopped=True, reason="interrupted"
@@ -2525,8 +2522,7 @@ def test_recovery_rejects_closures_that_would_discard_saved_evidence(
}
coverage = saved_coverage(deferred=[pending])
draft = {"scanId": scan_id, "complete": False, "findings": [], "coverage": coverage}
original = write_checkpoint(scan_dir / "checkpoints", draft)
os.utime(original, ns=(100, 100))
original = write_checkpoint(scan_dir / "checkpoints", draft, mtime_ns=100)
original_bytes = original.read_bytes()
closure = {"id": pending["id"], "reason": "Review closed."}
closures = [closure]
@@ -2536,7 +2532,7 @@ def test_recovery_rejects_closures_that_would_discard_saved_evidence(
closures.append({"id": "another-review", "reason": "Done.", "evidence": "Invalid field."})
elif case == "duplicate_closures":
closures.append(dict(closure))
terminal = write_checkpoint(
write_checkpoint(
scan_dir / "checkpoints",
{
**draft,
@@ -2547,8 +2543,8 @@ def test_recovery_rejects_closures_that_would_discard_saved_evidence(
"resolvedDeferred": closures,
},
},
mtime_ns=200,
)
os.utime(terminal, ns=(200, 200))
binding = {
"scanId": scan_id,
"startedAt": "2026-01-01T00:00:00Z",
@@ -2605,7 +2601,7 @@ def test_recovery_restores_work_reopened_after_parent_closure(
(scan_dir / "coverage.json").write_text(json.dumps(coverage))
os.utime(scan_dir / "coverage.json", ns=(100, 100))
pending = {"id": closure["id"], "reason": "New source evidence needs review."}
reopened = write_checkpoint(
write_checkpoint(
scan_dir / "checkpoints",
{
"scanId": scan_id,
@@ -2617,8 +2613,8 @@ def test_recovery_restores_work_reopened_after_parent_closure(
"resolvedDeferred": [],
},
},
mtime_ns=200,
)
os.utime(reopened, ns=(200, 200))
binding = saved_binding()
documents = workbench_saved_results.merge_saved_results(
scan_dir, scan_id, binding, [], [], stopped=True, reason="interrupted"
@@ -2660,23 +2656,18 @@ def test_recovery_uses_frozen_worker_head_for_identical_reclosure(
"resolvedDeferred": [{"id": pending["id"], "reason": "Review completed."}],
},
},
mtime_ns=100,
)
os.utime(closed, ns=(100, 100))
reopened = write_checkpoint(attempt / "checkpoints", draft)
os.utime(reopened, ns=(200, 200))
(attempt / "result.json").write_text(json.dumps(draft))
os.utime(attempt / "result.json", ns=(200, 200))
head = attempt / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": closed.name}))
os.utime(head, ns=(300, 300))
reopened = write_checkpoint(attempt / "checkpoints", draft, mtime_ns=200)
write_result_draft(attempt / "result.json", draft, mtime_ns=200)
select_checkpoint(attempt, closed, mtime_ns=300)
if layout != "current":
current = (
draft
if layout.endswith("attempt_reopens")
else {**draft, "coverage": {**coverage, "deferred": []}}
)
(output / "result.json").write_text(json.dumps(current))
os.utime(output / "result.json", ns=(300, 300))
write_result_draft(output / "result.json", current, mtime_ns=300)
workers = [saved_discovery_worker(output, "worker-one", 1 if layout == "current" else 2)]
if layout == "legacy_attempt_reopens":
workers[0]["attempt"] = 0
@@ -2702,8 +2693,7 @@ def test_recovery_uses_frozen_worker_head_for_identical_reclosure(
assert replay is not None
assert replay[2] == documents[2]
for checkpoint in (reopened, closed):
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(400, 400))
select_checkpoint(attempt, checkpoint, mtime_ns=400)
replay = workbench_saved_results.merge_saved_results(
scan_dir,
scan_id,
@@ -2717,7 +2707,7 @@ def test_recovery_uses_frozen_worker_head_for_identical_reclosure(
assert replay is not None
assert replay[2] == documents[2]
# Legacy frozen evidence did not bind a head; a later head cannot change its result.
head.write_text(json.dumps({"checkpoint": closed.name}))
select_checkpoint(attempt, closed)
legacy = workbench_saved_results.merge_saved_results(
scan_dir,
scan_id,
@@ -2750,15 +2740,11 @@ def test_recovery_keeps_worker_pending_saved_before_head_update(
"resolvedDeferred": [{"id": "review-closeout", "reason": "Initial review completed."}],
}
draft = {"scanId": scan_id, "complete": True, "findings": [], "coverage": coverage}
closed = write_checkpoint(output / "checkpoints", draft)
os.utime(closed, ns=(100, 100))
(output / "result.json").write_text(json.dumps(draft))
os.utime(output / "result.json", ns=(200, 200))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": closed.name}))
os.utime(head, ns=(200, 200))
closed = write_checkpoint(output / "checkpoints", draft, mtime_ns=100)
write_result_draft(output / "result.json", draft, mtime_ns=200)
select_checkpoint(output, closed, mtime_ns=200)
pending = {"id": "review-closeout", "reason": "New evidence needs review."}
reopened = write_checkpoint(
write_checkpoint(
output / "checkpoints",
{
**draft,
@@ -2768,8 +2754,8 @@ def test_recovery_keeps_worker_pending_saved_before_head_update(
"resolvedDeferred": [],
},
},
mtime_ns=pending_modified,
)
os.utime(reopened, ns=(pending_modified, pending_modified))
workers = [saved_discovery_worker(output, "worker-one", 1)]
binding = saved_binding("deep_repository")
documents = workbench_saved_results.merge_saved_results(
@@ -2832,8 +2818,7 @@ def test_frozen_parent_retains_identical_latest_observation(
original.parent.mkdir()
original.write_bytes(payload)
os.utime(original, ns=(100, 100))
checkpoint = write_checkpoint(original.parent, middle)
os.utime(checkpoint, ns=(200, 200))
write_checkpoint(original.parent, middle, mtime_ns=200)
write_saved_parent(tmp_path, latest, 300)
first = module.merge_saved_results(
tmp_path, pending["scanId"], binding, [], [], stopped=True, reason="interrupted"
@@ -2897,19 +2882,16 @@ def test_recovery_applies_surface_update_with_generic_closure(
output.mkdir(exist_ok=True)
workers = []
if layout.startswith("worker"):
(output / "result.json").write_text(json.dumps(pending))
os.utime(output / "result.json", ns=(100, 100))
write_result_draft(output / "result.json", pending, mtime_ns=100)
workers = [saved_discovery_worker(output, "worker", 1)]
else:
pending["complete"] = layout in {"terminal_parent", "reopened_parent"}
write_saved_parent(tmp_path, pending, 100)
checkpoint = write_checkpoint(output / "checkpoints", pending)
os.utime(checkpoint, ns=(100, 100))
write_checkpoint(output / "checkpoints", pending, mtime_ns=100)
terminal_draft = copy.deepcopy(closed)
if layout == "mixed_manifest":
terminal_draft["coverage"]["surfaces"][0].pop("receiptRefs")
terminal = write_checkpoint(output / "checkpoints", terminal_draft)
os.utime(terminal, ns=(200, 200))
write_checkpoint(output / "checkpoints", terminal_draft, mtime_ns=200)
if layout == "worker_idless_other_surface":
other = copy.deepcopy(pending)
other["coverage"]["surfaces"] = [
@@ -2917,8 +2899,7 @@ def test_recovery_applies_surface_update_with_generic_closure(
]
remaining = {"id": "other-review", "reason": "Independent review remains."}
other["coverage"]["deferred"] = [remaining]
checkpoint = write_checkpoint(output / "checkpoints", other)
os.utime(checkpoint, ns=(300, 300))
write_checkpoint(output / "checkpoints", other, mtime_ns=300)
if layout == "mixed_manifest":
canonical = {**closed, "complete": False}
write_saved_parent(tmp_path, canonical, 300)
@@ -2964,8 +2945,7 @@ def test_reopened_candidate_respects_current_outcome(
if candidate_identity == "alias":
candidate["id"] = "pending-review"
for draft, modified in ((closed, 100), (pending, 200)):
checkpoint = write_checkpoint(tmp_path / "checkpoints", draft)
os.utime(checkpoint, ns=(modified, modified))
write_checkpoint(tmp_path / "checkpoints", draft, mtime_ns=modified)
terminal = copy.deepcopy(closed)
terminal["coverage"].pop("resolvedDeferred")
terminal["coverage"]["surfaces"] = [
@@ -3046,11 +3026,8 @@ def test_worker_closure_preserves_ambiguous_legacy_surface_ids(
original = write_checkpoint(output / "checkpoints", pending)
for path in (result_path, original):
os.utime(path, ns=(100, 100))
terminal = write_checkpoint(output / "checkpoints", closed)
os.utime(terminal, ns=(200, 200))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": terminal.name}))
os.utime(head, ns=(200, 200))
terminal = write_checkpoint(output / "checkpoints", closed, mtime_ns=200)
head = select_checkpoint(output, terminal, mtime_ns=200)
original_bytes = {path: path.read_bytes() for path in (result_path, original, terminal, head)}
workers = [saved_discovery_worker(output, "worker", 1)]
@@ -3082,11 +3059,9 @@ def test_parent_closure_cannot_discard_reopened_worker_same_id(
write_saved_parent(tmp_path, closed, 300)
output = tmp_path / "worker"
output.mkdir()
(output / "result.json").write_text(json.dumps(closed))
os.utime(output / "result.json", ns=(100, 100))
write_result_draft(output / "result.json", closed, mtime_ns=100)
for draft, modified in ((closed, 100), (pending, 200)):
checkpoint = write_checkpoint(output / "checkpoints", draft)
os.utime(checkpoint, ns=(modified, modified))
write_checkpoint(output / "checkpoints", draft, mtime_ns=modified)
workers = [saved_discovery_worker(output, "worker", 1)]
first = module.merge_saved_results(
tmp_path, pending["scanId"], binding, workers, [], stopped=True, reason="interrupted"
@@ -3100,13 +3075,11 @@ def test_parent_head_preserves_newer_and_frozen_observations(
tmp_path: Path, generic_review_recovery, layout: str
) -> None:
module, pending, closed, binding = generic_review_recovery
closed_checkpoint = write_checkpoint(tmp_path / "checkpoints", closed)
os.utime(closed_checkpoint, ns=(100, 100))
pending_checkpoint = write_checkpoint(tmp_path / "checkpoints", pending)
os.utime(pending_checkpoint, ns=(300, 300))
closed_checkpoint = write_checkpoint(tmp_path / "checkpoints", closed, mtime_ns=100)
pending_checkpoint = write_checkpoint(tmp_path / "checkpoints", pending, mtime_ns=300)
head = tmp_path / "checkpoint-head.json"
selected = pending_checkpoint if layout == "newer_head" else closed_checkpoint
head.write_text(json.dumps({"checkpoint": selected.name}))
select_checkpoint(tmp_path, selected)
head_time = 400 if layout == "newer_head" else 200
os.utime(head, ns=(head_time, head_time))
original_head = head.read_bytes()
@@ -3167,8 +3140,7 @@ def test_generic_surface_recovery_preserves_unresolved_evidence(
pending["coverage"]["deferred"][0].pop("surfaceIds")
closed["coverage"]["surfaces"] = [{**old_surface, "disposition": "no_issue_found"}]
for draft, modified in ((pending, 100), (closed, 200)):
checkpoint = write_checkpoint(tmp_path / "checkpoints", draft)
os.utime(checkpoint, ns=(modified, modified))
write_checkpoint(tmp_path / "checkpoints", draft, mtime_ns=modified)
latest = copy.deepcopy(closed)
latest["coverage"]["surfaces"] = [old_surface]
workers = []
@@ -3195,8 +3167,7 @@ def test_generic_surface_recovery_preserves_unresolved_evidence(
(output / "result.json").write_text(json.dumps(latest))
workers = [saved_discovery_worker(output, "worker", 1)]
if later != "other_worker":
checkpoint = write_checkpoint(tmp_path / "checkpoints", latest)
os.utime(checkpoint, ns=(300, 300))
write_checkpoint(tmp_path / "checkpoints", latest, mtime_ns=300)
result = module.merge_saved_results(
tmp_path, pending["scanId"], binding, workers, [], stopped=True, reason="interrupted"
)
@@ -3233,10 +3204,8 @@ def test_worker_head_candidate_outcome_respects_newer_pending(
candidate["id"] = "pending-review"
observations = [(closed, 100)] if prior_closure else []
for draft, modified in [*observations, (pending, pending_time)]:
checkpoint = write_checkpoint(output / "checkpoints", draft)
os.utime(checkpoint, ns=(modified, modified))
(output / "result.json").write_text(json.dumps(pending))
os.utime(output / "result.json", ns=(200, 200))
write_checkpoint(output / "checkpoints", draft, mtime_ns=modified)
write_result_draft(output / "result.json", pending, mtime_ns=200)
terminal = copy.deepcopy(closed)
terminal["coverage"].pop("resolvedDeferred")
terminal["coverage"]["surfaces"] = [
@@ -3248,11 +3217,8 @@ def test_worker_head_candidate_outcome_respects_newer_pending(
"receiptRefs": [],
}
]
selected = write_checkpoint(output / "checkpoints", terminal)
os.utime(selected, ns=(150, 150))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
os.utime(head, ns=(300, 300))
selected = write_checkpoint(output / "checkpoints", terminal, mtime_ns=150)
select_checkpoint(output, selected, mtime_ns=300)
workers = [saved_discovery_worker(output, "worker", 1)]
first = module.merge_saved_results(
tmp_path, pending["scanId"], binding, workers, [], stopped=True, reason="interrupted"
@@ -3276,8 +3242,7 @@ def test_frozen_parent_keeps_unrelated_candidate_outcome(
"reason": "Validation remains.",
}
pending["coverage"]["deferred"].append(candidate)
checkpoint = write_checkpoint(tmp_path / "checkpoints", pending)
os.utime(checkpoint, ns=(100, 100))
write_checkpoint(tmp_path / "checkpoints", pending, mtime_ns=100)
closed["coverage"]["surfaces"] = [
{
"id": "candidate-outcome",
@@ -3321,11 +3286,8 @@ def test_equal_time_parent_and_head_preserve_pending_on_replay(
old.parent.mkdir()
old.write_bytes(payload)
os.utime(old, ns=(100, 100))
checkpoint = write_checkpoint(old.parent, previous)
os.utime(checkpoint, ns=(100, 100))
head = tmp_path / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(200, 200))
checkpoint = write_checkpoint(old.parent, previous, mtime_ns=100)
select_checkpoint(tmp_path, checkpoint, mtime_ns=200)
write_saved_parent(tmp_path, canonical, 200)
first = module.merge_saved_results(
tmp_path, pending["scanId"], binding, [], [], stopped=True, reason="interrupted"
@@ -3375,10 +3337,8 @@ def test_selected_candidate_outcome_keeps_its_evidence(
]
observations = [(closed, 100)] if prior_closure else []
for draft, modified in [*observations, (pending, 200)]:
checkpoint = write_checkpoint(output / "checkpoints", draft)
os.utime(checkpoint, ns=(modified, modified))
(output / "result.json").write_text(json.dumps(pending))
os.utime(output / "result.json", ns=(200, 200))
write_checkpoint(output / "checkpoints", draft, mtime_ns=modified)
write_result_draft(output / "result.json", pending, mtime_ns=200)
terminal = copy.deepcopy(closed)
terminal["coverage"].pop("resolvedDeferred")
rejection = {
@@ -3407,11 +3367,8 @@ def test_selected_candidate_outcome_keeps_its_evidence(
other_finding["extensions"]["candidateId"] = "other-candidate"
other_finding["identity"]["anchor"] = "another-entry-point"
terminal["findings"] = [finding, other_finding]
selected = write_checkpoint(output / "checkpoints", terminal)
os.utime(selected, ns=(300, 300))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
os.utime(head, ns=(300, 300))
selected = write_checkpoint(output / "checkpoints", terminal, mtime_ns=300)
select_checkpoint(output, selected, mtime_ns=300)
workers = [saved_discovery_worker(output, "worker", 1)]
if not stopped:
parent = copy.deepcopy(closed)
@@ -3452,14 +3409,10 @@ def test_interrupted_worker_reopening_preserves_candidate_identity(
pending["coverage"]["deferred"].append(
{**candidate, "id": "other-pending-review", "reason": "Another caller remains."}
)
(output / "result.json").write_text(json.dumps(closed))
os.utime(output / "result.json", ns=(100, 100))
write_result_draft(output / "result.json", closed, mtime_ns=100)
for draft, modified in ((closed, 100), (pending, 200)):
checkpoint = write_checkpoint(output / "checkpoints", draft)
os.utime(checkpoint, ns=(modified, modified))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
os.utime(head, ns=(200, 200))
checkpoint = write_checkpoint(output / "checkpoints", draft, mtime_ns=modified)
select_checkpoint(output, checkpoint, mtime_ns=200)
workers = [saved_discovery_worker(output, "worker", 1)]
result = module.merge_saved_results(
tmp_path, pending["scanId"], binding, workers, [], stopped=True, reason="interrupted"
@@ -1,7 +1,6 @@
from __future__ import annotations
import json
import os
import uuid
from pathlib import Path
@@ -18,9 +17,11 @@ from workbench_test_support import (
preserve_scan_results,
read_review_state,
saved_draft,
select_checkpoint,
upsert_deep_worker,
worker_paths,
write_checkpoint,
write_result_draft,
)
@@ -256,10 +257,11 @@ def test_pending_worker_surface_receipt_precedes_historical_receipt_repair(tmp_p
"receiptRefs": ["artifacts/other.md"],
}
task = {"id": "review-api", "reason": "Review remains.", "surfaceIds": ["api"]}
result.write_text(
json.dumps(saved_draft(scan_id, complete=True, surfaces=[surface, writer], deferred=[task]))
write_result_draft(
result,
saved_draft(scan_id, complete=True, surfaces=[surface, writer], deferred=[task]),
mtime_ns=100,
)
os.utime(result, ns=(100, 100))
historical = write_checkpoint(
output / "checkpoints",
saved_draft(
@@ -272,15 +274,14 @@ def test_pending_worker_surface_receipt_precedes_historical_receipt_repair(tmp_p
}
],
),
mtime_ns=50,
)
os.utime(historical, ns=(50, 50))
selected = write_checkpoint(
output / "checkpoints", saved_draft(scan_id, complete=True, surfaces=[writer])
output / "checkpoints",
saved_draft(scan_id, complete=True, surfaces=[writer]),
mtime_ns=300,
)
os.utime(selected, ns=(300, 300))
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
os.utime(head, ns=(400, 400))
head = select_checkpoint(output, selected, mtime_ns=400)
originals = {
path: path.read_bytes()
for path in (result, historical, selected, head, current_receipt, historical_receipt)
@@ -88,6 +88,28 @@ def junction_factory(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyP
return create
def write_reviewed_patch(
tmp_path: Path, source: Path, patch: bytes, revision: str = "unversioned"
) -> dict[str, object]:
scan_dir = tmp_path / "scan"
scan_dir.mkdir(mode=0o700)
(scan_dir / "reviewed.patch").write_bytes(patch)
return {
"target_path": str(source),
"target_inode": source.stat().st_ino,
"target_revision": revision,
"scan_dir": str(scan_dir),
}
def reviewed_remediation(patch: bytes, revision: str, digest: str) -> dict[str, str]:
return {
"base_revision": revision,
"base_content_digest": digest,
"patch_digest": "sha256:" + hashlib.sha256(patch).hexdigest(),
}
@pytest.mark.parametrize(
("git_repository", "git_exclusion"),
[
@@ -145,24 +167,14 @@ def test_reviewed_patch_preserves_junction_boundaries(
if change != "target_populated":
(outside / "source.txt").write_text("original contents\n")
junction_factory(junction, outside)
scan_dir = tmp_path / "scan"
scan_dir.mkdir(mode=0o700)
patch = b"diff --git a/app.txt b/app.txt\n--- a/app.txt\n+++ b/app.txt\n@@ -1 +1 @@\n-before\n+after\n"
(scan_dir / "reviewed.patch").write_bytes(patch)
scan = {
"target_path": str(source),
"target_inode": source.stat().st_ino,
"target_revision": "unversioned",
"scan_dir": str(scan_dir),
}
scan = write_reviewed_patch(tmp_path, source, patch)
(source / "app.txt").write_text("before\n")
if git_repository == "indexed":
subprocess.run(["git", "add", "."], cwd=source, check=True)
remediation = {
"base_revision": "unversioned",
"base_content_digest": workbench_db.directory_content_digest(source),
"patch_digest": "sha256:" + hashlib.sha256(patch).hexdigest(),
}
remediation = reviewed_remediation(
patch, "unversioned", workbench_db.directory_content_digest(source)
)
(source / "app.txt").write_text("after\n")
if change in {"junction_target", "same_content_target"}:
junction_target = tmp_path / "other"
@@ -346,21 +358,11 @@ def test_reviewed_patch_does_not_copy_through_indexed_directory_links(
(sentinel / "file.txt").write_text("staged outside sentinel\n")
# A relative link resolves to this different directory after materialization.
monkeypatch.setattr(workbench_db.tempfile, "tempdir", str(staging))
scan_dir = tmp_path / "scan"
scan_dir.mkdir(mode=0o700)
patch = b"diff --git a/app.txt b/app.txt\n--- a/app.txt\n+++ b/app.txt\n@@ -1 +1 @@\n-before\n+after\n"
(scan_dir / "reviewed.patch").write_bytes(patch)
scan = {
"target_path": str(source),
"target_inode": source.stat().st_ino,
"target_revision": revision,
"scan_dir": str(scan_dir),
}
remediation = {
"base_revision": revision,
"base_content_digest": workbench_db.worktree_content_digest(source),
"patch_digest": "sha256:" + hashlib.sha256(patch).hexdigest(),
}
scan = write_reviewed_patch(tmp_path, source, patch, revision)
remediation = reviewed_remediation(
patch, revision, workbench_db.worktree_content_digest(source)
)
(source / "app.txt").write_text("after\n")
if unrelated_change:
(source / "unrelated.txt").write_text("outside the reviewed patch\n")
@@ -485,22 +487,10 @@ def assert_reviewed_change(
)
)
).encode()
scan_dir = tmp_path / "scan"
scan_dir.mkdir(mode=0o700)
(scan_dir / "reviewed.patch").write_bytes(patch)
scan = {
"target_path": str(source),
"target_inode": source.stat().st_ino,
"target_revision": revision,
"scan_dir": str(scan_dir),
}
scan = write_reviewed_patch(tmp_path, source, patch, revision)
(source / relative).write_text(before, newline=newline)
revision, digest = workbench_db.remediation_checkout_snapshot(scan)
remediation = {
"base_revision": revision,
"base_content_digest": digest,
"patch_digest": "sha256:" + hashlib.sha256(patch).hexdigest(),
}
remediation = reviewed_remediation(patch, revision, digest)
(source / relative).write_text(after, newline=newline)
assert workbench_db.require_reviewed_patch_applied(scan, remediation, "reviewed.patch")
@@ -575,21 +565,9 @@ def test_reverse_patch_cannot_write_through_junction(
(outside / "keep.txt").write_text("outside contents\n")
junction = source / "linked"
junction_factory(junction, outside)
scan_dir = tmp_path / "scan"
scan_dir.mkdir(mode=0o700)
patch = b"diff --git a/linked/deleted.txt b/linked/deleted.txt\ndeleted file mode 100644\n--- a/linked/deleted.txt\n+++ /dev/null\n@@ -1 +0,0 @@\n-removed\n"
(scan_dir / "reviewed.patch").write_bytes(patch)
scan = {
"target_path": str(source),
"target_inode": source.stat().st_ino,
"target_revision": "unversioned",
"scan_dir": str(scan_dir),
}
remediation = {
"base_revision": "unversioned",
"base_content_digest": "different base",
"patch_digest": "sha256:" + hashlib.sha256(patch).hexdigest(),
}
scan = write_reviewed_patch(tmp_path, source, patch)
remediation = reviewed_remediation(patch, "unversioned", "different base")
with pytest.raises(OSError):
workbench_db.require_reviewed_patch_applied(scan, remediation, "reviewed.patch")
assert sorted(path.name for path in outside.iterdir()) == ["keep.txt"]
@@ -618,8 +596,6 @@ def test_reverse_patch_cannot_redirect_junction_restoration(
config = tmp_path / "gitconfig"
config.write_text("[core]\n\tsymlinks = true\n")
monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(config))
scan_dir = tmp_path / "scan"
scan_dir.mkdir(mode=0o700)
patch = f"""diff --git a/app.txt b/app.txt
--- a/app.txt
+++ b/app.txt
@@ -641,19 +617,11 @@ index {"0" * 40}..{"1" * 40}
@@ -0,0 +1 @@
+Subproject commit {"1" * 40}
""".encode()
(scan_dir / "reviewed.patch").write_bytes(patch)
scan = {
"target_path": str(source),
"target_inode": source.stat().st_ino,
"target_revision": "unversioned",
"scan_dir": str(scan_dir),
}
scan = write_reviewed_patch(tmp_path, source, patch)
(source / "app.txt").write_text("before\n")
remediation = {
"base_revision": "unversioned",
"base_content_digest": workbench_db.directory_content_digest(source),
"patch_digest": "sha256:" + hashlib.sha256(patch).hexdigest(),
}
remediation = reviewed_remediation(
patch, "unversioned", workbench_db.directory_content_digest(source)
)
(source / "app.txt").write_text("after\n")
try:
with pytest.raises(SystemExit, match="checkout path was replaced"):
@@ -794,26 +762,14 @@ def test_reviewed_patch_preserves_unborn_git_inventory(tmp_path: Path, change: s
cached_file = cache / "output.txt"
cached_file.write_text("ignored build output\n")
subprocess.run(["git", "add", ".gitignore", "src/app.txt"], cwd=source, check=True)
scan_dir = tmp_path / "scan"
scan_dir.mkdir(mode=0o700)
patch = (
b"diff --git a/src/app.txt b/src/app.txt\n"
b"--- a/src/app.txt\n+++ b/src/app.txt\n@@ -1 +1 @@\n-before\n+after\n"
)
(scan_dir / "reviewed.patch").write_bytes(patch)
scan = {
"target_path": str(source),
"target_inode": source.stat().st_ino,
"target_revision": "unversioned",
"scan_dir": str(scan_dir),
}
scan = write_reviewed_patch(tmp_path, source, patch)
revision, digest = workbench_db.remediation_checkout_snapshot(scan)
assert revision == "unversioned"
remediation = {
"base_revision": revision,
"base_content_digest": digest,
"patch_digest": "sha256:" + hashlib.sha256(patch).hexdigest(),
}
remediation = reviewed_remediation(patch, revision, digest)
app.write_text("after\n")
if change == "ignored_file":
cached_file.write_text("updated ignored build output\n")
@@ -8,12 +8,16 @@ from argparse import Namespace
from pathlib import Path
import pytest
from test_deep_scan_successful_publication import add_worker
from test_deep_scan_successful_publication import publication_scan as publication_scan
from test_partial_coverage_projection import stop_and_recover_projection
from test_partial_coverage_projection import stop_scan as stop_scan
from test_saved_deferred_identity import recover, save_worker
from workbench_test_support import read_review_state, saved_draft, write_checkpoint
from workbench_test_support import (
read_review_state,
saved_draft,
select_checkpoint,
write_checkpoint,
)
@pytest.mark.parametrize("reordered", [False, True])
@@ -37,8 +41,7 @@ def test_unselected_pending_checkpoint_links_to_accepted_worker_surface(
output = tmp_path / "reviewer"
result_path = output / "result.json"
selected = write_checkpoint(output / "checkpoints", accepted)
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": selected.name}))
head = select_checkpoint(output, selected)
for path in (selected, result_path, head):
os.utime(path, ns=(1_000_000_000, 1_000_000_000))
pending = copy.deepcopy(accepted)
@@ -50,8 +53,7 @@ def test_unselected_pending_checkpoint_links_to_accepted_worker_surface(
pending["coverage"]["deferred"] = [
{"id": "task", "reason": "Check boundary", "surfaceIds": ["api"]}
]
unselected = write_checkpoint(output / "checkpoints", pending)
os.utime(unselected, ns=(2_000_000_000, 2_000_000_000))
write_checkpoint(output / "checkpoints", pending, mtime_ns=2_000_000_000)
originals = {path: path.read_bytes() for path in output.rglob("*.json")}
worker.update(status="succeeded", result_manifest_path=str(result_path))
recovered = recover(tmp_path, saved, [worker])
@@ -71,7 +73,7 @@ def test_stopped_receipt_ownership_requires_a_matching_checkpoint(
workbench_api, workbench_db, publication_scan, stop_scan, recorded, retry, archived
):
scan = publication_scan()
initial = add_worker(workbench_db, scan)
initial = scan.add_worker()
worker_id = initial.parent.name
output = scan.scan_dir / "artifacts" / "deep_discovery" / "workers" / worker_id / "output"
output.mkdir(parents=True)
@@ -209,7 +211,7 @@ def test_legacy_file_scope_preserves_shared_receipts_when_stopped(
draft["scanId"] = scan.scan_id
draft["findings"][0]["locations"][0]["path"] = scope
legacy["checkpoint"]["findings"][1]["locations"][0]["path"] = f"{scope}/generated"
initial = add_worker(workbench_db, scan)
initial = scan.add_worker()
worker_id = initial.parent.name
output = scan.scan_dir / "artifacts" / "deep_discovery" / "workers" / worker_id / "output"
output.mkdir(parents=True)
@@ -220,8 +222,9 @@ def test_legacy_file_scope_preserves_shared_receipts_when_stopped(
(str(output), str(result), worker_id),
)
result.write_text(json.dumps(legacy["result"]))
checkpoint = write_checkpoint(result.parent / "checkpoints", legacy["checkpoint"])
os.utime(checkpoint, ns=(1_000_000_000, 1_000_000_000))
checkpoint = write_checkpoint(
result.parent / "checkpoints", legacy["checkpoint"], mtime_ns=1_000_000_000
)
os.utime(result, ns=(2_000_000_000, 2_000_000_000))
ref = "artifacts/evidence.txt"
shared, local = scan.scan_dir / ref, result.parent / ref
@@ -13,6 +13,7 @@ import sys
import tempfile
import uuid
from contextlib import nullcontext
from dataclasses import dataclass, field
from pathlib import Path
from types import ModuleType
from typing import Any
@@ -118,14 +119,29 @@ def source_plugin_version() -> str:
return version
def write_checkpoint(checkpoint_dir: Path, payload: Any) -> Path:
def write_checkpoint(checkpoint_dir: Path, payload: Any, *, mtime_ns: int | None = None) -> Path:
encoded = json.dumps(payload).encode()
checkpoint_dir.mkdir(parents=True, exist_ok=True)
checkpoint_path = checkpoint_dir / f"{hashlib.sha256(encoded).hexdigest()}.json"
checkpoint_path.write_bytes(encoded)
if mtime_ns is not None:
os.utime(checkpoint_path, ns=(mtime_ns, mtime_ns))
return checkpoint_path
def select_checkpoint(output: Path, checkpoint: Path, *, mtime_ns: int | None = None) -> Path:
head = output / "checkpoint-head.json"
head.write_text(json.dumps({"checkpoint": checkpoint.name}))
if mtime_ns is not None:
os.utime(head, ns=(mtime_ns, mtime_ns))
return head
def write_result_draft(path: Path, draft: dict, *, mtime_ns: int) -> None:
path.write_text(json.dumps(draft))
os.utime(path, ns=(mtime_ns, mtime_ns))
def sort_checkpoint_entries(monkeypatch, *, key=None, reverse=False):
from workbench import saved_sources
@@ -500,80 +516,83 @@ def write_remediation_patch(patch_path: Path, **text_options: Any) -> None:
)
def request_remediation(
state_dir: Path,
occurrence_id: str,
request_id: str,
action_token: str,
*,
check: bool = True,
) -> dict[str, object]:
return run_workbench(
state_dir,
"request-finding-remediation",
"--occurrence-id",
occurrence_id,
"--request-id",
request_id,
"--action-token",
action_token,
check=check,
)
@dataclass(frozen=True)
class RemediationRequest:
state_dir: Path
occurrence_id: str
id: str = field(default_factory=lambda: str(uuid.uuid4()))
def _run(self, command: str, *args: str, check: bool = True) -> dict[str, object]:
return run_workbench(
self.state_dir,
command,
"--occurrence-id",
self.occurrence_id,
"--request-id",
self.id,
*args,
check=check,
)
def set_remediation(
state_dir: Path,
occurrence_id: str,
request_id: str,
action_token: str,
expected_version: str,
state: str,
*extra: str,
check: bool = True,
) -> dict[str, object]:
return run_workbench(
state_dir,
"set-finding-remediation",
"--occurrence-id",
occurrence_id,
"--request-id",
request_id,
"--action-token",
action_token,
"--expected-version",
expected_version,
"--state",
state,
*extra,
check=check,
)
def start(self, token: str, *, check: bool = True) -> dict[str, object]:
return self._run("request-finding-remediation", "--action-token", token, check=check)
def update(
self, token: str, version: str, state: str, *args: str, check: bool = True
) -> dict[str, object]:
return self._run(
"set-finding-remediation",
"--action-token",
token,
"--expected-version",
version,
"--state",
state,
*args,
check=check,
)
def request_remediation_action(
state_dir: Path,
occurrence_id: str,
request_id: str,
expected_version: str,
action: str,
action_token: str,
*,
check: bool = True,
) -> dict[str, object]:
return run_workbench(
state_dir,
"request-finding-remediation-action",
"--occurrence-id",
occurrence_id,
"--request-id",
request_id,
"--expected-version",
expected_version,
"--action",
action,
"--action-token",
action_token,
check=check,
)
def generate(
self, token: str, patch: Path, *args: str, check: bool = True
) -> dict[str, object]:
digest = hashlib.sha256(patch.read_bytes()).hexdigest()
return self.update(
token,
"1",
"generated",
"--patch-path",
patch.name,
"--patch-digest",
f"sha256:{digest}",
*args,
check=check,
)
def request_action(
self, version: str, action: str, token: str, *, check: bool = True
) -> dict[str, object]:
return self._run(
"request-finding-remediation-action",
"--expected-version",
version,
"--action",
action,
"--action-token",
token,
check=check,
)
def claim_resend(self, token: str, *, check: bool = True) -> dict[str, object]:
return self._run("claim-finding-remediation-resend", "--action-token", token, check=check)
def cancel(self, token: str) -> dict[str, object]:
return self._run("cancel-finding-remediation-request", "--action-token", token)
def mark_delivered(self, token: str) -> dict[str, object]:
return self._run("mark-finding-remediation-delivered", "--action-token", token)
def release_claim(self, token: str) -> dict[str, object]:
return self._run("release-finding-remediation-claim", "--action-token", token)
def save_workspace(
@@ -625,63 +644,6 @@ def update_progress(
)
def claim_remediation_resend(
state_dir: Path,
occurrence_id: str,
request_id: str,
action_token: str,
*,
check: bool = True,
) -> dict[str, object]:
return run_workbench(
state_dir,
"claim-finding-remediation-resend",
"--occurrence-id",
occurrence_id,
"--request-id",
request_id,
"--action-token",
action_token,
check=check,
)
def cancel_remediation_request(
state_dir: Path,
occurrence_id: str,
request_id: str,
action_token: str,
) -> dict[str, object]:
return run_workbench(
state_dir,
"cancel-finding-remediation-request",
"--occurrence-id",
occurrence_id,
"--request-id",
request_id,
"--action-token",
action_token,
)
def mark_remediation_delivered(
state_dir: Path,
occurrence_id: str,
request_id: str,
action_token: str,
) -> dict[str, object]:
return run_workbench(
state_dir,
"mark-finding-remediation-delivered",
"--occurrence-id",
occurrence_id,
"--request-id",
request_id,
"--action-token",
action_token,
)
def fail_deep_scan(state_dir, codex_home, scan_id, *, message="Worker stopped.", deep_status=None):
return scan_command(
state_dir,
@@ -696,28 +658,27 @@ def fail_deep_scan(state_dir, codex_home, scan_id, *, message="Worker stopped.",
def start_delivered_scan(
state_dir: Path,
workspace_id: str,
*args: str,
environment: dict[str, str] | None = None,
) -> dict[str, object]:
"""Prepare an unclaimed, delivered scan for tests outside handoff ownership."""
started = run_workbench(state_dir, "start-scan", *args, environment=environment)
scan = started["results"]
scan = start_scan_command(state_dir, workspace_id, *args, environment=environment)["results"]
with sqlite3.connect(state_dir / "workbench.sqlite3") as connection:
connection.execute(
"UPDATE scans SET handoff_status = 'delivered' WHERE id = ?", (scan["scanId"],)
)
scan["handoffStatus"] = "delivered"
return started
return scan
def start_workspace_scan(state_dir: Path, workspace_id: str, scan_root: Path) -> tuple[str, Path]:
started = start_delivered_scan(
state_dir,
"--workspace-id",
workspace_id,
"--scan-root",
str(scan_root),
)["results"]
)
return str(started["scanId"]), Path(str(started["scanDir"]))
@@ -831,6 +792,14 @@ def mark_deep_coordinator_succeeded(state_dir: Path, scan_id: str, scan_dir: Pat
return manifest
def read_draft_documents(scan_dir: Path) -> dict:
return {
"manifest": json.loads((scan_dir / "scan-manifest.json").read_text()),
"findings": json.loads((scan_dir / "findings.json").read_text()),
"coverage": json.loads((scan_dir / "coverage.json").read_text()),
}
def write_completed_contract(
scan_dir: Path,
scan_id: str,
+12 -73
View File
@@ -11,9 +11,8 @@ security plugin, and TypeScript declarations. It uses ES modules.
- Review saved findings, identify duplicates, classify severity, and suggest owners.
- Import GitHub code scanning alerts, export SARIF, JSON, or CSV, and publish
findings to Linear or a findings service.
- Import [Snyk Open Source findings](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/snyk.md) from
official plugin JSON or native CLI JSON locally or into Cloud; Open Source
SARIF is also supported. License findings and other Snyk products are excluded.
- Import saved scanner reports locally or publish them to Codex Security Cloud.
See the [scanner import guides](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md) for supported vendors and formats.
- Automate scans across repositories and project components.
See the [CLI reference](docs/cli.md),
@@ -658,10 +657,12 @@ contributors. Suggestions do not assign tickets. See
`publish scan --to cloud` uploads selected findings to Codex Security Cloud.
It requires ChatGPT credentials; inference API keys and AWS credentials do not
grant Cloud access. See [Cloud publication](docs/cli.md#publish-findings-to-cloud)
grant Cloud access. See [Cloud publication](docs/cli.md#publish-completed-scans)
for setup and review steps, or [Linear publication](docs/cli.md#publish-completed-scans-to-linear)
for issue creation.
### Import external findings
External vendor imports are opt-in. Set `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1`
to enable `publish findings`, `findings imported`, `import sonar`, `import github-advisories`, and
the SDK's external publication, local import/readback, Sonar issue collection, and advisory acquisition
@@ -673,6 +674,8 @@ Omit `issueKeys` to collect the project's open security issues. An empty list is
If you know the source repository, pass its Git URL in `options.sourceRepositoryUrl`
to check the Sonar binding before fetching issues.
Pure normalizers and file readers remain available.
Use `normalizeSelectedSemgrepPlatformFindings` for selected SAST findings from saved
Semgrep Web API responses. See the [Semgrep SDK example](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md#import-selected-semgrep-platform-sast-findings-with-the-sdk).
This does not affect scan publishing or the existing GitHub alert collector.
The SDK also exposes `prepareExternalPublication(file, options)` for supported
@@ -684,70 +687,8 @@ use `ExternalPublicationOptions` for their supported formats. Both resolve the C
calling `publish()`. Imported evidence remains not assessed by Codex, and saved
requests and receipts support retries after interruption.
Prefer each provider's supported native JSON for local and Cloud imports. Keep
the same acquisition format for repeat imports: SARIF and CSV are compatibility
options where supported, and changing formats can change record identities or
replace richer evidence with less detail. See the
[import guide](docs/cli.md#import-vendor-findings-locally) for format selection.
For SonarQube Cloud, `codex-security import sonar` reads open security issues
through the signed-in Sonar CLI. You can pass exact issue keys from the
SonarQube plugin for Codex and save a local capture for later Cloud publication.
See the [Sonar import commands](docs/cli.md#import-sonarqube-cloud-issues).
For Amazon Inspector Code Security, use `--provider inspector` with a complete
ListFindings JSON export and `--source-repository-url`. When the export identifies
the repository by an ARN and name, pass `--inspector-project-arn ARN` with the ARN
you verified for that Git URL in the SCM integration. See the
[Inspector guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/inspector.md).
For Black Duck SCA, use `--provider blackduck` with a BOM-6 vulnerable-components
export for one project version. Map that version to its source repository with
`--source-repository-url`. See the
[Black Duck guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/blackduck.md).
For Veracode Static Analysis policy findings, use `--provider veracode` with
every Findings API page from one application. Set `--source-repository-url`
to the source repository mapped to that application. See the
[Veracode guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/veracode.md).
For OpenGrep, use `--provider opengrep` with native JSON or gzip and an explicit
`--source-repository-url`. Local and Cloud imports retain unassessed OpenGrep
evidence through the existing Semgrep source-provider contract. See the
[OpenGrep guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/opengrep.md) for preview commands,
coverage diagnostics, stable source identities, and local SDK assessment.
For Wiz, prefer supported native JSON acquired through an authorized MCP or API
connection. The [CSV compatibility reader](docs/cli.md#import-wiz-findings) covers
repository package vulnerabilities (SCA) only; it does not add SAST, CSPM or
complete code-to-cloud coverage. Both formats support gzip. The acquisition path
still needs validation with an authorized Wiz tenant.
For GitHub code scanning and GHSA advisories, save complete JSON from
`import github` or `import github-advisories`, respectively. **GHSA import
does not establish an installed dependency or applicability to the repository.**
For Dependabot, save the native REST alert records from one repository using the
[Dependabot export guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/github-dependabot.md).
The GitHub file reader accepts all three families. Secret-scanning alerts and
writeback to GitHub are outside its scope.
Use `publish findings FILE --to local --repository PATH --provider wiz
--source-key KEY` to store the same vendor evidence in the local workbench SQLite
database. Preview with `--dry-run --format json`, then confirm interactively or
use `--yes`. Read it with `findings imported [REPOSITORY] --format json`; the
repository defaults to the current directory. No Cloud login or model call is
needed. Use `--provider snyk` for native CLI JSON, a Snyk plugin SCA bundle or
Open Source SARIF. Prefer JSON, and keep one format and stable source key per scan
target; switching formats creates separate source identities. See
[local imports](docs/cli.md#import-vendor-findings-locally).
Use `--provider endor` with native Endor Finding JSON; existing endorctl SARIF is
accepted as a lossy compatibility format. See
[Endor imports](docs/cli.md#import-endor-labs-findings).
For saved GitHub code-scanning alerts, GHSA advisories, or Dependabot alerts, use
`--provider github` with a separate stable source key for each finding family.
See [local imports](docs/cli.md#import-vendor-findings-locally).
For CLI examples and supported input formats, see the
[scanner import guides](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md).
The SDK's `prepareLocalExternalImport(file, options)` returns a `preview` and a
separate `import()` operation. `prepareNormalizedLocalImport(findings,
@@ -757,9 +698,9 @@ remain unassessed source evidence, separate from native scan findings. Repeated
imports update the same repository/provider/source-key/source-ID record; omitted
records remain stored, and unknown evidence fields are not inferred.
File imports forward repository references from the reader automatically. Direct
normalized callers should provide additional known references in the third
argument's `sourceRepositories` when they are absent from
File imports forward repository references from the reader automatically. With
`prepareNormalizedLocalImport()`, supply additional known references in the
third argument's `sourceRepositories` when they are absent from
`evidence.details.repository.url`. For a known GitHub custom host, include
`platform: "github"`, for example `{ sourceRepositories: [{ url:
"https://git.example.test/example/project", platform: "github" }] }`. Named Wiz
@@ -767,8 +708,6 @@ reports carry this platform in their repository inventory. If you export only th
normalized finding rows to JSONL, supply that metadata separately; the original
finding evidence does not include the surrounding inventory.
See [Semgrep Code imports](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md) for native CLI/CI JSON, SARIF compatibility, and local or Cloud imports. Platform API and Guardian/MCP responses need a separate mapping.
## Findings storage and deduplication
Saved-scan deduplication uses local SQLite directly:
+170 -481
View File
@@ -1283,307 +1283,143 @@ Supply the validation prompt again when rerunning.
## Import vendor findings locally
Use the [scanner file import schema and capability guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/schema-guide.md) to compare provider identities, mapped evidence and destination behavior before selecting a report.
Choose an input in the [scanner import guides](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md).
Each guide shows how to preview its input for a local repository. Follow the [shared procedure](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md#save-or-publish-and-verify)
to confirm the import and read the resulting records.
External finding imports are disabled by default. Opt in for the current shell:
Set `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1` to enable `publish findings`,
`findings imported`, `import sonar`, and `import github-advisories`. Only `1`
enables these commands in help and schemas. The SDK's corresponding operations
require the flag in their effective environment. Pure normalizers, file readers,
and the existing `import github` alert collector remain available independently.
Disabling the flag retains saved records.
```bash
export CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1
```
For `publish findings`, `--to` is required. With `--to local`, `--repository`
takes a checkout path. The reader detects the file format, and `--format json`
selects the output format. A local preview writes no findings and needs no Cloud
login, network connection, or model call.
In PowerShell, use `$env:CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS = '1'`.
Only `1` enables the feature. Without it, `publish findings`, `findings imported`,
`import sonar`, and `import github-advisories` are absent from command help and schemas and cannot
run. The SDK's external publication, local import/readback, and advisory
acquisition APIs require the same flag in their effective environment. An explicit
`dependencies.environment` is used instead of the process environment. Pure
normalizers and file readers remain available as library utilities.
Local readback uses `findings imported [PATH]`. The path defaults to the current
directory. Each imported record starts as `not_assessed`. Unknown revisions and
locations stay unknown. Repository-scoped sources are checked against comparable
configured Git remotes as described in the provider guide. Reimporting the same
source key and finding ID reports created, updated, or unchanged records.
Records omitted from the new selection stay stored. An import with exclusions
exits with status 1. Local imports can retain evidence that exceeds Cloud's per-finding limits.
This flag does not affect `publish scan`, `publish check`, `scan import`, or the
existing `import github` alert collector. Disabling it retains previously imported
records; enable it again to read them with `findings imported`.
Prefer the provider's supported native JSON from its CLI, plugin, or API. Native
reports can retain details omitted by SARIF. Use SARIF or CSV as compatibility
inputs only for providers and report profiles that support them. A JSON API
summary is not automatically a supported report; follow the provider's acquisition
instructions and retain the original records. The readers detect supported input
formats; `--format json` selects command output, not the input format.
Keep the acquisition format consistent across imports. Depending on the provider,
switching formats can create separate records for the same vulnerability or
replace a richer evidence snapshot with less detail. The importer does not merge
evidence or deduplicate equivalent vulnerabilities across different source IDs.
Use the same vendor input and parser as Cloud publication, selecting a local
repository path instead of a Cloud repository ID or URL. Supported inputs include
Wiz findings, [Snyk Open Source JSON and SARIF](#import-snyk-open-source-findings),
[Endor Labs Finding JSON and SARIF](#import-endor-labs-findings),
[Amazon Inspector repository findings](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/inspector.md),
[Black Duck SCA project-version vulnerabilities](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/blackduck.md),
[Veracode Static Analysis policy findings](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/veracode.md),
[Semgrep Code JSON and SARIF](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/semgrep.md),
[SonarQube Cloud issue-search pages](#import-sonarqube-cloud-issues),
[OpenGrep native JSON](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/opengrep.md),
[GitHub Dependabot repository alerts](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/github-dependabot.md),
and [saved GitHub code-scanning alerts and GHSA advisories](#import-github-findings-locally-or-to-cloud):
```bash
codex-security publish findings selected-wiz.json \
--to local --repository ./project --provider wiz \
--source-key TENANT_ID/vulnerability-finding --dry-run --format json
```
Review the normalized evidence, repository, source namespace, and exclusions.
Run the same command without `--dry-run` to confirm interactively, or add `--yes`
after reviewing the preview. `--to` is required; there is no default destination.
Local import uses the workbench SQLite database and requires no Cloud login,
network connection, or model call. `--dry-run` does not write findings.
Read the saved evidence with:
```bash
codex-security findings imported ./project --format json
```
The repository argument defaults to the current directory. Local imports are
separate from the assessed findings shown by `findings list`: they remain
`not_assessed`, retain the original vendor evidence, and do not create a completed
scan or automatically validate or patch findings. Missing revisions, locations,
and assessment fields stay unknown. When the source includes a repository URL and the local checkout has configured
Git remotes, the URL must match one of those remotes; the importer does not
substitute the checkout's current commit for an unknown scanner revision.
Repeated imports update the same record by repository, provider, source key, and
source finding ID. The result reports created, updated, and unchanged counts.
Keep the source key stable across exports. Records omitted from a later selection
remain stored; omission does not resolve or delete a finding. Excluded records
are reported, and an import with exclusions exits with status 1. Both destinations
read the same vendor formats; Cloud's field, size and nesting limits do not apply
to local file imports.
For OpenGrep, use `--provider opengrep` and supply `--source-repository-url`.
The reader supports native JSON and gzip for both destinations. It uses the
existing `semgrep` source-provider contract while retaining `OpenGrep` as the
scanner origin; keep a stable OpenGrep-specific source key. Review report
diagnostics as well as findings: import completion does not establish scan
coverage. The [OpenGrep guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/opengrep.md)
covers evidence identity, empty reports, and assessing an imported finding with
the existing SDK validator.
`scan import --json` and `scan import --csv` remain separate commands for importing
Codex Security's findings schema as a saved scan; they do not accept vendor
exports.
For completed scans exported in the Codex Security JSON or CSV format, use
[scan import](#import-findings-as-a-saved-scan).
## Import Endor Labs findings
For local or Cloud import, prefer complete native Finding JSON from authenticated
`endorctl`, scoped to one project and context. Omit `--field-mask` and use
`--list-all` to finish pagination:
```sh
endorctl api list --resource Finding --namespace "YOUR_NAMESPACE" \
--filter 'context.type==CONTEXT_TYPE_MAIN and spec.project_uuid=="PROJECT_UUID"' \
--list-all --output-type json > endor-findings.json
codex-security publish findings endor-findings.json --to local \
--provider endor --repository ./project \
--source-key "YOUR_NAMESPACE/PROJECT_UUID/main" --dry-run
```
Replace the example namespace, project UUID and local repository with your selection.
Review the preview, remove `--dry-run` to confirm, then read the stored evidence
with `codex-security findings imported ./project --format json`. To publish to
Cloud instead, use `--to cloud --repository "CLOUD_REPOSITORY_ID"` with the same
file, provider and source key. The official
[Endor Labs Agent Kit for Codex](https://github.com/endorlabs/ai-plugins/tree/main/plugins/codex/endor-labs-agent-kit)
can help with setup and investigation, but summaries, counts and field-masked
results do not replace complete Finding objects. `endorctl` reads the Endor API;
the importer reads the saved export without maintaining an API connection or
writing changes back to Endor.
Native JSON retains severity, package and advisory data, primary SAST/AI SAST
locations and the scanned commit. Existing self-contained endorctl SARIF 2.1.0
reports are a lossy compatibility format, retaining finding links and UUIDs;
unavailable severity and revisions stay unknown. Both formats use the Endor UUID
within the selected repository and stable source key as identity. Importing SARIF
after native JSON for that UUID updates the same record by replacing its evidence
snapshot, not merging it. Native detail absent from SARIF is removed from the
snapshot. Use native JSON consistently for ongoing imports.
Local and Cloud records remain unassessed source evidence. Local imports use the
SQLite readback described above; Cloud imports use the login, preview,
confirmation and retry flow below.
Use `--provider endor` for one Endor project and context. The
[Endor Labs guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/endor.md) covers native Finding JSON,
SARIF compatibility, and the local preview.
## Publish findings to Cloud
Use the [scanner import guides](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md) to prepare a supported input
and follow the [shared publication steps](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/README.md#save-or-publish-and-verify)
to preview and confirm it. The following settings and result fields apply to
scanner publication across providers.
### Preview and publish
With `--to cloud`, `--repository` accepts a connected GitHub or GitHub Enterprise
repository URL or Cloud repository ID. A unique URL and its ID resolve to the
same destination and saved submission. Use the ID if several connectors share
the URL. Use a file-backed ChatGPT login for the selected Cloud
account. If you use your regular Codex login, set `cli_auth_credentials_store = "file"`
in Codex `config.toml` and sign in again. API-key-only and keyring-only logins
cannot publish. The destination needs an authorized environment. It can receive
scanner findings before its first native scan.
Cloud preview reads current source versions and lists the account, endpoint,
repository, and environments. Existing source records keep their environment.
New records use the repository's current authorized default. The terminal
summarizes severities, shows up to five finding IDs and titles, and identifies
the evidence file and exclusions. Inspect the full preview with `--dry-run --format json`.
The interactive confirmation defaults to No and identifies skipped records.
Without a terminal, uploading requires `--yes`.
### Configure an alternate Cloud deployment
Set `CODEX_SECURITY_CLOUD_BASE_URL` to the deployment's API root, such as
`https://cloud.example.test/backend-api/aardvark`. Use a login issued by that
deployment. Remote API roots require HTTPS. Loopback development also accepts
HTTP on `localhost`, `127.0.0.0/8`, or `::1`. An empty or invalid setting
stops preparation before authentication or network requests. Leaving it unset
selects production. For testing, use an isolated `CODEX_SECURITY_STATE_DIR`.
For a separately hosted Cloud UI, set `CODEX_SECURITY_CLOUD_WEB_URL` to the
full app URL. The preview and result can then supply a repository-specific
`cloudUrl`. With a custom API and no web URL, the CLI prints navigation
instructions. API requests always use the API root. The older
`CODEX_SECURITY_CLOUD_PUBLISH_URL` setting applies only to native scan publishing.
### Resume interrupted imports
The publisher saves request IDs and bodies privately in the configured state
directory before uploading batches of up to 100 findings within Cloud payload
limits. After a lost response, use the same input, destination, account, API
endpoint, and state directory to resume. Deployments have separate checkpoints
even if their account and repository IDs match. Check `cloudApiUrl` for the API
endpoint and `savedSubmission` for the checkpoint. A repository reset retires
the old request and requires a fresh preview and approval.
[Retry a Cloud submission](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/schema-guide.md#retry-a-cloud-submission)
### Results and exit codes
| Status | Exit code | Meaning |
| ------------- | --------- | ----------------------------------------------------------------------- |
| `complete` | 0 | All selected records were acknowledged and read back. |
| `partial` | 1 | Some records were excluded locally or rejected by Cloud. |
| `interrupted` | 2 | Upload, verification, or receipt persistence stopped after preparation. |
| `failed` | 2 | Preparation failed before upload. |
With `--format json` or `--format jsonl`, add `--full-output` for an envelope.
Failed and interrupted imports set `ok` to `false` and `error.code` to
`IMPORT_FAILED`. Available results, receipts, and counts remain under `data`.
Other formats reject `--full-output` before reading the file or contacting
Cloud. Ctrl-C and SIGTERM retain exit codes 130 and 143.
`verified` and `unacknowledged` are counts. Each receipt item identifies a
request item by `client_id`. Each entry in `failures` identifies the vendor
record by `source_finding_id`. A lost response can leave accepted records
unacknowledged. Review `error` before retrying, and check `excluded` for local
input errors. Counts include previously acknowledged batches in the same
saved submission.
Progress goes to stderr and JSON results to stdout. Lookups and readback use up
to four concurrent requests. Uploads are sequential. Saved receipts and
readback verify source-record identity and evidence. Codex assessment and
visibility in the shared Cloud Findings view are separate. `cloudUrl`, when
available, links to the destination repository in Cloud.
### Import Snyk Open Source findings
Import **Open Source SCA vulnerabilities only**. Licenses, Code, Container, IaC,
SBOM results and platform backlog ingestion are outside this adapter.
Use the [official Snyk Codex plugin](https://github.com/snyk/studio-recipes/tree/main/plugins/codex)
with its `snyk-findings-export` skill to collect SCA findings from the repository's
Git root. It runs a fresh local scan and writes a `snyk-findings-export/v1` bundle;
it does not retrieve existing platform project findings.
The same saved bundle supports [local import](#import-vendor-findings-locally)
without a Cloud login:
```sh
codex-security publish findings snyk-findings.json --to local \
--provider snyk --repository ./project \
--source-key github.com/example/project/main/root/plugin-sca --dry-run
```
Or preview publication to a connected Cloud repository:
```sh
codex-security publish findings snyk-findings.json --to cloud \
--provider snyk --repository https://github.com/example/project \
--source-key github.com/example/project/main/root/plugin-sca --dry-run
```
Check the collection's scan outcomes and limitations. Only Open Source SCA
vulnerabilities are imported; other products and licenses are explicit exclusions.
The importer retains the selected finding, native MCP record and collection
context. MCP may shorten descriptions and omit dependency paths. Plugin paths
remain in original evidence because v1 lacks their offset from the Git root.
For automation, prefer native JSON from
`snyk test --file=package.json --json-file-output=snyk.json`. Exit 1 means findings;
stop on other nonzero exits before importing. The existing `--provider snyk`
autodetects a single project object or an `--all-projects` array; any project error
stops the import. Use default ungrouped output, without `--group-issues`.
Native JSON preserves individual dependency paths and remediation fields. Its
paths remain original evidence because it does not establish their Git-root offset.
Open Source SARIF from `snyk test --sarif-file-output=snyk.sarif` remains supported
for compatibility. Its target-relative manifest paths and synthetic line numbers
remain original evidence, without being projected as repository locations or
package manifest paths. All three formats accept either destination. Use a consistent
format and stable source key per repository, branch and scan target, for example
`github.com/example/project/main/root/native-sca` for native JSON. Their source
identities differ: use separate keys when switching acquisition formats. Imports
do not deduplicate across formats or remove earlier imported records.
Known repository claims must
match the selected Cloud repository or, when available, a configured local Git
remote. Unknown repository context still requires selecting the correct target;
the importer does not infer provenance from the current checkout.
Remove `--dry-run` from the selected command to review and confirm the import, or
use `--yes` after reviewing the preview. Read local records with
`codex-security findings imported ./project --format json`. Imported source
evidence is not a Codex assessment. No Snyk-side triage state is changed. See the
[Snyk import guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/snyk.md) for format limits and
acquisition details.
Use `--provider snyk` for Open Source SCA vulnerabilities. Native CLI JSON, plugin
exports, and Open Source SARIF can produce different occurrence IDs. Use a
separate source key for each format. See the [Snyk guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/snyk.md) for
collection and preview commands.
### Import Wiz findings
Import selected Wiz package vulnerabilities, SAST findings, repository secrets,
and IaC findings without creating a scan. Imported records retain vendor evidence
and remain **not assessed by Codex**, including when Wiz marks them resolved or
reports an AI verdict. Workload secrets, cloud configuration findings, and external
network findings are not supported by this repository importer. Cloud destinations
currently support connected GitHub and GitHub Enterprise repositories, including
custom Enterprise hostnames. Named Wiz exports do not add other VCS destinations.
The [Wiz guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/wiz.md) shows how to preview saved package vulnerabilities,
SAST findings, repository secrets, or IaC findings. The format reference below
describes the fields to preserve when preparing those exports.
#### Select findings and a destination
Use an authorized [Wiz MCP](https://www.wiz.io/blog/introducing-wiz-mcp) or Wiz API
connection to acquire findings and save the supported native JSON. A configured
plugin may provide that connection; an official Codex plugin is not a prerequisite.
The publisher reads the saved records. It does not fetch from Wiz or require a
manual website download. The acquisition path still needs validation against
actual responses from an authorized Wiz tenant; local parser checks do not
establish that qualification.
Acquire selected findings through an authorized Wiz connection and save the
complete native response. The publisher reads the saved file. MCP summaries,
Wiz Issues, and local Wiz CLI scan results may have different shapes. Verify
the selected response against the format for its finding family. Acquisition
against a live Wiz tenant requires separate qualification.
Inspect the connection's actual response before importing it. MCP summaries,
Wiz Issues, and local Wiz CLI scan results are not automatically compatible with
this finding mapper. Keep the original occurrence IDs and evidence; use the
named collections below when the response contains repository findings.
Before the first import:
1. Select an existing repository in Codex Security Cloud and copy its URL or
Cloud repository ID. The repository needs an
authorized environment, but does not need a completed native scan.
2. Read the selected records through the authorized connection and save their
JSON. For **package vulnerabilities**, include `id`, `name`, `detailedName`,
`vendorSeverity` (or `severity`), and `vulnerableAsset.id`; retain available
package, image, and source metadata. For SAST, repository secrets, and IaC,
retain the named API collections and repository metadata described below.
Complete the selected pages before importing; a summary or unfinished page
is not a complete finding selection.
3. Choose a stable source key such as `TENANT_ID/vulnerability-finding`. Reuse it
for that Wiz tenant and finding class across exports. Do not create a new key
for each project filter or import; that creates different source identities.
4. Check the ChatGPT account used by your existing file-backed Codex Security
login. API-key-only and keyring-only logins are not supported for Cloud
publication. See the credential-storage instructions below.
Prefer the supported native JSON. Existing package-vulnerability CSV reports are
accepted as a compatibility input. **CSV support covers repository package
vulnerabilities (SCA) only; it does not add SAST, cloud posture (CSPM), or complete
Wiz code-to-cloud coverage.** The named JSON readers described below handle their
respective finding families separately.
When a UI report is needed, retain the repository and finding filters in Wiz
**Vulnerability Findings**, choose **Save as → Report**, select **Repository
Branch**, **JSON** or **CSV**, and **Detailed** columns, then download the completed
report. CSV must use the columns described below and a comma delimiter. Plain and
gzip-compressed JSON or CSV are accepted; gzip is detected regardless of the
filename extension. **Raw Event** on Code & Build Scans contains scan metadata
rather than findings.
#### Configure an alternate Cloud deployment
For an alternate Cloud deployment, set `CODEX_SECURITY_CLOUD_BASE_URL` to its
API root before previewing or uploading, for example
`https://cloud.example.test/backend-api/aardvark`. Remote APIs require HTTPS;
HTTP is accepted only for loopback development (`localhost`, `127.0.0.0/8`, or
`::1`). Use a login issued by that deployment and an isolated
`CODEX_SECURITY_STATE_DIR` for testing. The endpoint
does not change your login or sign you into another deployment. An invalid or
empty configured URL stops the import before authentication or network requests.
With the variable unset, the existing production endpoint remains the default.
The older `CODEX_SECURITY_CLOUD_PUBLISH_URL` overrides only the final native scan
publication endpoint; it does not route vendor imports.
If that deployment serves its UI separately, set `CODEX_SECURITY_CLOUD_WEB_URL`
to the full Cloud app URL shown in the browser. The import handoff supplies both
deployment settings. The preview and result include a repository-specific
`cloudUrl`, and terminal completion prints the link. This setting only controls
the return link; all API requests still use `CODEX_SECURITY_CLOUD_BASE_URL`.
For custom API destinations without a configured app URL, completion retains
the manual navigation guidance rather than guessing a UI host or port.
#### Preview and publish
Preview the selection and destination:
```bash
codex-security publish findings selected-wiz.json \
--to cloud --repository https://github.com/example/project --provider wiz \
--source-key TENANT_ID/vulnerability-finding --dry-run --format json
```
`--repository` accepts the repository's URL or ID. Both resolve to the same Cloud
destination and resume the same saved submission. This command reads the
authorized destination and current source versions during
preview. It uses the same saved ChatGPT file login as scan publication. The Cloud
repository needs an existing environment; no native scan is required. Review the
Cloud API endpoint, account, repository, environments, findings, and exclusions,
then rerun without
`--dry-run`. The default terminal prompt is No; `--yes` confirms a previously
reviewed input for scripts or the plugin. Without a terminal or `--yes`, no upload
occurs. Existing source findings keep their Cloud environment; new findings use
the repository’s current authorized default. Preview shows the environments that
will receive the selected findings. The terminal preview summarizes severities,
shows up to five finding IDs and titles, and identifies the evidence file and
exclusions. `--dry-run --format json` retains all normalized findings and complete
evidence for inspection. A prompt explicitly includes any records that will be
skipped.
For saved reports, use the detailed repository package vulnerability export
shown in the Wiz guide. Raw Event on Code & Build Scans contains scan
metadata. For other CSV exports, see [Convert CSV reports](#convert-csv-reports).
#### Package vulnerability inputs
@@ -1595,6 +1431,10 @@ A response that advertises another page is rejected. Complete the requested page
or save only the explicitly selected records; retain the named collection for
SAST, repository secrets, and IaC.
For native package records, include `id`, `name`, `detailedName`,
`vulnerableAsset.id`, and `vendorSeverity` or `severity`. Retain any available
package, image, and repository metadata.
The CSV mapper requires `ID`, `Name`, `DetailedName`, `AssetID`, `WizURL`,
`CloudPlatform`, and `CloudProviderURL`. Check the actual report headers against
this profile; other Wiz report types use different fields.
@@ -1743,56 +1583,6 @@ Inputs must be valid UTF-8. Integer-valued evidence outside JavaScript's safe
integer range is rejected; export those values as strings to preserve them
exactly. Invalid records appear in `excluded` with their source ID and reason.
#### Resume interrupted imports
Requests contain at most 100 findings and respect the Cloud payload limits.
Before uploading, the publisher saves request IDs and bodies privately under
the configured Codex Security state directory. After an uncertain response,
repeat the same command with unchanged input and Cloud API endpoint to resume those
requests. Different deployments have separate saved submissions, including when
their account and repository IDs match. The preview and result include
`cloudApiUrl` so scripts can verify which API received the findings; this is an
API endpoint, not a link to the Cloud UI. A reset
retires the old request without republishing; review and explicitly approve a
fresh invocation.
#### Results and exit codes
Results distinguish completion from partial or interrupted work:
| Status | Exit code | Meaning |
| ------------- | --------- | -------------------------------------------------------------------------------------------------- |
| `complete` | 0 | All selected records were acknowledged and their source records read back. |
| `partial` | 1 | The import finished, but some records were excluded locally or rejected by Cloud. |
| `interrupted` | 2 | Upload, verification, or receipt persistence stopped; acknowledged work is included in the result. |
| `failed` | 2 | Preparation failed before uploading; structured output includes the error. |
For finding imports, `--full-output` requires `--format json` or `--format jsonl`.
Failed and interrupted imports set the envelope's `ok` to `false`, with
`error.code: "IMPORT_FAILED"`, while retaining available results, receipts, and
counts under `data`. Other full-output format combinations are rejected before
reading the input or contacting Cloud; omit `--full-output` to use those formats.
Ctrl-C and SIGTERM retain exit codes 130 and 143. Interrupted JSON output preserves
`receipts`, `counts`, `failures` with vendor source IDs, `excluded`, `verified`, and
`unacknowledged`. A lost response can mean unacknowledged findings were accepted;
resume the saved submission rather than treating them as never uploaded. When
available, `savedSubmission` identifies the checkpoint to resume by repeating the
same command. Review `error` before retrying; a repository reset retires the old
submission and requires fresh approval. Correct local exclusions or final source
conflicts before preparing a new submission.
Counts are cumulative for the saved submission: a resumed result includes
batches acknowledged by earlier invocations, not just the latest upload attempt.
Terminal progress reports preparation, acknowledged uploads, and verification
on stderr; JSON results stay on stdout. Lookups and readback use at most four
concurrent requests, while uploads remain sequential. Successful receipts are
saved locally. Verification reads the imported source records and checks their
identities and evidence against the receipts. This does not establish a Codex
assessment or visibility in the shared Cloud Findings view.
When available, `cloudUrl` links to the destination repository in Cloud.
### Publish completed scans
Preview selected completed scans before uploading:
@@ -2447,97 +2237,30 @@ installation fails. The installer respects `core.hooksPath`.
## Import SonarQube Cloud issues
Enable [external imports](#import-vendor-findings-locally) and run
`codex-security import sonar` from the project's checkout to import open
security issues from the active Sonar CLI connection. For issues selected in
the SonarQube plugin, pass each issue key with `--sonar-issue`, its project
with `--sonar-project`, and its branch or PR with `--sonar-branch` or
`--sonar-pull-request`. The plugin and terminal use the same Sonar login.
When you omit `--sonar-project`, Sonar must bind the checkout's Git origin to
one project in that login's organization.
```sh
codex-security import sonar --sonar-project example_project --sonar-branch main \
--sonar-issue ISSUE_A --sonar-issue ISSUE_B --dry-run --format json
codex-security import sonar "/path/from/capture.json" --yes
```
`--dry-run` saves the reviewed selection and returns its path in `capture`.
The default destination is the local workbench. For both local import and
Cloud publication, preview with `--to cloud` and confirm with the exact
`capture` path from the successful Cloud preview and `--to cloud --yes`.
If the checkout or Cloud destination changes, preview again. For a structured
success or error envelope, use `--full-output` with `--format json` or
`--format jsonl`. You can publish a local import later
without reconnecting to Sonar. See [Sonar import and replay](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/sonar.md)
for authentication, repository mapping, and native JSON input.
The [SonarQube Cloud guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/sonar.md) covers live collection, repository
binding, saved issue-search pages, and replay. Unlike a saved-file
`publish findings` preview, `import sonar --dry-run` writes a private capture
and returns its path. Confirm with the capture from the preview for the intended
destination. A Cloud confirmation imports the selected issues locally and
publishes them to Cloud. Use `--full-output` with `--format json` or
`--format jsonl` for a structured success or error envelope.
## Import GitHub findings locally or to Cloud
Local and Cloud ingestion require the [external-import opt-in](#import-vendor-findings-locally).
The existing alert collector remains available without it.
Choose the [code scanning](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/github-code-scanning.md),
[Dependabot](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/github-dependabot.md), or
[GitHub Security Advisories](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/github-security-advisories.md) guide to acquire
and preview findings. All three use `--provider github`. Keep a separate source
key for each family. Saving locally or publishing to Cloud requires the
[external-import opt-in](#import-vendor-findings-locally).
Acquire code-scanning findings with the existing `import github` collector and
save its complete JSON output. In Codex, the official
[GitHub Codex plugin](https://github.com/openai/plugins/tree/main/plugins/github)
can help select the repository, alert numbers and ref through GitHub's MCP
server. Pass that selection to the collector. For Dependabot, use a token with
**Dependabot alerts: read** and follow
the [repository alert export guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/github-dependabot.md)
to save the native REST records from one repository and preview them with
`--provider github`. For GHSA disclosures, use the
[advisory collector](#import-ghsa-advisories-separately).
The following example previews local storage of a code-scanning export.
```bash
codex-security import github example/project --format json > /path/outside/repository/alerts.json
codex-security publish findings /path/outside/repository/alerts.json \
--to local --provider github --repository ./project \
--source-key github.com/example/project/code-scanning --dry-run --format json
```
Or preview publication to a connected Cloud repository:
```bash
codex-security publish findings /path/outside/repository/alerts.json \
--to cloud --provider github --repository https://github.com/example/project \
--source-key github.com/example/project/code-scanning --dry-run --format json
```
The importer fetches every page, retrieves alert details, and retains the selected
ref's instance. It writes the saved input for publication; no website download or
hand-written JSON mapping is needed. Use `--github-alert NUMBER` repeatedly for
selected alerts or `--github-ref REF` for another ref. Defaults are open alerts on
the default branch. MCP list calls are paginated separately. Code-scanning
imports require the saved collector output, which includes the selected instance.
The importer uses GitHub CLI authentication (`gh auth login`) and `GH_HOST`;
the plugin's connection does not sign in `gh`. Reading code-scanning alerts requires
[code-scanning access](https://docs.github.com/en/rest/code-scanning/code-scanning#list-code-scanning-alerts-for-a-repository):
**Code scanning alerts: read** for a fine-grained token, or `security_events` for
a classic token (`public_repo` is sufficient for public repositories). The source
repository must have code scanning available. For Cloud publication, the
destination must be connected in the selected Cloud account. For local import,
the source repository must match a configured Git remote when remotes are
available; no Cloud login is required to store the acquired evidence.
Review the destination, source, exclusions and evidence in the preview. Repeat the
selected command without `--dry-run` and confirm it, or add `--yes` for a
previously reviewed input. Local persistence and readback follow the
[local import flow](#import-vendor-findings-locally); use
`codex-security findings imported ./project --format json` to read the records.
Cloud authentication, batching, saved receipts, partial results and
interrupted-upload recovery follow the [publication flow](#import-wiz-findings).
JSON, JSONL and gzip are supported. Save complete import output without field or
token filters or `--full-output`.
Use a stable source key for the GitHub host, repository and finding family.
Code-scanning identities include the selected ref, so branches retain separate
evidence. The original alert, rule, scanner, location, revision and source state
remain attached. An alert-wide dismissal takes precedence over the selected
instance's open/fixed state. Missing security severity stays `unknown`;
SARIF error/warning/note levels are not vulnerability ratings. Imported evidence
remains unassessed by Codex.
The code-scanning and advisory CLI collectors use `gh` to authenticate for
`GH_HOST` (default `github.com`). A GitHub
plugin connection can select alerts but does not sign the CLI in.
Collection retains the selected ref's instance. Branches keep separate
evidence. An alert-wide dismissal takes precedence over the selected instance's
open or fixed state. Missing security severity stays `unknown`. See
[code-scanning access requirements](https://docs.github.com/en/rest/code-scanning/code-scanning#list-code-scanning-alerts-for-a-repository).
The SDK offers the same preview and publication boundary for Cloud:
@@ -2552,7 +2275,7 @@ const alerts = await importGitHubCodeScanningAlerts({
repository: "example/project",
});
const prepared = await prepareNormalizedExternalPublication(
normalizeGitHubCodeScanningAlerts(alerts),
normalizeGitHubCodeScanningAlerts(alerts, "cloud"),
{
provider: "github",
repository: "https://github.com/example/project",
@@ -2564,73 +2287,37 @@ console.log(prepared.preview);
const receipt = await prepared.publish();
```
For local storage, pass the same normalized evidence to
`prepareNormalizedLocalImport()` with `repository: "/path/to/project"`, inspect
its preview, and call `import()`. `prepareLocalExternalImport()` accepts the saved
import file directly. Read records with `listLocalExternalFindings({ repository })`.
For local storage, call `normalizeGitHubCodeScanningAlerts(alerts, "local")` on
the original alerts to retain evidence that exceeds Cloud limits. Pass the result
to `prepareNormalizedLocalImport()` with `repository: "/path/to/project"`, inspect
its preview, and call `import()`. Alternatively, pass the saved alert file directly
to `prepareLocalExternalImport()`. Read records with `listLocalExternalFindings({ repository })`.
### Import GHSA advisories separately
Set `CODEX_SECURITY_ENABLE_EXTERNAL_IMPORTS=1` before using this command or its SDK API.
See the [GitHub Security Advisories guide](https://github.com/openai/codex-security/blob/main/docs/scanner-imports/github-security-advisories.md)
to save repository advisories or selected global database records and preview
them for the chosen destination. Advisories report affected ranges and
available fixes. Verify installed dependencies and applicability in the
destination repository separately.
**Importing a GHSA advisory does not establish an installed dependency or
applicability to the destination repository.** Repository advisories are
disclosures maintained by a repository; global advisories describe affected
software in GitHub's public advisory database. Both are evidence for
investigation, not Dependabot alerts. Check the repository’s dependency versions
and applicability separately.
Repository lists default to published advisories. When selecting exact IDs, omit
`--github-state`. Selecting a repository advisory by its GHSA ID can return a
draft if you have access.
Global collection requires one or more explicit IDs.
Acquisition failure yields no partial selection. Access to private or
unpublished repository advisories requires the repository advisory read
permission and access to the record. See
[GitHub repository advisory permissions](https://docs.github.com/en/rest/security-advisories/repository-advisories#list-repository-security-advisories).
```bash
# Read only published advisories for this repository.
codex-security import github-advisories example/project --format json > /path/outside/repository/advisories.json
# Select individual public database records without enumerating the database.
codex-security import github-advisories example/project \
--github-advisory-source global --github-advisory GHSA-2345-6789-cfgh \
--format json > /path/outside/repository/advisories.json
codex-security publish findings /path/outside/repository/advisories.json \
--to cloud --provider github --repository https://github.com/example/project \
--source-key github.com/example/project/security-advisories --dry-run --format json
```
For local storage, use the same advisory file, provider and source key with
`--to local --repository ./project`. Follow the [local import flow](#import-vendor-findings-locally)
to review, confirm and read the stored evidence.
`--github-advisory-source` defaults to `repository`. Repeat `--github-advisory`
to select exact IDs from that API, regardless of advisory state. Repository
lists default to `--github-state published`; `draft`, `triage`, and `closed`
require explicit selection. A nondefault state cannot be combined with exact
IDs. Global selection requires at least one ID and never lists the advisory
database. Both readers use `GH_HOST` and GitHub CLI authentication by default;
the SDK also accepts `githubHost` and `githubToken`. Private or unpublished
[repository advisories](https://docs.github.com/en/rest/security-advisories/repository-advisories#list-repository-security-advisories)
require **Repository security advisories: read**, or the classic `repo` or
`repository_advisories:read` scope, plus access to the advisory. Public records
need no additional advisory permission.
Review the saved evidence before local import or Cloud publication, including any
selected private advisories. Acquisition failure returns no partial selection.
Both destinations report invalid records as exclusions. Cloud publication retains
acknowledged receipts if a later batch or readback fails.
Advisory evidence retains GHSA/CVE IDs, affected version ranges, available
patched versions, source status and original JSON. It does not infer an installed
version or source location. Global advisories omit a source repository; the
explicit local or Cloud destination binds the import for investigation. Repository
advisories retain their source repository and check it against the Cloud target
or configured local Git remotes when available. Withdrawal remains vendor
state, and all imported evidence remains not assessed by Codex. Use a separate
source key from code-scanning alerts; shared advisory IDs do not combine source
records from different providers.
In the SDK, call `importGitHubAdvisories()` and `normalizeGitHubAdvisories()`
with `prepareNormalizedExternalPublication()` for Cloud or
`prepareNormalizedLocalImport()` for local storage as described above.
In the SDK, collect the advisories with `importGitHubAdvisories()`. For Cloud,
pass `normalizeGitHubAdvisories(advisories, "cloud")` to
`prepareNormalizedExternalPublication()`. For local storage, pass
`normalizeGitHubAdvisories(advisories, "local")` to `prepareNormalizedLocalImport()`.
`importGitHubAdvisories()` defaults to `{ source: "repository", state: "published" }`; use
`{ source: "global", advisoryIds: ["GHSA-2345-6789-cfgh"] }` for selected database
records. Both forms require `repository: "OWNER/REPO"` as source or target context.
Supply `githubHost` and `githubToken` to override the GitHub CLI login and host.
## Import alerts from the CLI
@@ -2661,6 +2348,7 @@ import {
const findings = await importGitHubCodeScanningAlerts({
repository: "example/repository",
alertNumbers: [12, 18], // Omit for all open alerts on the default branch.
githubHost: "github.com",
githubToken: process.env["GH_TOKEN"],
});
@@ -2679,8 +2367,9 @@ try {
```
SDK options include `state` (default `"open"`), `ref`, and `signal`.
Supply `githubToken` or use `gh auth token` credentials, including GitHub CLI
token environment variables. `githubHost` defaults to `GH_HOST` or `github.com`.
Without `gh`, pass a `githubToken` issued for the selected `githubHost`.
If you omit the token, the SDK asks the GitHub CLI for credentials, including
its supported token environment variables. `githubHost` defaults to `GH_HOST` or `github.com`.
The token needs code-scanning read access; access failures reject the import.
## Validate and patch findings
@@ -32,6 +32,7 @@ const distModules = [
"snyk-findings",
"scanner-repository-url",
"semgrep-findings",
"semgrep-platform-findings",
"sonar-findings",
"sonar-collector",
"sonar-import",
@@ -76,6 +77,7 @@ const distModules = [
"finding-catalogue",
"findings-import",
"git-remote",
"local-git-metadata",
"github",
"github-advisories",
"github-dependabot-findings",
+3 -15
View File
@@ -1,4 +1,3 @@
import { z } from "zod";
import { CodexSecurityError } from "./errors.js";
import type { Provider } from "./external-import-models.js";
import {
@@ -185,16 +184,6 @@ function projectReference(
};
}
const bomComponent = z.object(
{
vulnerabilityWithRemediation: z.custom<Record<string, unknown>>(
isRecord,
"Black Duck vulnerabilityWithRemediation must be an object.",
),
},
"Black Duck BOM component must be an object.",
);
function scopedRow(
value: unknown,
scope: string | undefined,
@@ -222,16 +211,15 @@ function scopedRow(
);
scope = reference.scope;
}
const component = bomComponent.safeParse(value);
const vulnerability = row["vulnerabilityWithRemediation"];
return {
row,
matched,
scope,
// Shape errors are row exclusions; project-scope errors abort the report.
get vulnerability() {
if (!component.success)
throw new Error(component.error.issues[0]!.message);
return component.data.vulnerabilityWithRemediation;
record(value, "Black Duck BOM component");
return record(vulnerability, "Black Duck vulnerabilityWithRemediation");
},
};
}
+7 -26
View File
@@ -5,13 +5,13 @@ import { isRecord } from "./record.js";
import {
array,
hasSarifExternalPropertyReferences,
indexSarifRules,
matchesSarifRuleReference,
normalizeRecords,
readScannerJson,
record,
relativePath,
requiredText,
sarifRunContextForResult,
sarifResultContext,
strings,
text,
} from "./scanner-import.js";
@@ -198,26 +198,15 @@ export function normalizeEndorSarif(
hasSarifExternalPropertyReferences(run["externalPropertyFileReferences"])
)
throw new Error("Use a self-contained Endor SARIF report.");
const rules = array(driver["rules"] ?? [], "Endor rules").map((r) =>
record(r, "Endor rule"),
);
const rulesById = indexSarifRules(rules);
const { runs: _runs, ...documentContext } = document;
const { results: _results, tool: _tool, ...runContext } = run;
const { rules: _rules, ...driverContext } = driver;
const { driver: _driver, ...toolContext } = tool;
const context = sarifResultContext(document, run, tool, driver, "Endor");
return array(run["results"] ?? [], "Endor results").map((result) => ({
result,
rulesById,
documentContext,
runContext,
driverContext,
toolContext,
...context,
}));
});
return normalizeRecords(
entries,
({ result: value, rulesById, ...context }) => {
({ result: value, rulesById, selectRunContext, ...context }) => {
const result = record(value, "Endor result");
const properties = record(
result["properties"],
@@ -238,14 +227,7 @@ export function normalizeEndorSarif(
throw new Error("Endor ruleIndex and ruleId disagree.");
if (result["rule"] !== undefined) {
const reference = record(result["rule"], "Endor rule reference");
if (
reference["toolComponent"] !== undefined ||
(reference["id"] !== undefined && reference["id"] !== ruleId) ||
(reference["index"] !== undefined &&
reference["index"] !== ruleIndex) ||
(reference["guid"] !== undefined &&
reference["guid"] !== rule["guid"])
)
if (!matchesSarifRuleReference(reference, ruleId, selectedRule))
throw new Error("Inconsistent or external Endor rule reference.");
}
const message = record(result["message"], "Endor message");
@@ -320,8 +302,7 @@ export function normalizeEndorSarif(
],
source_data: structuredClone({
...context,
runContext: sarifRunContextForResult(
context.runContext,
runContext: selectRunContext(
result,
rule,
context.documentContext,
+6 -204
View File
@@ -1,7 +1,4 @@
import { lstat, readFile, realpath, stat } from "node:fs/promises";
import { dirname, isAbsolute, join, resolve, sep } from "node:path";
import { isNumberObject } from "node:util/types";
import { environmentEntry } from "./auth.js";
import { CodexSecurityError } from "./errors.js";
import {
forwardExternalImportSetting,
@@ -23,6 +20,11 @@ import type {
Provider,
} from "./external-import-models.js";
import { localFindingRepositories } from "./external-findings-read.js";
import {
hasGitMetadata,
localGitProtectionRoots,
importGitProtectionRoots,
} from "./local-git-metadata.js";
import {
blackDuckReportRepositories,
projectedBlackDuckRepositoryUrl,
@@ -53,11 +55,8 @@ import {
import {
abortable,
enclosingGitWorktreeRoot,
gitMarkerRoot,
gitOutput,
gitProtectionRoots,
normalizeRepository,
nullIfMissingPath,
} from "./targets.js";
/** A scanner source record, independent of a Codex assessment or completed scan. */
@@ -405,194 +404,6 @@ function sameScannerRepositories(
return true;
}
async function bareMetadataRoots(
repository: string,
signal?: AbortSignal,
): Promise<string[]> {
const roots: string[] = [];
let directory = repository;
for (;;) {
signal?.throwIfAborted();
const present = async (name: string) =>
(await abortable(
() => lstat(join(directory, name)).catch(nullIfMissingPath),
signal,
)) !== null;
// Git also discovers bare repositories and linked metadata without .git.
const head = await abortable(
() => lstat(join(directory, "HEAD")).catch(nullIfMissingPath),
signal,
);
if (
(head?.isFile() || head?.isSymbolicLink()) &&
((await present("commondir")) ||
((await present("objects")) && (await present("refs"))))
)
roots.push(directory);
const parent = dirname(directory);
if (parent === directory) return roots;
directory = parent;
}
}
async function metadataPointer(
path: string,
prefix: string,
context: { directory: string; environment: NodeJS.ProcessEnv },
signal?: AbortSignal,
): Promise<string | undefined> {
const metadata = await abortable(
() => stat(path).catch(nullIfMissingPath),
signal,
);
if (!metadata?.isFile()) return undefined;
const text = await abortable(() => readFile(path, "utf8"), signal);
if (!text.startsWith(prefix) || (prefix === "" && text.length === 0))
return undefined;
const payload = text.slice(prefix.length).replace(/[\r\n]+$/u, "");
if (prefix !== "" && payload.length === 0) return undefined;
// Git checks emptiness before consuming the path as a NUL-terminated string.
const value = payload.split("\0", 1)[0]!;
// Preserve filesystem traversal through links before '..'.
let target = isAbsolute(value) ? value : `${dirname(path)}${sep}${value}`;
if (process.platform === "win32") {
const drive = /^[A-Za-z]:(?![\\/])/u.exec(value)?.[0].toUpperCase();
if (drive !== undefined) {
const directory =
context.directory.slice(0, 2).toUpperCase() === drive
? context.directory
: environmentEntry(context.environment, `=${drive}`) || `${drive}\\`;
target = resolve(directory, value.slice(2));
} else if (isAbsolute(value)) target = resolve(context.directory, value);
}
return (
(await abortable(
() => realpath(target).catch(nullIfMissingPath),
signal,
)) ?? undefined
);
}
async function associatedMetadataRoots(
directory: string,
context: { directory: string; environment: NodeJS.ProcessEnv },
signal?: AbortSignal,
configurationDirectory?: string,
): Promise<string[]> {
const head = await abortable(
() => lstat(join(directory, "HEAD")).catch(nullIfMissingPath),
signal,
);
if (!head || (!head.isFile() && !head.isSymbolicLink())) return [];
const commonMarker = join(directory, "commondir");
const hasCommon = await abortable(
() => lstat(commonMarker).catch(nullIfMissingPath),
signal,
);
const common = hasCommon
? await metadataPointer(commonMarker, "", context, signal)
: undefined;
if (hasCommon && common === undefined) return [];
const storage = common ?? directory;
for (const name of ["objects", "refs"]) {
const metadata = await abortable(
() => stat(join(storage, name)).catch(nullIfMissingPath),
signal,
);
if (!metadata?.isDirectory()) return [];
}
const roots = common === undefined ? [directory] : [directory, common];
if (
process.platform === "win32" &&
configurationDirectory !== undefined &&
configurationDirectory !== context.directory
) {
// Git rereads commondir after changing to the discovered repository root.
roots.push(
...(await associatedMetadataRoots(
directory,
{
...context,
directory: await abortable(
() => canonicalConfigPath(configurationDirectory),
signal,
),
},
signal,
)),
);
}
return roots;
}
export async function localGitProtectionRoots(
repository: string,
environment: NodeJS.ProcessEnv,
signal?: AbortSignal,
): Promise<string[]> {
const roots = new Set(
await abortable(() => gitProtectionRoots(repository, signal), signal),
);
const context = {
directory: await abortable(() => canonicalConfigPath(repository), signal),
environment,
};
const paths = new Set([resolve(repository), context.directory]);
for (const path of paths) {
for (const root of await bareMetadataRoots(path, signal)) {
roots.add(root);
for (const associated of await associatedMetadataRoots(
root,
context,
signal,
root,
))
roots.add(associated);
}
let directory = path;
for (;;) {
signal?.throwIfAborted();
const marker = join(directory, ".git");
const metadata = await abortable(
() => stat(marker).catch(nullIfMissingPath),
signal,
);
if (metadata !== null) {
roots.add(directory);
const gitDirectory = metadata.isDirectory()
? await abortable(() => realpath(marker), signal)
: await metadataPointer(marker, "gitdir: ", context, signal);
if (gitDirectory !== undefined)
for (const associated of await associatedMetadataRoots(
gitDirectory,
context,
signal,
directory,
))
roots.add(associated);
}
const parent = dirname(directory);
if (parent === directory) break;
directory = parent;
}
}
for (const root of [...roots])
roots.add(await abortable(() => canonicalConfigPath(root), signal));
return [...roots];
}
async function hasGitMetadata(
repository: string,
signal?: AbortSignal,
): Promise<boolean> {
return (
(await abortable(
() => gitMarkerRoot(repository, signal, "nearest"),
signal,
)) !== null || (await bareMetadataRoots(repository, signal)).length !== 0
);
}
/** @internal */
export interface ConfiguredFetchRemote {
name: string;
@@ -786,16 +597,7 @@ async function localContext(
...new Set([
repository,
...(await abortable(
() => localGitProtectionRoots(path, environment, dependencies.signal),
dependencies.signal,
)),
...(await abortable(
() =>
localGitProtectionRoots(
process.cwd(),
environment,
dependencies.signal,
),
() => importGitProtectionRoots(path, environment, dependencies.signal),
dependencies.signal,
)),
]),
@@ -31,6 +31,7 @@ import {
type ExternalFindingsReaderOptions,
} from "./external-findings-read.js";
import { canonicalJson } from "./record.js";
import { notify } from "./value.js";
import { wizCsvRepositoryUrl } from "./wiz-csv.js";
import { wizFindingRepository } from "./wiz-findings.js";
import { dependabotRepository } from "./github-dependabot-findings.js";
@@ -446,13 +447,8 @@ async function preparePublicationInput(
dependencies: ExternalPublicationDependencies,
): Promise<PreparedExternalPublication> {
const { inspectorProjectMap } = options;
const progress = (event: ExternalPublicationProgress): void => {
try {
dependencies.onProgress?.(event);
} catch {
// Optional progress must not interrupt preparation or publication.
}
};
const progress = (event: ExternalPublicationProgress): void =>
notify(() => dependencies.onProgress?.(event));
if (
!options.sourceKey.trim() ||
options.sourceKey.includes("\0") ||
@@ -163,6 +163,8 @@ export async function readExternalFindings(
sourceRepositories: [{ url }],
};
}
// A new reader must choose its parser before reaching the Wiz replay path.
options.provider satisfies "wiz";
const publication = await readVendorFindingsForPublication(path, target);
const sourceRepositories = publication.current.findings.flatMap((finding) =>
localFindingRepositories("wiz", finding),
@@ -349,6 +349,7 @@ export function validateExternalEvidenceJson(
pending.push([child, depth + 1]);
} else if (typeof value === "number") {
requireJsonNumber(value, "Evidence");
if (target === "local") continue;
const wire = JSON.stringify(value);
// Cloud pads short exponents and formats small fractions scientifically.
const cloud = (
+22 -48
View File
@@ -3,9 +3,15 @@ import {
CANONICAL_GHSA_ID,
githubRepositoryParts,
} from "./github-identifiers.js";
import { CodexSecurityError, errorMessage } from "./errors.js";
import { CodexSecurityError } from "./errors.js";
import { requireExternalImports } from "./external-imports-feature.js";
import { createAuthenticatedGitHub } from "./github.js";
import {
githubImportHost,
githubImportClient,
githubImportError,
type GitHubImportConnectionOptions,
type GitHubImportDependencies,
} from "./github.js";
export const GITHUB_ADVISORY_STATES = [
"published",
@@ -14,7 +20,7 @@ export const GITHUB_ADVISORY_STATES = [
"closed",
] as const;
export interface GitHubAdvisoryImportOptions {
export interface GitHubAdvisoryImportOptions extends GitHubImportConnectionOptions {
/** Source repository, or the selected target for explicit global advisory IDs. */
repository: string;
/** Exact GHSA IDs. Required for the global advisory API. */
@@ -23,11 +29,6 @@ export interface GitHubAdvisoryImportOptions {
source?: "repository" | "global";
/** Repository list state (default: published). Exact IDs ignore state. */
state?: (typeof GITHUB_ADVISORY_STATES)[number];
/** Defaults to GH_HOST or github.com. */
githubHost?: string;
/** Omit to use the authenticated GitHub CLI. */
githubToken?: string;
signal?: AbortSignal;
}
type RepositoryAdvisory = Awaited<ReturnType<typeof fetchRepositoryAdvisory>>;
@@ -44,16 +45,10 @@ export interface ImportedGitHubAdvisory {
advisory: RepositoryAdvisory | GlobalAdvisory;
}
interface GitHubAdvisoryImportDependencies {
environment?: NodeJS.ProcessEnv;
currentDirectory?: string;
createGitHub?: (host: string, signal?: AbortSignal) => Promise<Octokit>;
}
/** Read repository disclosures or explicitly selected public GHSA records. */
export async function importGitHubAdvisories(
options: GitHubAdvisoryImportOptions,
dependencies: GitHubAdvisoryImportDependencies = {},
dependencies: GitHubImportDependencies = {},
): Promise<ImportedGitHubAdvisory[]> {
options.signal?.throwIfAborted();
const environment = dependencies.environment ?? process.env;
@@ -93,20 +88,15 @@ export async function importGitHubAdvisories(
throw new CodexSecurityError(
"--github-state only filters repository lists; omit it when selecting exact GHSA IDs.",
);
const host =
options.githubHost?.trim() ??
(environment["GH_HOST"]?.trim() || "github.com");
if (!host) throw new CodexSecurityError("GitHub host must not be empty.");
const host = githubImportHost(options.githubHost, environment);
try {
const github = dependencies.createGitHub
? await dependencies.createGitHub(host, options.signal)
: await createAuthenticatedGitHub(host, {
token: options.githubToken,
environment,
currentDirectory: dependencies.currentDirectory,
signal: options.signal,
});
const github = await githubImportClient(
host,
options,
dependencies,
environment,
);
const advisories: (RepositoryAdvisory | GlobalAdvisory)[] = [];
if (ids.length > 0) {
for (const id of ids) {
@@ -165,29 +155,13 @@ export async function importGitHubAdvisories(
advisory,
}));
} catch (error) {
options.signal?.throwIfAborted();
if (error instanceof CodexSecurityError) throw error;
const status =
typeof error === "object" && error !== null && "status" in error
? error.status
: undefined;
if (status === 401)
throw new CodexSecurityError("GitHub authentication failed.");
if (status === 403)
throw new CodexSecurityError(
throw githubImportError(error, options.signal, {
operation: "security advisory",
denied:
"GitHub denied security advisory access. Check repository advisory permissions and API rate limits.",
);
if (status === 404)
throw new CodexSecurityError(
notFound:
"GitHub repository or security advisory was not found or is not accessible.",
);
if (status === 429)
throw new CodexSecurityError(
"GitHub request was rate limited. Wait and retry.",
);
throw new CodexSecurityError(
`GitHub security advisory request failed${typeof status === "number" ? ` (HTTP ${status})` : ""}: ${errorMessage(error)}`,
);
});
}
}
+13 -18
View File
@@ -10,14 +10,9 @@ import {
isGitHubDependabotAlert,
normalizeGitHubDependabotAlerts,
} from "./github-dependabot-findings.js";
import { asRecord } from "./record.js";
import { parseJsonOrJsonl, readScannerText, text } from "./scanner-import.js";
function object(value: unknown): Record<string, unknown> | undefined {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
function repositoryName(value: unknown): string {
const repository = text(value);
if (!repository || !githubRepositoryParts(repository))
@@ -58,7 +53,7 @@ function codeScanningFinding(
target: ExternalImportTarget = "cloud",
): ExternalFinding {
const repository = repositoryName(record["repository"]);
const alert = object(record["alert"]);
const alert = asRecord(record["alert"]);
const number = record["number"];
if (
!alert ||
@@ -84,16 +79,16 @@ function codeScanningFinding(
throw new Error(
"GitHub alert URL does not match the selected repository and alert.",
);
const rule = object(alert["rule"]);
const instance = object(alert["most_recent_instance"]);
const rule = asRecord(alert["rule"]);
const instance = asRecord(alert["most_recent_instance"]);
const ref = text(instance?.["ref"]);
if (!ref)
throw new Error(
"GitHub code-scanning evidence requires the selected instance ref.",
);
const location = object(instance?.["location"]);
const tool = object(alert["tool"]);
const message = text(object(instance?.["message"])?.["text"]);
const location = asRecord(instance?.["location"]);
const tool = asRecord(alert["tool"]);
const message = text(asRecord(instance?.["message"])?.["text"]);
const description =
text(rule?.["full_description"]) ?? text(rule?.["description"]);
const tags = Array.isArray(rule?.["tags"]) ? rule["tags"] : [];
@@ -158,7 +153,7 @@ function advisoryFinding(
target: ExternalImportTarget = "cloud",
): ExternalFinding {
const repository = repositoryName(record["repository"]);
const advisory = object(record["advisory"]);
const advisory = asRecord(record["advisory"]);
const id = text(record["ghsaId"]);
const selection = record["selection"];
if (
@@ -202,11 +197,11 @@ function advisoryFinding(
const advisoryIds = [
id,
text(advisory["cve_id"]),
...identifiers.map((identifier) => text(object(identifier)?.["value"])),
...identifiers.map((identifier) => text(asRecord(identifier)?.["value"])),
].filter((value): value is string => value !== null);
const packages = vulnerabilities.flatMap((value) => {
const vulnerability = object(value);
const pkg = object(vulnerability?.["package"]);
const vulnerability = asRecord(value);
const pkg = asRecord(vulnerability?.["package"]);
const name = text(pkg?.["name"]);
// GitHub permits incomplete package metadata in advisory disclosures.
// Preserve it in source_data without inventing a typed package identity.
@@ -255,7 +250,7 @@ function advisoryFinding(
(selection === "global" ? "published" : null)),
scanner_origin: "GitHub Security Advisories",
weakness_ids: cwes
.map((value) => text(object(value)?.["cwe_id"]))
.map((value) => text(asRecord(value)?.["cwe_id"]))
.filter((value): value is string => value !== null),
},
},
@@ -275,7 +270,7 @@ function normalizeRecords(
};
const identities = new Set<string>();
for (const [index, value] of records.entries()) {
const record = object(value);
const record = asRecord(value);
try {
if (!record) throw new Error("GitHub finding must be an object.");
let finding: ExternalFinding;
+77 -44
View File
@@ -17,7 +17,15 @@ export const GITHUB_ALERT_STATES = [
"all",
] as const;
export interface GitHubCodeScanningImportOptions {
export interface GitHubImportConnectionOptions {
/** Defaults to GH_HOST or github.com. */
githubHost?: string;
/** Omit to use the authenticated GitHub CLI, including its token environment. */
githubToken?: string;
signal?: AbortSignal;
}
export interface GitHubCodeScanningImportOptions extends GitHubImportConnectionOptions {
/** GitHub repository in OWNER/REPO form. */
repository: string;
/** Exact alert numbers, regardless of state. Omit to list matching alerts. */
@@ -26,11 +34,6 @@ export interface GitHubCodeScanningImportOptions {
state?: (typeof GITHUB_ALERT_STATES)[number];
/** Git reference to inspect; omitted lists the default branch. */
ref?: string;
/** Defaults to GH_HOST or github.com. */
githubHost?: string;
/** Omit to use the authenticated GitHub CLI, including its token environment. */
githubToken?: string;
signal?: AbortSignal;
}
export interface ImportedGitHubCodeScanningAlert {
@@ -42,7 +45,7 @@ export interface ImportedGitHubCodeScanningAlert {
alert: GitHubAlert;
}
interface GitHubImportDependencies {
export interface GitHubImportDependencies {
environment?: NodeJS.ProcessEnv;
currentDirectory?: string;
createGitHub?: (host: string, signal?: AbortSignal) => Promise<Octokit>;
@@ -96,6 +99,61 @@ export async function createAuthenticatedGitHub(
});
}
export function githubImportHost(
githubHost: string | undefined,
environment: NodeJS.ProcessEnv,
): string {
const host =
githubHost?.trim() ?? (environment["GH_HOST"]?.trim() || "github.com");
if (!host) throw new CodexSecurityError("GitHub host must not be empty.");
return host;
}
export function githubImportClient(
host: string,
options: GitHubImportConnectionOptions,
dependencies: GitHubImportDependencies,
environment: NodeJS.ProcessEnv,
): Promise<Octokit> {
return dependencies.createGitHub
? dependencies.createGitHub(host, options.signal)
: createAuthenticatedGitHub(host, {
token: options.githubToken,
environment,
currentDirectory: dependencies.currentDirectory,
signal: options.signal,
});
}
export function githubImportError(
error: unknown,
signal: AbortSignal | undefined,
messages: { operation: string; denied: string; notFound: string },
): CodexSecurityError {
signal?.throwIfAborted();
if (error instanceof CodexSecurityError) return error;
const status =
typeof error === "object" && error !== null && "status" in error
? error.status
: undefined;
switch (status) {
case 401:
return new CodexSecurityError("GitHub authentication failed.");
case 403:
return new CodexSecurityError(messages.denied);
case 404:
return new CodexSecurityError(messages.notFound);
case 429:
return new CodexSecurityError(
"GitHub request was rate limited. Wait and retry.",
);
default:
return new CodexSecurityError(
`GitHub ${messages.operation} request failed${typeof status === "number" ? ` (HTTP ${status})` : ""}: ${errorMessage(error)}`,
);
}
}
export async function importGitHubCodeScanningAlerts(
options: GitHubCodeScanningImportOptions,
dependencies: GitHubImportDependencies = {},
@@ -126,22 +184,15 @@ export async function importGitHubCodeScanningAlerts(
throw new CodexSecurityError("GitHub reference must not be empty.");
}
const environment = dependencies.environment ?? process.env;
const host =
options.githubHost?.trim() ??
(environment["GH_HOST"]?.trim() || "github.com");
if (host.length === 0) {
throw new CodexSecurityError("GitHub host must not be empty.");
}
const host = githubImportHost(options.githubHost, environment);
try {
const github = dependencies.createGitHub
? await dependencies.createGitHub(host, options.signal)
: await createAuthenticatedGitHub(host, {
token: options.githubToken,
environment,
currentDirectory: dependencies.currentDirectory,
signal: options.signal,
});
const github = await githubImportClient(
host,
options,
dependencies,
environment,
);
const selected = new Map<number, GitHubAlert["most_recent_instance"]>();
if (numbers.length === 0 || ref !== undefined) {
let page = 1;
@@ -204,31 +255,13 @@ export async function importGitHubCodeScanningAlerts(
}
return alerts;
} catch (error) {
options.signal?.throwIfAborted();
if (error instanceof CodexSecurityError) throw error;
const status =
typeof error === "object" && error !== null && "status" in error
? error.status
: undefined;
if (status === 401)
throw new CodexSecurityError("GitHub authentication failed.");
if (status === 403) {
throw new CodexSecurityError(
throw githubImportError(error, options.signal, {
operation: "code scanning",
denied:
"GitHub denied code scanning access. Check repository permissions, code scanning availability, and API rate limits.",
);
}
if (status === 404) {
throw new CodexSecurityError(
notFound:
"GitHub repository or code scanning alert was not found or is not accessible.",
);
}
if (status === 429)
throw new CodexSecurityError(
"GitHub request was rate limited. Wait and retry.",
);
throw new CodexSecurityError(
`GitHub code scanning request failed${typeof status === "number" ? ` (HTTP ${status})` : ""}: ${errorMessage(error)}`,
);
});
}
}
+1
View File
@@ -354,6 +354,7 @@ export {
normalizeSnykSarif,
readSnykFindings,
} from "./snyk-findings.js";
export { normalizeSelectedSemgrepPlatformFindings } from "./semgrep-platform-findings.js";
export {
normalizeSemgrepFindings,
normalizeSemgrepSarif,
+3 -14
View File
@@ -20,7 +20,7 @@ import {
normalizeRecords,
readScannerJson,
record,
relativePath,
repositoryFilePath,
requiredText,
text,
} from "./scanner-import.js";
@@ -444,17 +444,6 @@ export function inspectorReportRepository(
};
}
function repoFile(value: unknown): string | null {
const relative = relativePath(value);
if (!relative) return null;
const path = posix.normalize(relative);
return path === "." ||
path.endsWith("/") ||
/^(?:[a-z][a-z\d+.-]*:|~[^/]*(?:\/|$)|[^/]+@[^/]+:)/iu.test(path)
? null
: path;
}
function timestamp(value: unknown): number {
const seconds =
typeof value === "number"
@@ -587,7 +576,7 @@ function evidence(
const level = requiredText(severity, "Inspector severity").toLowerCase();
const paths = new Set<string>();
const packages = (pkg?.vulnerablePackages ?? []).map((item) => {
const path = repoFile(item.filePath);
const path = repositoryFilePath(item.filePath);
if (path) paths.add(path);
const ecosystem = ecosystems.get(text(item.packageManager) ?? "") ?? null;
const version = (value: unknown) =>
@@ -609,7 +598,7 @@ function evidence(
);
if (code) {
const { fileName, filePath, startLine } = code.filePath;
const path = repoFile(filePath);
const path = repositoryFilePath(filePath);
if (path && posix.basename(path) === fileName)
locations.push({
path,
+213
View File
@@ -0,0 +1,213 @@
import { lstat, readFile, realpath, stat } from "node:fs/promises";
import { dirname, isAbsolute, join, resolve, sep } from "node:path";
import { environmentEntry } from "./auth.js";
import { abortReason } from "./errors.js";
import { canonicalConfigPath } from "./runtime.js";
import {
abortable,
gitMarkerRoot,
gitProtectionRoots,
nullIfMissingPath,
} from "./targets.js";
async function bareMetadataRoots(
repository: string,
signal?: AbortSignal,
): Promise<string[]> {
const roots: string[] = [];
let directory = repository;
for (;;) {
signal?.throwIfAborted();
const present = async (name: string) =>
(await abortable(
() => lstat(join(directory, name)).catch(nullIfMissingPath),
signal,
)) !== null;
// Git also discovers bare repositories and linked metadata without .git.
const head = await abortable(
() => lstat(join(directory, "HEAD")).catch(nullIfMissingPath),
signal,
);
if (
(head?.isFile() || head?.isSymbolicLink()) &&
((await present("commondir")) ||
((await present("objects")) && (await present("refs"))))
)
roots.push(directory);
const parent = dirname(directory);
if (parent === directory) return roots;
directory = parent;
}
}
async function metadataPointer(
path: string,
prefix: string,
context: { directory: string; environment: NodeJS.ProcessEnv },
signal?: AbortSignal,
): Promise<string | undefined> {
const metadata = await abortable(
() => stat(path).catch(nullIfMissingPath),
signal,
);
if (!metadata?.isFile()) return undefined;
const text = await abortable(() => readFile(path, "utf8"), signal);
if (!text.startsWith(prefix) || (prefix === "" && text.length === 0))
return undefined;
const payload = text.slice(prefix.length).replace(/[\r\n]+$/u, "");
if (prefix !== "" && payload.length === 0) return undefined;
// Git checks emptiness before consuming the path as a NUL-terminated string.
const value = payload.split("\0", 1)[0]!;
// Preserve filesystem traversal through links before '..'.
let target = isAbsolute(value) ? value : `${dirname(path)}${sep}${value}`;
if (process.platform === "win32") {
const drive = /^[A-Za-z]:(?![\\/])/u.exec(value)?.[0].toUpperCase();
if (drive !== undefined) {
const directory =
context.directory.slice(0, 2).toUpperCase() === drive
? context.directory
: environmentEntry(context.environment, `=${drive}`) || `${drive}\\`;
target = resolve(directory, value.slice(2));
} else if (isAbsolute(value)) target = resolve(context.directory, value);
}
return (
(await abortable(
() => realpath(target).catch(nullIfMissingPath),
signal,
)) ?? undefined
);
}
async function associatedMetadataRoots(
directory: string,
context: { directory: string; environment: NodeJS.ProcessEnv },
signal?: AbortSignal,
configurationDirectory?: string,
): Promise<string[]> {
const head = await abortable(
() => lstat(join(directory, "HEAD")).catch(nullIfMissingPath),
signal,
);
if (!head || (!head.isFile() && !head.isSymbolicLink())) return [];
const commonMarker = join(directory, "commondir");
const hasCommon = await abortable(
() => lstat(commonMarker).catch(nullIfMissingPath),
signal,
);
const common = hasCommon
? await metadataPointer(commonMarker, "", context, signal)
: undefined;
if (hasCommon && common === undefined) return [];
const storage = common ?? directory;
for (const name of ["objects", "refs"]) {
const metadata = await abortable(
() => stat(join(storage, name)).catch(nullIfMissingPath),
signal,
);
if (!metadata?.isDirectory()) return [];
}
const roots = common === undefined ? [directory] : [directory, common];
if (
process.platform === "win32" &&
configurationDirectory !== undefined &&
configurationDirectory !== context.directory
) {
// Git rereads commondir after changing to the discovered repository root.
roots.push(
...(await associatedMetadataRoots(
directory,
{
...context,
directory: await abortable(
() => canonicalConfigPath(configurationDirectory),
signal,
),
},
signal,
)),
);
}
return roots;
}
export async function localGitProtectionRoots(
repository: string,
environment: NodeJS.ProcessEnv,
signal?: AbortSignal,
): Promise<string[]> {
const roots = new Set(
await abortable(() => gitProtectionRoots(repository, signal), signal),
);
const context = {
directory: await abortable(() => canonicalConfigPath(repository), signal),
environment,
};
const paths = new Set([resolve(repository), context.directory]);
for (const path of paths) {
for (const root of await bareMetadataRoots(path, signal)) {
roots.add(root);
for (const associated of await associatedMetadataRoots(
root,
context,
signal,
root,
))
roots.add(associated);
}
let directory = path;
for (;;) {
signal?.throwIfAborted();
const marker = join(directory, ".git");
const metadata = await abortable(
() => stat(marker).catch(nullIfMissingPath),
signal,
);
if (metadata !== null) {
roots.add(directory);
const gitDirectory = metadata.isDirectory()
? await abortable(() => realpath(marker), signal)
: await metadataPointer(marker, "gitdir: ", context, signal);
if (gitDirectory !== undefined)
for (const associated of await associatedMetadataRoots(
gitDirectory,
context,
signal,
directory,
))
roots.add(associated);
}
const parent = dirname(directory);
if (parent === directory) break;
directory = parent;
}
}
for (const root of [...roots])
roots.add(await abortable(() => canonicalConfigPath(root), signal));
return [...roots];
}
/** Discover Git metadata for the selection, then for the current working directory. */
export async function importGitProtectionRoots(
repository: string,
environment: NodeJS.ProcessEnv,
signal?: AbortSignal,
): Promise<string[]> {
const roots = await localGitProtectionRoots(repository, environment, signal);
const cwd = process.cwd();
if (signal?.aborted) throw abortReason(signal);
if (cwd !== repository)
roots.push(...(await localGitProtectionRoots(cwd, environment, signal)));
return roots;
}
export async function hasGitMetadata(
repository: string,
signal?: AbortSignal,
): Promise<boolean> {
return (
(await abortable(
() => gitMarkerRoot(repository, signal, "nearest"),
signal,
)) !== null || (await bareMetadataRoots(repository, signal)).length !== 0
);
}
+4
View File
@@ -2,6 +2,10 @@ export function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
export function asRecord(value: unknown): Record<string, unknown> | undefined {
return isRecord(value) ? value : undefined;
}
export function canonicalJson(
value: unknown,
compareKeys?: (left: string, right: string) => number,

Some files were not shown because too many files have changed in this diff Show More