From a2ca5b48b8b3807c944c7380ad571f8253a6ff3a Mon Sep 17 00:00:00 2001 From: Max Irgiznov <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:07:28 +0100 Subject: [PATCH 1/4] Prepare 0.16.1 from protected dev (#361) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Scope Promote the reviewed development branch for 0.16.1. This includes incremental local review fixes and diagnostics, reviewed dependency and action updates (#346–350), OCR qualification, the protected contributor workflow, and publication and external-tool boundary changes. Operators using MCP federation must migrate the external registry and tool declarations together. The default identity-only configuration requires no registry. The pending changelog includes migration guidance and credits @ahmedpdf445-stack for #354. Related issues: #351, #352, #353, #355, #356, #358. Keep these open through stable receipt verification. ## Release sequence Verify all required checks against the actual protected dev and main revisions before promotion. After merging this promotion, verify the development wheel and source distribution on TestPyPI. Stable publication follows the separate signed release pull request and maintainer authorization. ## Verified development tree Development head 4e82db11 has the exact tree reviewed in #360. All 12 required checks and both additional macOS test jobs passed before the squash merge. Local quality passed 6,809 tests and 364 subtests, with 11 optional skips and 90.03% coverage. Both distribution formats passed the installed MCP smoke. The full correction range and tree passed Gitleaks and the locked third-party dependency audit reported no known vulnerabilities. The subsequent test-only change #362 verifies that the protected main branch’s older OCR correctly triggers a rejection on a tracked ignored file missing from preview. It also checks the explicit gitignore exclusion with the newly qualified OCR on dev. All 12 required checks and both macOS jobs passed on #362. The final development commit is 65ed3d0. --------- Co-authored-by: Ahmed --- .github/ISSUE_TEMPLATE/bug_report.yml | 2 +- .github/ISSUE_TEMPLATE/feature_request.yml | 3 + .github/PULL_REQUEST_TEMPLATE.md | 4 + .github/dependabot.yml | 2 + .github/workflows/actions-maintenance.yml | 1 + .github/workflows/build.yml | 21 +- .github/workflows/ci.yml | 100 ++- .github/workflows/codeql.yml | 20 +- .github/workflows/dependency-review.yml | 7 +- .github/workflows/ocr-compatibility.yml | 87 +-- .github/workflows/release.yml | 79 ++- .github/workflows/scorecard.yml | 7 +- .github/workflows/security.yml | 82 ++- .github/workflows/site-release-notify.yml | 122 +++- .github/workflows/testpypi.yml | 6 +- CONTRIBUTING.md | 28 +- PLANS.md | 155 +++++ README.md | 4 +- changelog.d/346.maintenance.md | 1 + changelog.d/350.security.md | 1 + changelog.d/351.bugfix.md | 1 + changelog.d/352.feature.md | 1 + changelog.d/353.feature.md | 1 + changelog.d/354.contributor.md | 1 + changelog.d/355.bugfix.md | 1 + changelog.d/355.maintenance.md | 1 + changelog.d/356.maintenance.md | 1 + changelog.d/356.security.md | 4 + changelog.d/358.bugfix.md | 1 + changelog.d/README.md | 4 +- .../evidence/ocr-1.14.6-local-review.json | 31 + compatibility/evidence/ocr-1.14.6.json | 421 ++++++++++++ compatibility/ocr-support.json | 61 +- docs/README.md | 2 + docs/codex/ENGINEERING_WORKFLOW_STATE.yaml | 2 +- docs/codex/TASKS_BACKLOG.md | 4 +- docs/compatibility.md | 44 +- docs/configuration.md | 33 +- docs/contributor-intake.md | 15 + docs/development.md | 88 ++- docs/engineering/README.md | 2 +- .../governed_federation_contracts.md | 84 ++- docs/engineering/review_signal_ownership.md | 16 +- docs/engineering/test_evidence_matrix.md | 19 +- docs/engineering/toolkit_strategy.md | 26 +- docs/gitlab.md | 34 +- docs/local.md | 53 +- docs/operations.md | 18 +- docs/release.md | 36 +- docs/review-context.md | 32 +- docs/review-decision-flow.md | 57 +- docs/security.md | 150 +++- examples/gitlab/README.md | 8 +- examples/gitlab/context/README.md | 2 +- .../gitlab/modes/direct-mcp.gitlab-ci.yml | 4 +- .../modes/enriched-discussions.gitlab-ci.yml | 2 +- .../gitlab/modes/identity-only.gitlab-ci.yml | 2 +- examples/gitlab/modes/metadata.gitlab-ci.yml | 2 +- examples/gitlab/ocr-review.gitlab-ci.yml | 2 +- pyproject.toml | 5 + scripts/dependency-audit.sh | 2 +- scripts/gitleaks.sh | 45 +- scripts/installed_runtime_smoke.py | 27 +- scripts/ocr_qualification/delivery.py | 15 +- scripts/release_authorization.py | 2 +- src/ocr_toolkit/_qualified_handoffs.json | 30 + src/ocr_toolkit/common/redaction.py | 21 +- src/ocr_toolkit/context/broker.py | 28 +- src/ocr_toolkit/context/ci_outcomes.py | 8 +- src/ocr_toolkit/context/dlp/admission.py | 190 ++++-- src/ocr_toolkit/context/dlp/arithmetic.py | 59 ++ src/ocr_toolkit/context/dlp/datetimes.py | 77 ++- src/ocr_toolkit/context/dlp/markup.py | 26 +- src/ocr_toolkit/context/dlp/numeric.py | 13 +- src/ocr_toolkit/context/dlp/projection.py | 102 ++- src/ocr_toolkit/context/dlp/provenance.py | 69 ++ src/ocr_toolkit/context/mcp.py | 13 +- src/ocr_toolkit/context/store.py | 92 ++- .../evidence/gitlink_projection.py | 620 +++++++++++++---- src/ocr_toolkit/evidence/gitlinks.py | 21 +- src/ocr_toolkit/evidence/project.py | 4 +- src/ocr_toolkit/evidence/repository.py | 290 ++++++-- src/ocr_toolkit/evidence/source_reader.py | 3 + src/ocr_toolkit/federation/admission.py | 209 ++++-- src/ocr_toolkit/federation/contracts.py | 9 +- src/ocr_toolkit/federation/gateway.py | 95 ++- src/ocr_toolkit/federation/registry.py | 53 +- src/ocr_toolkit/federation/runtime.py | 20 +- src/ocr_toolkit/local_incremental.py | 409 +++++++++-- .../local_incremental_dependencies.py | 385 ++++++++--- src/ocr_toolkit/local_incremental_replay.py | 257 +++++++ src/ocr_toolkit/local_incremental_state.py | 253 ++++++- src/ocr_toolkit/mcp_config.py | 12 +- src/ocr_toolkit/native_capabilities.py | 6 + src/ocr_toolkit/ocr_result.py | 141 +++- src/ocr_toolkit/posting/approval.py | 9 +- src/ocr_toolkit/posting/formatting.py | 74 +- src/ocr_toolkit/posting/snapshot.py | 82 ++- src/ocr_toolkit/posting/workflow.py | 132 +++- src/ocr_toolkit/preflight.py | 3 +- .../providers/gitlab_discussions.py | 7 +- .../providers/gitlab_remediation.py | 15 +- src/ocr_toolkit/providers/local.py | 43 +- src/ocr_toolkit/reporting/dlp.py | 45 +- src/ocr_toolkit/reporting/incremental.py | 52 ++ src/ocr_toolkit/reporting/outcome.py | 21 +- src/ocr_toolkit/reporting/result.py | 18 + src/ocr_toolkit/result_contract.py | 92 ++- src/ocr_toolkit/review_coverage.py | 90 +++ src/ocr_toolkit/review_receipt.py | 66 +- src/ocr_toolkit/review_runner.py | 255 +++++-- src/ocr_toolkit/telemetry/locales/en.json | 1 + src/ocr_toolkit/telemetry/locales/ru.json | 3 +- .../telemetry/metrics/technical.py | 2 +- .../telemetry/publications/metrics.py | 32 +- .../telemetry/publications/signals.py | 3 +- .../telemetry/publications/status.py | 5 +- .../telemetry/publications/summary.py | 3 +- tests/federation/sdk_peer.py | 5 + tests/federation/test_admission.py | 188 +++++- tests/federation/test_gateway.py | 291 +++++++- tests/federation/test_https.py | 97 ++- tests/federation/test_ocr_qualification.py | 158 ++++- tests/federation/test_process.py | 13 +- tests/fuzz/test_federation.py | 17 +- tests/providers/installed_local_review.py | 18 +- tests/reporting/test_dlp_accounting.py | 21 +- tests/reporting/test_local.py | 82 +++ tests/test_context_broker.py | 35 +- tests/test_context_mcp.py | 26 + tests/test_context_store.py | 79 +++ tests/test_dependency_workflow.py | 49 +- tests/test_dlp_arithmetic.py | 145 ++++ tests/test_dlp_attribution.py | 77 ++- tests/test_dlp_audit.py | 40 ++ tests/test_dlp_composition.py | 55 +- tests/test_dlp_date_ranges.py | 136 ++++ tests/test_dlp_publication_edges.py | 226 +++++++ tests/test_dlp_safe_markup.py | 63 +- tests/test_docs_only_ci.py | 353 +++++++++- tests/test_environment_contract.py | 6 +- tests/test_evidence_repository.py | 151 ++++- tests/test_gitlab_discussions.py | 37 +- tests/test_gitlab_provider.py | 90 ++- tests/test_gitlinks.py | 461 ++++++++++++- tests/test_installed_policy_e2e.py | 73 +- tests/test_integration_contracts.py | 30 +- tests/test_local_incremental.py | 549 ++++++++++++++- tests/test_local_incremental_replay.py | 539 +++++++++++++++ ...mcp_config_v2.py => test_mcp_config_v3.py} | 15 +- tests/test_ocr_compat.py | 79 ++- tests/test_ocr_qualification_recovery.py | 3 +- tests/test_ocr_result_contract.py | 62 ++ tests/test_operations_docs.py | 25 +- tests/test_posting_approval.py | 146 +++- tests/test_posting_helpers.py | 142 +++- tests/test_posting_v11_flow.py | 327 +++++++-- tests/test_quality_script.py | 162 +++-- tests/test_release_authorization.py | 104 +++ tests/test_release_notes.py | 1 + tests/test_repository_coverage.py | 5 +- tests/test_result_contract.py | 34 + tests/test_review_coverage.py | 77 +++ tests/test_review_receipt_v11.py | 7 +- tests/test_review_receipt_v13.py | 10 +- tests/test_review_runner.py | 339 ++++++++-- ...st_review_runner_publication_boundaries.py | 639 ++++++++++++++++++ tests/test_review_runtime_cleanup.py | 337 +++++++++ tests/test_site_release_notify.py | 144 +++- tests/test_telemetry_metrics.py | 15 + tests/test_telemetry_publications.py | 22 + tests/test_testpypi_preview.py | 4 +- uv.lock | 412 +++++------ 173 files changed, 12082 insertions(+), 1801 deletions(-) create mode 100644 changelog.d/346.maintenance.md create mode 100644 changelog.d/350.security.md create mode 100644 changelog.d/351.bugfix.md create mode 100644 changelog.d/352.feature.md create mode 100644 changelog.d/353.feature.md create mode 100644 changelog.d/354.contributor.md create mode 100644 changelog.d/355.bugfix.md create mode 100644 changelog.d/355.maintenance.md create mode 100644 changelog.d/356.maintenance.md create mode 100644 changelog.d/356.security.md create mode 100644 changelog.d/358.bugfix.md create mode 100644 compatibility/evidence/ocr-1.14.6-local-review.json create mode 100644 compatibility/evidence/ocr-1.14.6.json create mode 100644 docs/contributor-intake.md create mode 100644 src/ocr_toolkit/context/dlp/arithmetic.py create mode 100644 src/ocr_toolkit/context/dlp/provenance.py create mode 100644 src/ocr_toolkit/local_incremental_replay.py create mode 100644 src/ocr_toolkit/review_coverage.py create mode 100644 tests/test_dlp_arithmetic.py create mode 100644 tests/test_dlp_date_ranges.py create mode 100644 tests/test_dlp_publication_edges.py create mode 100644 tests/test_local_incremental_replay.py rename tests/{test_mcp_config_v2.py => test_mcp_config_v3.py} (92%) create mode 100644 tests/test_review_coverage.py create mode 100644 tests/test_review_runner_publication_boundaries.py create mode 100644 tests/test_review_runtime_cleanup.py diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 9d943d8c..ad5f0ee0 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -5,7 +5,7 @@ labels: [bug] body: - type: markdown attributes: - value: Do not include credentials, proprietary source, or private provider payloads. + value: Search existing issues and PRs first. Use a minimal synthetic example. Remove credentials, proprietary source and private provider payloads from every field and attachment. For a suspected vulnerability, use the private reporting link on the issue chooser. - type: input id: version attributes: diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index a605ce59..3f87aa99 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -3,6 +3,9 @@ description: Propose a provider-neutral improvement. title: "[Feature]: " labels: [enhancement] body: + - type: markdown + attributes: + value: Search existing issues and PRs first. Describe a synthetic example and how a maintainer can tell that the proposed behavior works. Report suspected vulnerabilities through the private reporting link on the issue chooser. - type: textarea id: problem attributes: diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 4c27c3bc..f7a92bb7 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,7 +1,11 @@ ## Summary +Link the issue and summarize the change. If AI materially assisted the submission, briefly identify its role and who verified the result. + ## Validation +For a bug fix, confirm the result for the synthetic case in the linked issue. Identify checks still pending. + - [ ] Applicable validation from `docs/development.md` completed; list commands and results below (`scripts/quality.sh check` for implementation/release work, affected existing contracts and semantic review for documentation-only work) - [ ] User-visible change has a Towncrier fragment, or this is classified `no-release` with the reason below - [ ] Examples and fixtures are synthetic diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 4327d9a5..9bd2596a 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -2,6 +2,7 @@ version: 2 updates: - package-ecosystem: uv directory: / + target-branch: dev schedule: interval: monthly day: monday @@ -17,6 +18,7 @@ updates: open-pull-requests-limit: 5 - package-ecosystem: github-actions directory: / + target-branch: dev schedule: interval: monthly day: monday diff --git a/.github/workflows/actions-maintenance.yml b/.github/workflows/actions-maintenance.yml index bf91e0b7..05dbbe83 100644 --- a/.github/workflows/actions-maintenance.yml +++ b/.github/workflows/actions-maintenance.yml @@ -21,6 +21,7 @@ concurrency: jobs: cleanup: name: cleanup-actions-storage + if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest timeout-minutes: 10 permissions: diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f2037aa8..d2d9b655 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -3,7 +3,8 @@ name: Build artifacts on: workflow_dispatch: pull_request: - branches: [main] + branches: [main, dev] + types: [opened, synchronize, reopened, edited, ready_for_review, converted_to_draft] permissions: contents: read @@ -15,6 +16,7 @@ concurrency: jobs: classify: name: classify-documentation + if: github.event_name != 'pull_request' || !github.event.pull_request.draft runs-on: ubuntu-latest timeout-minutes: 5 outputs: @@ -42,8 +44,11 @@ jobs: echo "$result" >> "$GITHUB_OUTPUT" build: - name: build-distributions + name: >- + ${{ github.event_name != 'pull_request' && 'manual-build-distributions' || + github.event.pull_request.draft && 'draft-deferred-build-distributions' || 'build-distributions' }} needs: classify + if: ${{ !cancelled() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }} runs-on: ubuntu-latest timeout-minutes: 15 steps: @@ -52,10 +57,14 @@ jobs: with: fetch-depth: 0 persist-credentials: false - - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 if: needs.classify.outputs.docs_only != 'true' with: - version: "0.13.8" + version: "0.13.10" + require-checksums: true + checksum: bf65ac1a0af10f92c522d91ac096c7c0a39657647b155577e7836c2cbbb4526c + enable-cache: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }} + save-cache: false - if: needs.classify.outputs.docs_only != 'true' run: uv sync --locked - if: needs.classify.outputs.docs_only != 'true' @@ -87,7 +96,9 @@ jobs: /tmp/sdist-smoke/bin/python -m pip check (cd /tmp && env -u PYTHONPATH /tmp/sdist-smoke/bin/python -I "${GITHUB_WORKSPACE}/scripts/installed_runtime_smoke.py") - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - if: needs.classify.outputs.docs_only != 'true' + if: >- + needs.classify.outputs.docs_only != 'true' && + (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) with: name: distributions path: dist/ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4abf64f1..bc5d6ab2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,6 +2,8 @@ name: CI on: pull_request: + branches: [main, dev] + types: [opened, synchronize, reopened, edited, ready_for_review, converted_to_draft] workflow_dispatch: permissions: @@ -41,8 +43,11 @@ jobs: echo "$result" >> "$GITHUB_OUTPUT" test-python312: - name: test-ubuntu-latest-py3.12 + name: >- + ${{ github.event_name != 'pull_request' && 'manual-test-ubuntu-latest-py3.12' || + github.event.pull_request.draft && 'draft-deferred-test-ubuntu-py3.12' || 'test-ubuntu-latest-py3.12' }} needs: classify + if: ${{ !cancelled() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }} runs-on: ubuntu-latest timeout-minutes: 20 env: @@ -53,11 +58,13 @@ jobs: with: fetch-depth: 0 persist-credentials: false - - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 if: needs.classify.outputs.docs_only != 'true' with: - version: "0.13.8" - enable-cache: true + version: "0.13.10" + require-checksums: true + checksum: bf65ac1a0af10f92c522d91ac096c7c0a39657647b155577e7836c2cbbb4526c + enable-cache: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }} save-cache: false - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 if: needs.classify.outputs.docs_only != 'true' @@ -71,7 +78,10 @@ jobs: test-matrix: needs: classify - name: test-${{ matrix.os }}-py${{ matrix.python }} + name: >- + ${{ github.event_name != 'pull_request' && format('manual-test-{0}-py{1}', matrix.os, matrix.python) || + github.event.pull_request.draft && 'draft-deferred-test-matrix' || format('test-{0}-py{1}', matrix.os, matrix.python) }} + if: ${{ !cancelled() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }} continue-on-error: ${{ matrix.advisory }} env: UV_PYTHON: ${{ matrix.python }} @@ -92,11 +102,69 @@ jobs: with: fetch-depth: 0 persist-credentials: false - - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + - name: Install qualified OCR for native coverage + id: native-ocr + if: ${{ needs.classify.outputs.docs_only != 'true' && matrix.coverage }} + env: + PR_BASE: ${{ github.event.pull_request.base.sha }} + shell: bash + run: | + read_native_pin() { + [[ "$1" =~ ^[0-9a-f]{40}$ ]] || return 1 + git --no-replace-objects show "$1:compatibility/ocr-support.json" | + jq -er ' + .recommended_version as $version | + select($version | type == "string" and test("^[0-9]+\\.[0-9]+\\.[0-9]+$")) | + [.releases[] | select(.version == $version)] | + select(length == 1) | .[0] | select(.status == "tested") | + [.assets[] | select(.name == "opencodereview-linux-amd64")] | + select(length == 1) | .[0] | + select(.sha256 | type == "string" and test("^[0-9a-f]{64}$")) | + select(.size | type == "number" and . == floor and . > 0 and . <= 67108864) | + [$version, .sha256, .size] | @tsv + ' + } + if [[ "${GITHUB_EVENT_NAME}" == pull_request ]]; then + pin=$(read_native_pin "${PR_BASE}") + else + pin=$(read_native_pin "${GITHUB_SHA}") + fi + read -r version digest size <<< "${pin}" + umask 077 + directory=$(mktemp -d "${RUNNER_TEMP}/ocr-coverage.XXXXXXXX") + name=opencodereview-linux-amd64 + binary="${directory}/${name}" + url="https://github.com/alibaba/open-code-review/releases/download/v${version}/${name}" + final_url=$(curl --fail --silent --show-error --location \ + --proto '=https' --proto-redir '=https' --connect-timeout 10 --max-time 120 \ + --retry 2 --retry-max-time 120 --max-filesize "${size}" --output "${binary}" \ + --write-out '%{url_effective}' "${url}") + case "${final_url}" in + https://github.com/*|https://objects.githubusercontent.com/*|https://release-assets.githubusercontent.com/*) ;; + *) echo "Unexpected OCR release asset origin." >&2; exit 1 ;; + esac + test "$(wc -c < "${binary}")" -eq "${size}" + actual_digest=$(sha256sum < "${binary}") + if [[ "${actual_digest%% *}" != "${digest}" ]]; then + echo "OCR release asset digest does not match the reviewed pin." >&2 + exit 1 + fi + chmod 0500 "${binary}" + printf 'binary=%s\n' "${binary}" >> "${GITHUB_OUTPUT}" + - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 if: needs.classify.outputs.docs_only != 'true' with: - version: "0.13.8" - enable-cache: true + version: "0.13.10" + require-checksums: true + checksum: >- + ${{ fromJSON('{ + "Linux": {"X64": "bf65ac1a0af10f92c522d91ac096c7c0a39657647b155577e7836c2cbbb4526c"}, + "macOS": { + "ARM64": "e419bf07533bdbf48795fc793601c834dd79db57a8c49ce8e25cfe3a8639958d", + "X64": "153e03197588204c04fc4c81cc4bafbfa4280222a385e4ee36a87aeec0ae63b4" + } + }')[runner.os][runner.arch] }} + enable-cache: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }} save-cache: false - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 if: needs.classify.outputs.docs_only != 'true' @@ -109,6 +177,9 @@ jobs: run: uv run --no-sync pytest -q --ignore=tests/test_installed_policy_e2e.py - name: Test with boundary coverage gates if: ${{ needs.classify.outputs.docs_only != 'true' && matrix.coverage }} + env: + OCR_FEDERATION_QUALIFY_BINARY: ${{ steps.native-ocr.outputs.binary }} + OCR_GITLINK_QUALIFY_BINARY: ${{ steps.native-ocr.outputs.binary }} run: | uv run --no-sync pytest --ignore=tests/test_installed_policy_e2e.py --cov=ocr_toolkit --cov-report=term-missing --cov-fail-under=88 uv run --no-sync coverage report --include=src/ocr_toolkit/ocr_result.py,src/ocr_toolkit/preflight.py --fail-under=85 @@ -130,8 +201,11 @@ jobs: done quality: - name: quality + name: >- + ${{ github.event_name != 'pull_request' && 'manual-quality' || + github.event.pull_request.draft && 'draft-quality' || 'quality' }} needs: classify + if: ${{ !cancelled() }} runs-on: ubuntu-latest steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -139,10 +213,14 @@ jobs: with: fetch-depth: 0 persist-credentials: false - - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 if: needs.classify.outputs.docs_only != 'true' with: - version: "0.13.8" + version: "0.13.10" + require-checksums: true + checksum: bf65ac1a0af10f92c522d91ac096c7c0a39657647b155577e7836c2cbbb4526c + enable-cache: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }} + save-cache: false - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 if: needs.classify.outputs.docs_only != 'true' with: diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 4af71285..0b189a88 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -2,7 +2,8 @@ name: CodeQL on: pull_request: - branches: [main] + branches: [main, dev] + types: [opened, synchronize, reopened, edited, ready_for_review, converted_to_draft] schedule: - cron: "29 3 * * 2" workflow_dispatch: @@ -16,9 +17,15 @@ concurrency: jobs: analyze: - name: analyze-python - if: github.event.repository.private == false + name: >- + ${{ github.event_name != 'pull_request' && 'non-pr-analyze-python' || + github.event.pull_request.draft && 'draft-deferred-analyze-python' || 'analyze-python' }} + if: >- + github.event.repository.private == false && + (github.event_name != 'pull_request' || !github.event.pull_request.draft) && + (github.event_name != 'workflow_dispatch' || github.ref == 'refs/heads/main') runs-on: ubuntu-latest + timeout-minutes: 20 env: # CodeQL v4 controls overlay database caching separately from TRAP caching. # A full database is cheap for this repository and avoids per-run overlay caches. @@ -30,8 +37,11 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + - uses: github/codeql-action/init@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5 with: languages: python trap-caching: false - - uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + - uses: github/codeql-action/analyze@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5 + with: + upload: always + upload-database: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }} diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml index 40a88fe6..070c1bbd 100644 --- a/.github/workflows/dependency-review.yml +++ b/.github/workflows/dependency-review.yml @@ -2,6 +2,8 @@ name: Dependency review on: pull_request: + branches: [main, dev] + types: [opened, synchronize, reopened, edited, ready_for_review, converted_to_draft] permissions: contents: read @@ -12,13 +14,14 @@ concurrency: jobs: review: - name: dependency-review + name: ${{ github.event.pull_request.draft && 'draft-dependency-review' || 'dependency-review' }} if: github.event.repository.private == false runs-on: ubuntu-latest + timeout-minutes: 10 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0 + - uses: actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec # v5.0.1 with: fail-on-severity: moderate diff --git a/.github/workflows/ocr-compatibility.yml b/.github/workflows/ocr-compatibility.yml index 4e96d0e7..ebd9ae4c 100644 --- a/.github/workflows/ocr-compatibility.yml +++ b/.github/workflows/ocr-compatibility.yml @@ -30,14 +30,32 @@ concurrency: cancel-in-progress: false jobs: + reject-ref: + name: Reject compatibility dispatch outside main + if: github.event_name == 'workflow_dispatch' && github.ref != 'refs/heads/main' + runs-on: ubuntu-latest + timeout-minutes: 2 + permissions: {} + steps: + - run: | + echo "Run OCR compatibility from the main branch." >&2 + exit 1 + discover: name: discover-stable-releases + if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest timeout-minutes: 5 outputs: count: ${{ steps.matrix.outputs.count }} matrix: ${{ steps.matrix.outputs.matrix }} steps: + - name: Require the exact main ref + run: | + if [ "${GITHUB_REF}" != refs/heads/main ]; then + echo "Run OCR compatibility from the main branch." >&2 + exit 1 + fi - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false @@ -121,10 +139,12 @@ jobs: fetch-depth: 0 persist-credentials: false - id: setup_uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 continue-on-error: true with: - version: "0.13.8" + version: "0.13.10" + require-checksums: true + checksum: bf65ac1a0af10f92c522d91ac096c7c0a39657647b155577e7836c2cbbb4526c enable-cache: true save-cache: false - id: setup_python @@ -181,7 +201,7 @@ jobs: issues: write name: assess-complete-chain needs: [discover, qualify] - if: ${{ !cancelled() && needs.discover.result == 'success' && needs.discover.outputs.count != '0' }} + if: ${{ !cancelled() && github.ref == 'refs/heads/main' && needs.discover.result == 'success' && needs.discover.outputs.count != '0' }} runs-on: ubuntu-latest timeout-minutes: 10 steps: @@ -206,15 +226,21 @@ jobs: RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | printf '%s\n' "${EXPECTED_MATRIX}" > /tmp/ocr-matrix.json + assessment_status=0 PYTHONPATH=src python scripts/ocr_compat.py assess-matrix \ --matrix /tmp/ocr-matrix.json --artifacts /tmp/ocr-chain --head "${GITHUB_SHA}" \ --after-tag "${AFTER_TAG}" --issue-repository "${GITHUB_REPOSITORY}" --run-url "${RUN_URL}" \ - --output /tmp/ocr-chain-assessment.json | tee -a "${GITHUB_STEP_SUMMARY}" + --output /tmp/ocr-chain-assessment.json | tee -a "${GITHUB_STEP_SUMMARY}" || assessment_status=$? + if [ "${assessment_status}" -ne 0 ] && [ ! -s /tmp/ocr-chain-assessment.json ]; then + exit "${assessment_status}" + fi classification=$(python -c 'import json; print(json.load(open("/tmp/ocr-chain-assessment.json"))["classification"])') target=$(python -c 'import json; print(json.load(open("/tmp/ocr-chain-assessment.json"))["target_version"])') echo "classification=${classification}" >>"${GITHUB_OUTPUT}" echo "target=${target}" >>"${GITHUB_OUTPUT}" + exit "${assessment_status}" - name: Prepare one cumulative automatic-safe patch + id: patch if: needs.qualify.result == 'success' && github.ref == 'refs/heads/main' && !inputs.qualification_only && steps.chain.outputs.classification == 'automatic-safe' env: TARGET_VERSION: ${{ steps.chain.outputs.target }} @@ -238,6 +264,7 @@ jobs: git diff --binary >"/tmp/ocr-chain-update.patch" test -s /tmp/ocr-chain-update.patch - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + id: upload_chain if: ${{ !cancelled() && steps.chain.outcome != 'skipped' }} with: name: ocr-compatibility-chain @@ -246,40 +273,22 @@ jobs: /tmp/ocr-chain-update.patch if-no-files-found: error retention-days: 2 - - name: Open automatic-safe compatibility PR when bot credential is configured - if: needs.qualify.result == 'success' && github.ref == 'refs/heads/main' && !inputs.qualification_only && steps.chain.outputs.classification == 'automatic-safe' + - name: Summarize chain and patch outcomes + if: ${{ !cancelled() }} env: - GH_TOKEN: ${{ secrets.OCR_UPDATE_BOT_TOKEN }} - REPOSITORY: ${{ github.repository }} - TARGET_VERSION: ${{ steps.chain.outputs.target }} + CHAIN_OUTCOME: ${{ steps.chain.outcome }} + CHAIN_CLASSIFICATION: ${{ steps.chain.outputs.classification }} + CANDIDATE_OUTCOME: ${{ needs.qualify.result }} + QUALIFICATION_ONLY: ${{ inputs.qualification_only || false }} + PATCH_OUTCOME: ${{ steps.patch.outcome }} + ARTIFACT_OUTCOME: ${{ steps.upload_chain.outcome }} run: | - if [ -z "${GH_TOKEN}" ]; then - echo "OCR_UPDATE_BOT_TOKEN is not configured; patch artifact and issue are the resume path." - exit 0 - fi - version=${TARGET_VERSION} - branch="automation/ocr-${version}" - bot_login=$(gh api user --jq .login) - if [ "${bot_login}" = "github-actions[bot]" ]; then - echo "OCR_UPDATE_BOT_TOKEN must identify a non-Actions bot so PR workflows run." >&2 - exit 1 - fi - git config user.name "OCR compatibility automation" - git config user.email "ocr-compatibility@users.noreply.github.com" - gh auth setup-git - git fetch origin "${branch}" || true - git switch -C "${branch}" "${GITHUB_SHA}" - git add compatibility/ocr-support.json compatibility/evidence/ \ - src/ocr_toolkit/preflight.py src/ocr_toolkit/_qualified_handoffs.json examples/gitlab/ocr-review.gitlab-ci.yml \ - changelog.d/ - git commit -m "Target OCR ${version}" - git push --force-with-lease="${branch}" origin "${branch}" - existing=$(gh pr list --repo "${REPOSITORY}" --state open --head "${branch}" --json number --jq '.[0].number // empty') - if [ -z "${existing}" ]; then - gh pr create --repo "${REPOSITORY}" \ - --base main \ - --head "${branch}" \ - --title "Target OCR ${version}" \ - --label dependencies \ - --body "Checksum-verified automatic-safe OCR compatibility update. Machine evidence and the exact generated patch are attached to workflow run ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}. This PR does not publish a release; merge remains subject to every protected check and the separate stable release workflow." - fi + { + printf '\n### Release chain and patch\n\n' + printf -- '- Chain assessment: `%s`\n' "${CHAIN_OUTCOME}" + printf -- '- Aggregate classification: `%s`\n' "${CHAIN_CLASSIFICATION:-unavailable}" + printf -- '- Candidate jobs: `%s`\n' "${CANDIDATE_OUTCOME}" + printf -- '- Qualification only: `%s`\n' "${QUALIFICATION_ONLY}" + printf -- '- Patch generation: `%s`\n' "${PATCH_OUTCOME}" + printf -- '- Chain artifact upload: `%s`\n' "${ARTIFACT_OUTCOME}" + } >> "${GITHUB_STEP_SUMMARY}" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 12aa0d57..8cb9f5bb 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -61,6 +61,8 @@ jobs: needs: classify if: >- github.event.repository.private == false && + github.ref == 'refs/heads/main' && + (github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && needs.classify.outputs.release == 'true' runs-on: ubuntu-latest timeout-minutes: 5 @@ -81,6 +83,55 @@ jobs: tree: ${{ steps.authorize.outputs.tree }} version: ${{ steps.authorize.outputs.version }} steps: + - name: Load the pinned main history for recovery + if: github.event_name == 'workflow_dispatch' + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + path: dispatch-main + fetch-depth: 0 + persist-credentials: false + - name: Verify the historical recovery policy reference before checkout + if: github.event_name == 'workflow_dispatch' + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ inputs['pull-request-number'] }} + VERSION: ${{ inputs.version }} + MERGE: ${{ inputs['merge-commit'] }} + HEAD: ${{ inputs['reviewed-head'] }} + BASE: ${{ inputs['reviewed-base'] }} + shell: bash + run: | + [[ "${PR_NUMBER}" =~ ^[1-9][0-9]*$ && "${VERSION}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] + [[ "${MERGE}" =~ ^[0-9a-f]{40}$ && "${HEAD}" =~ ^[0-9a-f]{40}$ && "${BASE}" =~ ^[0-9a-f]{40}$ ]] + [[ "${GITHUB_SHA}" =~ ^[0-9a-f]{40}$ ]] + export GIT_NO_REPLACE_OBJECTS=1 + test "$(git -C dispatch-main rev-parse HEAD)" = "${GITHUB_SHA}" + if ! git -C dispatch-main rev-list --first-parent "${GITHUB_SHA}" | + awk -v merge="${MERGE}" '$0 == merge { found = 1 } END { exit !found }'; then + echo "release merge is outside the dispatch main first-parent history" >&2 + exit 1 + fi + read_github_metadata() { + curl --fail --silent --show-error --proto '=https' \ + --connect-timeout 10 --max-time 30 --max-filesize 1048576 \ + --header 'Accept: application/vnd.github+json' \ + --header 'X-GitHub-Api-Version: 2026-03-10' \ + --oauth2-bearer "${GH_TOKEN}" \ + "https://api.github.com/repos/${GITHUB_REPOSITORY}/$1" + } + read_github_metadata "pulls/${PR_NUMBER}" | + jq -e --arg repo "${GITHUB_REPOSITORY}" --argjson number "${PR_NUMBER}" \ + --arg version "${VERSION}" --arg head "${HEAD}" --arg merge "${MERGE}" --arg base "${BASE}" ' + .number == $number and .merged == true and .merge_commit_sha == $merge and + .base.repo.full_name == $repo and .base.ref == "main" and .base.sha == $base and + .head.repo.full_name == $repo and .head.ref == ("release/v" + $version) and + .head.sha == $head and .title == ("Release v" + $version) + ' >/dev/null + read_github_metadata "git/commits/${MERGE}" | + jq -e --arg merge "${MERGE}" --arg base "${BASE}" ' + .sha == $merge and (.parents | length) == 1 and .parents[0].sha == $base + ' >/dev/null - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: # Authorization code must come from protected policy that predates the @@ -201,9 +252,11 @@ jobs: ref: ${{ needs.authorize.outputs.commit }} fetch-depth: 0 persist-credentials: false - - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 with: - version: "0.13.8" + version: "0.13.10" + require-checksums: true + checksum: bf65ac1a0af10f92c522d91ac096c7c0a39657647b155577e7836c2cbbb4526c - run: uv sync --locked - id: validate name: Validate the authorized release merge @@ -522,6 +575,7 @@ jobs: name: reviewed-release-distributions path: . - name: Publish tag and GitHub Release + id: publish env: EXPECTED_COMMIT: ${{ needs.authorize.outputs.commit }} EXPECTED_BASE: ${{ needs.authorize.outputs.base }} @@ -613,6 +667,7 @@ jobs: /tmp/github-release-upload-assets.json) case "${receipt_count}" in 0) + receipt_mode=created test "${release_is_draft}" = true || { echo "published GitHub Release is missing its receipt" >&2 exit 1 @@ -634,6 +689,7 @@ jobs: --output release-receipt.json ;; 1) + receipt_mode=reused bounded_release_download release-receipt.json release-receipt.json 1048576 python scripts/release_receipt.py \ --version "${VERSION}" \ @@ -648,6 +704,11 @@ jobs: --hashes artifact-hashes.json \ --runtime-requirements runtime-requirements.txt \ --validate-existing release-receipt.json + if [[ "${GITHUB_EVENT_NAME}" == pull_request ]] && + ! jq -e --argjson run "${GITHUB_RUN_ID}" '.workflow.run_id == $run' release-receipt.json >/dev/null; then + echo "This receipt was created by another run. Use the main-branch release recovery dispatch." >&2 + exit 1 + fi ;; *) echo "duplicate GitHub Release receipt asset" >&2; exit 1 ;; esac @@ -785,3 +846,17 @@ jobs: done <> "${GITHUB_OUTPUT}" + echo "receipt_sha=${receipt_sha}" >> "${GITHUB_OUTPUT}" + echo "receipt_mode=${receipt_mode}" >> "${GITHUB_OUTPUT}" + # The notifier reads this exact completion step through the jobs API for + # the triggering attempt. The digest also binds an existing recovery receipt. + - name: Site release receipt ${{ steps.publish.outputs.site_tag }} ${{ steps.publish.outputs.receipt_sha }} ${{ steps.publish.outputs.receipt_mode }} + env: + TAG: ${{ steps.publish.outputs.site_tag }} + RECEIPT_SHA: ${{ steps.publish.outputs.receipt_sha }} + RECEIPT_MODE: ${{ steps.publish.outputs.receipt_mode }} + shell: bash + run: | + [[ "${TAG}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ && "${RECEIPT_SHA}" =~ ^[0-9a-f]{64}$ ]] + [[ "${RECEIPT_MODE}" == created || "${RECEIPT_MODE}" == reused ]] diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index e79c808b..51282d7a 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -18,8 +18,9 @@ concurrency: jobs: analysis: name: analyze-supply-chain - if: github.event.repository.private == false + if: github.event.repository.private == false && github.ref == 'refs/heads/main' runs-on: ubuntu-latest + timeout-minutes: 15 permissions: security-events: write # Upload Scorecard SARIF to code scanning. id-token: write # Publish signed Scorecard results. @@ -28,11 +29,11 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0 + - uses: ossf/scorecard-action@23f22cd43608bae7a1f1fa2603d7314dee9538a5 # v2.6.0 with: results_file: results.sarif results_format: sarif publish_results: true - - uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + - uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5 with: sarif_file: results.sarif diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 5a143aca..fbaec132 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -2,6 +2,8 @@ name: Security on: pull_request: + branches: [main, dev] + types: [opened, synchronize, reopened, edited, ready_for_review, converted_to_draft] schedule: - cron: "17 4 * * 1" workflow_dispatch: @@ -16,6 +18,7 @@ concurrency: jobs: classify: name: classify-documentation + if: github.event_name != 'pull_request' || !github.event.pull_request.draft runs-on: ubuntu-latest timeout-minutes: 5 outputs: @@ -43,8 +46,11 @@ jobs: echo "$result" >> "$GITHUB_OUTPUT" sast-bandit: - name: sast-bandit + name: >- + ${{ github.event_name != 'pull_request' && 'non-pr-sast-bandit' || + github.event.pull_request.draft && 'draft-deferred-sast-bandit' || 'sast-bandit' }} needs: classify + if: ${{ !cancelled() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }} runs-on: ubuntu-latest timeout-minutes: 10 steps: @@ -52,45 +58,89 @@ jobs: if: needs.classify.outputs.docs_only != 'true' with: persist-credentials: false - - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 if: needs.classify.outputs.docs_only != 'true' with: - version: "0.13.8" + version: "0.13.10" + require-checksums: true + checksum: bf65ac1a0af10f92c522d91ac096c7c0a39657647b155577e7836c2cbbb4526c + enable-cache: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }} + save-cache: false - if: needs.classify.outputs.docs_only != 'true' run: ./scripts/quality.sh security dependency-audit: - name: dependency-audit + name: >- + ${{ github.event_name != 'pull_request' && 'non-pr-dependency-audit' || + github.event.pull_request.draft && 'draft-deferred-dependency-audit' || 'dependency-audit' }} needs: classify + if: ${{ !cancelled() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }} runs-on: ubuntu-latest + timeout-minutes: 10 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 if: needs.classify.outputs.docs_only != 'true' with: persist-credentials: false - - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 if: needs.classify.outputs.docs_only != 'true' with: - version: "0.13.8" + version: "0.13.10" + require-checksums: true + checksum: bf65ac1a0af10f92c522d91ac096c7c0a39657647b155577e7836c2cbbb4526c + enable-cache: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }} + save-cache: false - if: needs.classify.outputs.docs_only != 'true' run: ./scripts/dependency-audit.sh secrets: - name: secrets + name: >- + ${{ github.event_name != 'pull_request' && 'non-pr-secrets' || + github.event.pull_request.draft && 'draft-secrets' || 'secrets' }} runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: read # Gitleaks reads PR refs; comments are disabled. + timeout-minutes: 10 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: + # Scan candidate history as Git objects while keeping the base scanner + # policy and checkout. Gitleaks reads config and ignores from its source. + ref: ${{ github.event.pull_request.base.sha || github.sha }} fetch-depth: 0 persist-credentials: false - - name: Load pinned Gitleaks version + - name: Install checksum-pinned Gitleaks without a cache run: | - version=$(./scripts/gitleaks.sh --version) - echo "GITLEAKS_VERSION=${version}" >> "${GITHUB_ENV}" - - uses: gitleaks/gitleaks-action@e0c47f4f8be36e29cdc102c57e68cb5cbf0e8d1e # v3.0.0 + version=$(sed -n 's/^GITLEAKS_VERSION=\([0-9][0-9.]*\)$/\1/p' scripts/gitleaks.sh) + # Keep the reviewed checksum for each active target's base pin during upgrades. + case "${version}" in + 8.30.1) digest=551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb ;; + *) echo "Gitleaks version has no reviewed Linux x64 checksum" >&2; exit 1 ;; + esac + archive="gitleaks_${version}_linux_x64.tar.gz" + curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' \ + --retry 3 --max-time 60 --output "${RUNNER_TEMP}/${archive}" \ + "https://github.com/gitleaks/gitleaks/releases/download/v${version}/${archive}" + cd "${RUNNER_TEMP}" + printf '%s %s\n' "${digest}" "${archive}" | sha256sum --check --strict + tar -xzf "${archive}" gitleaks + test "$(./gitleaks version)" = "${version}" + - name: Scan immutable Git history env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GITLEAKS_ENABLE_COMMENTS: "false" + PR_BASE: ${{ github.event.pull_request.base.sha }} + PR_HEAD: ${{ github.event.pull_request.head.sha }} + PR_NUMBER: ${{ github.event.pull_request.number }} + shell: bash + run: | + scan_args=(--redact=100 --exit-code=1 --log-level=warn) + if [[ "${GITHUB_EVENT_NAME}" == pull_request ]]; then + [[ "${PR_BASE}" =~ ^[0-9a-f]{40}$ && "${PR_HEAD}" =~ ^[0-9a-f]{40}$ ]] + [[ "${PR_NUMBER}" =~ ^[1-9][0-9]*$ ]] + test "$(git rev-parse HEAD)" = "${PR_BASE}" + git fetch --no-tags --recurse-submodules=no origin "refs/pull/${PR_NUMBER}/head" + if [[ "$(git rev-parse FETCH_HEAD)" != "${PR_HEAD}" ]]; then + echo "PR head moved after this event. Check the latest PR run." >&2 + exit 1 + fi + options="--no-ext-diff --no-textconv --diff-merges=first-parent ${PR_BASE}..${PR_HEAD}" + scan_args+=(--ignore-gitleaks-allow "--log-opts=${options}") + fi + "${RUNNER_TEMP}/gitleaks" git "${scan_args[@]}" . diff --git a/.github/workflows/site-release-notify.yml b/.github/workflows/site-release-notify.yml index 32923c10..4c23003c 100644 --- a/.github/workflows/site-release-notify.yml +++ b/.github/workflows/site-release-notify.yml @@ -5,23 +5,30 @@ on: workflows: [Release] types: [completed] -permissions: - actions: read - contents: read +permissions: {} concurrency: group: toolkit-site-release-notify cancel-in-progress: false jobs: - notify: - name: notify-site-after-immutable-release + verify: + name: verify-immutable-release if: >- github.repository == 'xeonvs/open-code-review-toolkit' && + github.ref == 'refs/heads/main' && + github.event.workflow_run.repository.full_name == github.repository && + github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.conclusion == 'success' && - github.event.workflow_run.event != 'workflow_run' + ((github.event.workflow_run.event == 'pull_request' && startsWith(github.event.workflow_run.head_branch, 'release/v')) || + (github.event.workflow_run.event == 'workflow_dispatch' && github.event.workflow_run.head_branch == 'main')) runs-on: ubuntu-latest timeout-minutes: 5 + permissions: + actions: read + contents: read + outputs: + release_tag: ${{ steps.release.outputs.release_tag }} steps: # workflow_run has privileged credentials. Never check out or execute the # release run's head; inspect only GitHub-owned metadata and immutable data. @@ -32,12 +39,16 @@ jobs: SOURCE_RUN_ID: ${{ github.event.workflow_run.id }} SOURCE_RUN_ATTEMPT: ${{ github.event.workflow_run.run_attempt }} SOURCE_WORKFLOW_ID: ${{ github.event.workflow_run.workflow_id }} + SOURCE_HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + SOURCE_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }} + SOURCE_EVENT: ${{ github.event.workflow_run.event }} shell: bash run: | set -euo pipefail [[ "${SOURCE_RUN_ID}" =~ ^[1-9][0-9]*$ ]] [[ "${SOURCE_RUN_ATTEMPT}" =~ ^[1-9][0-9]*$ ]] [[ "${SOURCE_WORKFLOW_ID}" =~ ^[1-9][0-9]*$ ]] + [[ "${SOURCE_HEAD_SHA}" =~ ^[0-9a-f]{40}$ ]] gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/release.yml" \ > "${RUNNER_TEMP}/release-workflow.json" @@ -49,15 +60,19 @@ jobs: for attempt in 1 2 3 4 5 6; do gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${SOURCE_RUN_ID}/attempts/${SOURCE_RUN_ATTEMPT}/jobs?per_page=100" \ > "${RUNNER_TEMP}/release-jobs.json" - jq -e ' - (.total_count | type == "number" and . > 0 and . <= 100) and - (.jobs | type) == "array" and (.jobs | length) == .total_count and - ([.jobs[] | select(.name == "publish-github-release")] | length == 1) - ' "${RUNNER_TEMP}/release-jobs.json" >/dev/null - publish_status=$(jq -r '[.jobs[] | select(.name == "publish-github-release")][0].status' \ - "${RUNNER_TEMP}/release-jobs.json") - publish_conclusion=$(jq -r '[.jobs[] | select(.name == "publish-github-release")][0].conclusion' \ - "${RUNNER_TEMP}/release-jobs.json") + publish_job=$(jq -ec --argjson id "${SOURCE_RUN_ID}" \ + --argjson attempt "${SOURCE_RUN_ATTEMPT}" --arg sha "${SOURCE_HEAD_SHA}" ' + select((.total_count | type == "number" and . > 0 and . <= 100) and + (.jobs | type) == "array" and (.jobs | length) == .total_count) | + [.jobs[] | select(.name == "publish-github-release")] | + select(length == 1) | .[0] | + select(.run_id == $id and .run_attempt == $attempt and .head_sha == $sha) + ' "${RUNNER_TEMP}/release-jobs.json") || { + echo 'Expected one publication job for the triggering run and attempt.' >&2 + exit 1 + } + publish_status=$(jq -r '.status' <<< "${publish_job}") + publish_conclusion=$(jq -r '.conclusion' <<< "${publish_job}") if [[ "${publish_status}" == completed ]]; then break fi @@ -79,38 +94,81 @@ jobs: echo 'Release publication job was not successful.' >&2 exit 1 fi + marker=$(jq -er ' + [.steps[] | select(.name | startswith("Site release receipt "))] | + select(length == 1) | .[0] | + select(.status == "completed" and .conclusion == "success") | + .name | select(test("^Site release receipt v[0-9]+\\.[0-9]+\\.[0-9]+ [0-9a-f]{64} (created|reused)$")) + ' <<< "${publish_job}") || { + echo 'Publication job has no unique successful site receipt step.' >&2 + exit 1 + } + read -r _ _ _ expected_tag expected_digest receipt_mode <<< "${marker}" + case "${SOURCE_EVENT}" in + pull_request) test "${SOURCE_HEAD_BRANCH}" = "release/${expected_tag}" ;; + workflow_dispatch) test "${SOURCE_HEAD_BRANCH}" = main ;; + *) exit 1 ;; + esac - gh api "repos/${GITHUB_REPOSITORY}/releases/latest" \ + gh api -H 'X-GitHub-Api-Version: 2026-03-10' "repos/${GITHUB_REPOSITORY}/releases/latest" \ > "${RUNNER_TEMP}/latest-release.json" - jq -e ' + jq -e --arg tag "${expected_tag}" ' .immutable == true and .draft == false and .prerelease == false and (.published_at | type == "string" and length > 0) and - (.tag_name | type == "string" and test("^v[0-9]+\\.[0-9]+\\.[0-9]+$")) and - ([.assets[] | select(.name == "release-receipt.json" and .state == "uploaded" and - (.size | type == "number" and . > 0 and . <= 1048576))] | length == 1) - ' "${RUNNER_TEMP}/latest-release.json" >/dev/null - tag=$(jq -r .tag_name "${RUNNER_TEMP}/latest-release.json") - receipt_asset_id=$(jq -r \ - '.assets[] | select(.name == "release-receipt.json") | .id' \ - "${RUNNER_TEMP}/latest-release.json") + .tag_name == $tag + ' "${RUNNER_TEMP}/latest-release.json" >/dev/null || { + echo 'Latest immutable stable Release does not match the publication job tag.' >&2 + exit 1 + } + receipt_asset=$(jq -ec ' + [.assets[] | select(.name == "release-receipt.json")] | + select(length == 1) | .[0] | + select(.state == "uploaded" and (.size | type == "number" and . == floor and . > 0 and . <= 1048576)) + ' "${RUNNER_TEMP}/latest-release.json") + receipt_asset_id=$(jq -r .id <<< "${receipt_asset}") [[ "${receipt_asset_id}" =~ ^[1-9][0-9]*$ ]] gh api -H 'Accept: application/octet-stream' \ - "repos/${GITHUB_REPOSITORY}/releases/assets/${receipt_asset_id}" \ + "repos/${GITHUB_REPOSITORY}/releases/assets/${receipt_asset_id}" | head -c 1048577 \ > "${RUNNER_TEMP}/release-receipt.json" - jq -e --arg tag "${tag}" ' + test "$(wc -c < "${RUNNER_TEMP}/release-receipt.json")" -eq "$(jq -r .size <<< "${receipt_asset}")" + actual_digest=$(sha256sum < "${RUNNER_TEMP}/release-receipt.json") + if [[ "${actual_digest%% *}" != "${expected_digest}" ]]; then + echo 'Immutable receipt digest does not match the publication job.' >&2 + exit 1 + fi + jq -e --arg tag "${expected_tag}" --arg mode "${receipt_mode}" \ + --arg event "${SOURCE_EVENT}" --arg head "${SOURCE_HEAD_SHA}" \ + --argjson id "${SOURCE_RUN_ID}" --argjson attempt "${SOURCE_RUN_ATTEMPT}" ' + def positive_integer: type == "number" and . == floor and . > 0; .schema_version == "ocr-toolkit.release-receipt/v2" and .tag == $tag and .version == ($tag | ltrimstr("v")) and - (.workflow.run_id | type == "number" and . > 0) and - (.workflow.run_attempt | type == "number" and . > 0) + (.reviewed.merge | type == "string" and test("^[0-9a-f]{40}$")) and + .github.annotated_tag_target == .reviewed.merge and + ($event != "pull_request" or .reviewed.head == $head) and + (.workflow.run_id | positive_integer) and (.workflow.run_attempt | positive_integer) and + (if $mode == "created" then + .workflow.run_id == $id and .workflow.run_attempt == $attempt + elif .workflow.run_id == $id then + .workflow.run_attempt <= $attempt + else + $event == "workflow_dispatch" + end) ' "${RUNNER_TEMP}/release-receipt.json" >/dev/null - echo "release_tag=${tag}" >> "${GITHUB_OUTPUT}" + echo "release_tag=${expected_tag}" >> "${GITHUB_OUTPUT}" + notify: + name: notify-site-after-immutable-release + needs: verify + if: github.ref == 'refs/heads/main' && needs.verify.outputs.release_tag != '' + runs-on: ubuntu-latest + timeout-minutes: 5 + environment: site-release-notification + steps: - name: Request site refresh - if: steps.release.outputs.release_tag != '' env: GH_TOKEN: ${{ secrets.OCR_SITE_DISPATCH_TOKEN }} - RELEASE_TAG: ${{ steps.release.outputs.release_tag }} + RELEASE_TAG: ${{ needs.verify.outputs.release_tag }} shell: bash run: | set -euo pipefail diff --git a/.github/workflows/testpypi.yml b/.github/workflows/testpypi.yml index 548c7c5e..65984d40 100644 --- a/.github/workflows/testpypi.yml +++ b/.github/workflows/testpypi.yml @@ -49,9 +49,11 @@ jobs: with: fetch-depth: 0 persist-credentials: false - - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 with: - version: "0.13.8" + version: "0.13.10" + require-checksums: true + checksum: bf65ac1a0af10f92c522d91ac096c7c0a39657647b155577e7836c2cbbb4526c - id: preview name: Resolve deterministic development version run: | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bdedd764..568f6565 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,13 +4,25 @@ Thank you for improving Open Code Review Toolkit. Keep changes focused, add regr Participation in this project is governed by the [Code of Conduct](CODE_OF_CONDUCT.md). Report conduct incidents through its private enforcement route rather than a public issue. -1. Create a branch from `main`. -2. Install the locked development environment with `uv sync --frozen`. -3. Maintain `PLANS.md` using the [canonical planning workflow](docs/development.md#planning-and-documentation-lifecycle). -4. Add a Towncrier fragment for user-visible changes. -5. Run the checks in [docs/development.md](docs/development.md). -6. Open a pull request; protected `main` accepts changes only through green pull requests. - -Development publication follows the [release classification](docs/release.md): internal CI and test-only changes do not automatically publish artifacts. Stable releases use a repository-owned `release/vX.Y.Z` branch and an exact `Release vX.Y.Z` pull-request title; merging that reviewed PR authorizes the automated TestPyPI, PyPI, and GitHub Release chain. +1. Search open and closed issues and PRs for the same problem. For a bug or feature, use the existing issue or open one before submitting a patch. Put the expected and observed behavior, minimal synthetic input, or feature acceptance criteria there. For a suspected vulnerability, use [private reporting](SECURITY.md) from the start. A small editorial correction or automated dependency update can use the PR alone. +2. Fork the repository and create a topic branch from the current intake branch. During the transition to protected `dev`, use `main` until a maintainer opens `dev` for contributions. Maintainers can retarget existing PRs after the new branch checks are operational. [Protected contributor intake](docs/contributor-intake.md) +3. Install the locked development environment with `uv sync --frozen`. +4. Follow the [planning workflow](docs/development.md#planning-and-documentation-lifecycle). Maintainers own the shared release plan and reconcile accepted external work there. +5. Add a Towncrier fragment for user-visible changes and run the [applicable checks](docs/development.md). +6. Link the issue in the PR and describe what changed, the tests you ran and their results, including any failures or skips. Use ordinary issue references for work tracked through stable delivery. A maintainer reviews the current revision before approving fork CI. + +## AI-assisted contributions + +We welcome AI-assisted changes. When an agent materially helped write the patch, tests or analysis, mention its role briefly in the PR description. A human submitter or sponsor should read the complete diff, verify the behavior, explain the design and respond to review. Keep prompts, private logs and credentials out of the submission. + +For broad changes, discuss the intended scope on the issue before generating a series of PRs. Link the original work when adapting someone else's patch, preserve authorship and check its license. Keep follow-up fixes on the original PR so reviewers can compare revisions. + +## Dependencies and workflow actions + +Before pushing, follow the [dependency and action checks](docs/development.md#dependency-audit-before-push). Maintainers and the repository's configured Dependabot integration own dependency additions, upgrades, removals and changes to their sources or integrity pins. This includes transitive lockfile edits and GitHub Actions references. If your change needs one, explain the requirement in the issue or PR so a maintainer can prepare the dependency change separately. Report suspected security vulnerabilities through [private vulnerability reporting](SECURITY.md). + +## Release and reporting + +Development publication follows the [release classification](docs/release.md). Stable releases use a repository-owned `release/vX.Y.Z` branch and an exact `Release vX.Y.Z` pull-request title. Merging that reviewed PR authorizes automated publication to TestPyPI, PyPI and GitHub Releases. Do not include real credentials, provider payloads, internal hosts, or private repository details. Security reports should follow [SECURITY.md](SECURITY.md), while conduct incidents follow [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md); neither belongs in a public issue. diff --git a/PLANS.md b/PLANS.md index c4d7255b..fb6894ac 100644 --- a/PLANS.md +++ b/PLANS.md @@ -1,5 +1,160 @@ # Execution Plans +## Active Plan: Toolkit 0.16.1 — contributor intake and incremental review + +plan_schema_version: 2 +Status: active +Release classification: release-required +Target release: 0.16.1 +Next development marker: 0.17.0 +Last Updated: 2026-12-01 + +### Goal + +Deliver the full selected patch release through protected external intake on `dev`, maintainer promotion to `main`, and the existing signed release and receipt process. + +### Plan Origin + +direct_execution + +### Requested Scope + +Review the new contributor's entire repository history, fix incremental qualification and extend safe reuse, integrate the pending dependency and OCR updates, harden contributor CI, update contribution rules for agent-assisted submissions and credit accepted work in the release. + +### Requirement Traceability + +| Requirement | Outcome | Queue | Status | +| --- | --- | --- | --- | +| REQ-001 | Inspect external submissions and observed GitHub disclosure surfaces | WQ-01 | done | +| REQ-002 | Protect dev intake and isolate privileged publication | WQ-02 | in_progress | +| REQ-003 | Qualify #351/#354 and implement #352–353 | WQ-03 | done | +| REQ-004 | Review #346–350 and qualify #355 | WQ-04 | done | +| REQ-005 | Document contribution rules and conditional release credit | WQ-02, WQ-05 | done | +| REQ-006 | Deliver and reconcile 0.16.1 | WQ-06, WQ-08 | pending | +| REQ-007 | Retain proven technical literals during publication and increase default test coverage (#358) | WQ-07 | complete | + +### Explicit Non-Goals + +Prepare protected dev intake and retarget both existing PRs before merge or publication. Keep the contributor’s #354 changes and attribution in the original PR. + +### Constraints + +Inspect fork revisions as data locally. Keep private evidence, credentials, operator inputs and unredacted logs outside public artifacts. Preserve contributor attribution and the stable release authorizer. Review real effective permissions after changes. Keep security reports on the private reporting route. + +### Inputs And Sources + +Use the live [contributor PR](https://github.com/xeonvs/open-code-review-toolkit/pull/354), [CI failure](https://github.com/xeonvs/open-code-review-toolkit/actions/runs/46632932603/job/142597665154), [qualification issue](https://github.com/xeonvs/open-code-review-toolkit/issues/355), all eleven workflows, GitHub Actions settings, rulesets, environments and the repository's development, local review, compatibility and release guides. + +For AI-assisted intake, the September policy study documents substantial variation in disclosure requirements. The October Linux Foundation survey identifies disclosure and contributor responsibility as common practices. GitHub's July workflow holds illustrate why maintainers inspect proposed execution before approval. Adopt a short disclosure and actual verification evidence, with the same security review for all authors. [Policy study](https://arxiv.org/abs/2609.07542), [Linux Foundation research](https://www.linuxfoundation.org/hubfs/Research%20Reports/Navigating-Open-Source-Software-Development-in-the-Generative-AI-Era.pdf), [GitHub July update](https://github.blog/changelog/2026-07-28-github-actions-holds-potentially-malicious-workflows-for-approval/). + +### User Decisions And Answers + +Prepare the full maintainer-owned implementation on `maintainer/0.16.1-intake`, review successive changes incrementally and open a draft. Use an existing issue when available; the issue owns the synthetic case and the PR links it and reports actual validation. Keep suspected vulnerabilities on the private reporting route. + +The owner selected protected `dev → main`, the full release composition, revised contributor rules and a conditional acknowledgment section. Include all currently open maintenance PRs, independently of the human contributor's work. + +REQ-002/004 include the external contribution supply-chain threat model, Docker Hub consumption, mandatory pre-push freshness review and maintainer/Dependabot ownership. At merge the maintainer checks the author and source branch in GitHub and reviews every dependency-related change, including additions, renames/deletions, lock sources, action references and installers. Exercise an ordinary fork PR, a fork changing a pin, a spoofed bot label/name, genuine Dependabot and maintainer updates. WQ-04 includes qualifying and pinning the official Python manifest used by the GitLab example and verifying the supported Linux image and installed toolkit in that environment. Keep monthly refresh ownership explicit; the configured uv and github-actions ecosystems do not update a GitLab YAML image digest. + +The contributor guide and PR template now request material AI disclosure, human verification, existing-PR checks and source attribution. Keep intake open. If overlapping submissions become a problem here, GitHub supports a per-user limit on simultaneous external PRs without granting write access to bypass it. [GitHub June update](https://github.blog/changelog/2026-06-17-limit-open-pull-requests-for-users-without-write-access/). + +### Completed Baseline State + +Current protected main is c5750fd, the v0.16.0 release merge. GitHub reports that release immutable. Remote dev and the new milestone did not exist at inspection. The contributor authored one repository PR (#354) and zero issues across all states. #351–353 belong to the maintainer, #355 to Actions and #346–350 to Dependabot. + +At b93ec7d the three changed files cover local opt-in qualification, its tests and the bugfix fragment. The change accepts two editor settings, still falls back for other unsupported settings and prints their names to stderr. Values are omitted, but arbitrary inherited names can contain private text or control characters and the output has no count or byte bound. Use a closed vocabulary of useful known names plus a generic bounded fallback. Verify the two editor commands never run during qualification or review; prefer removing the unnecessary editor values from the incremental child environment. The follow-up 4b395cbe changes only the unused test binding. + +### Current Work Queue + +| Item | Work and exit evidence | Requirements | Status | +| --- | --- | --- | --- | +| WQ-01 | Inventory submissions, review immutable diff, logs, token permissions, artifacts, CI triggers and settings. Record limits below. | REQ-001 | done | +| WQ-02 | Target the maintainer bootstrap and external PR at protected dev; promote reviewed dev to main. Restrict both publishing environments to branch main only and verify the external Trusted Publishers. Scope site dispatch credentials to the trusted main workflow/environment. Configure approval for all outside collaborators. Set up native GitHub protections and required Build/CodeQL checks on dev. At merge the maintainer verifies external PRs target dev and main receives repository-owned promotions and release PRs. Account explicitly for maintenance bots and bootstrap. Verify the intended review and retargeting paths before retargeting #354. Synchronize contribution guide and template with rollout. | REQ-002, REQ-005 | in_progress | +| WQ-03 | Retarget and review #354 at the new merge base, retain author credit, replace premature issue closing keywords, address diagnostic bounds. #352 uses closed per-group reason counts with overlapping reasons and no paths/arguments. #353 extends file-level reuse to unchanged non-Python blobs and replays bounded deterministic searches on immutable inputs; qualify only complete equivalent observations including dependencies, result order, truncation and failures. Recheck uncertain groups. | REQ-003 | done | +| WQ-04 | Integrate development tooling #346, certifi #347, regex #348, httpx2 #349 and six action updates #350. Check upstream commit identities, permissions, cache defaults and artifact changes before updating action pins. Reconcile overlapping lock changes and test the combined tree. For #355 inspect upstream gitignore/preview semantics, verify exact assets, Linux and applicable native handoffs and consumer behavior before promotion to OCR 1.14.6. | REQ-004 | done | +| WQ-05 | Add conditional Towncrier Contributors category, maintainer-reviewed public handle and accepted PR link once per contributor. Verify populated and empty releases, canonical changelog section and final comparison link. | REQ-005 | done | +| WQ-06 | After WQ-08 passes on the final development head and the maintainer authorizes release, merge the protected promotion, verify TestPyPI on the resulting push to main, then prepare the signed release/v0.16.1 PR and reconcile published artifacts. | REQ-006 | pending | +| WQ-07 | Qualify publication-only DLP handling for date ranges, dated headings and size assignments, retain phone and credential rejection, and integrate #359 through the twelve protected checks. | REQ-007 | complete | +| WQ-08 | Complete private corrective review, verify native OCR and installed-wheel behavior, run the full quality and secret gates on the final development range, and record review findings and their disposition in the private corrective PR before requesting release authorization. | REQ-006 | in_progress | + +### Locked Decisions + +Keep #354 open against its original fork head. The maintainer posted [two requested adjustments](https://github.com/xeonvs/open-code-review-toolkit/pull/354#issuecomment-7310075633). When protected dev is ready, change the existing PR base, inspect the new merge diff, require fresh checks and review, and squash into dev with attribution. Open a separate repository-owned dev-to-main promotion PR. Use non-closing issue references in its body and squash message. + +Exercise the base-change event in CI. Default pull_request activity types omit edited. Require observed runs bound to the new dev base and head; a rerun of an old main-target event cannot establish this. [GitHub base change behavior](https://docs.github.com/en/pull-requests/how-tos/create-pull-requests/changing-the-base-branch-of-a-pull-request). + +Protect the long-lived dev ref from automatic deletion. Repository merge commits are enabled. Main retains signed linear history, strict checks and squash/rebase restrictions. Create a maintainer sync branch at the current dev tip, merge main into it with a signed commit, and merge its reviewed PR into dev with a merge commit so the latest main becomes its ancestor after a squash promotion and release-marker changes. Test two consecutive promotion cycles and verify that the second contains only its intended tree changes. Keep this configuration decision in the bootstrap review. + +Fork validation uses GitHub-hosted pull_request jobs with SHA-pinned actions, read-only effective tokens, no environment, no publisher secrets or OIDC. Allow classification, tests, lint/types, SAST, dependency review/audit, CodeQL PR analysis and distribution build/install smoke after head review. Read the Gitleaks policy and version selector from the protected base. Keep package build local to the job for external PRs; disable unnecessary fork artifact uploads, including scanner reports, or validate and redact any retained public output. Rebuild reviewed source for publication. Reserve Release, TestPyPI, site dispatch, Scorecard publication, maintenance and qualification writes for trusted triggers. No privileged execution of fork code through pull_request_target or workflow_run. + +### Verification + +Verify a bare dev push starts no publisher. With a dev-to-main promotion open, push a fresh reviewed commit to dev and inspect the resulting PR synchronization jobs for effective permissions and exclusion of publishing OIDC and site credentials. Use a fork PR to verify dev CI and actual runner permission banners, maintainer retargeting of external main-targeted PRs, eligible dev promotion, changed-head reapproval, and dev exclusion from both registry environments. Check release authorization on its existing protected path. Verify the actual current PR target, source repository and revision in GitHub before merge. Verify admin bypass is limited and auditable. Allow the sole maintainer to promote via a reviewed PR without creating an impossible self-approval requirement. Require maintainer review of external changes, especially workflows, runnable build/test scripts, dependencies and CODEOWNERS. + +For #351–353 exercise installed incremental review across successive heads, an editor setting, a disallowed key, bounded diagnostics, changed and unchanged search results, deleted and newly matching files, failed/incomplete calls, changed policy and the issue's 23-file/two-change case. Compare findings with fresh full review. Run focused tests, quality, Gitleaks, dependency audit, aggregate security and own-tool review, installed package smoke and the release contracts named in docs/release.md. Versioned dependency CI and hosted ruleset checks must cover the exact promotion tree. + +### Latest Validation Results + +The maintainer intake work is tracked in [#356](https://github.com/xeonvs/open-code-review-toolkit/issues/356). The external contribution stays in #354. The contribution guide and forms now put reusable synthetic evidence on the issue; the PR records implementation, verification and attribution. Maintainers own the shared release plan and credit accepted work through Towncrier. + +The maintainer branch integrates #346–350, qualifies OCR 1.14.6 with official assets and exercises the installed wheel on Linux amd64 using the pinned GitLab Python image. Empty and populated Towncrier previews verified conditional contributor credit. Publication and the hosted intake transition remain pending. A real self-review of c5750fd..d37c88d completed all 21 selected files and identified documentation corrections. Two incremental attempts on the first commit failed before a model response when using the staged executable. With governed MCP enabled, official OCR 1.14.6 exercised a complete fresh review and recorded the reason, with one completed gateway call and no reused files. + +The managed worktree scan rejected the resolvable maintainer checkout before allocating a scan ID or SARIF. Independent reviewers inspected contributor intake, publisher recovery, site notification, secrets, cache and artifact permissions, and traced incremental playback against OCR 1.14.6. The owner accepted this limitation for the draft only. Review findings on partial observations, native input ordering, narrowed groups, private argument storage and dependency selection are tracked through implementation and regression checks. + +The owner selected native GitHub branch rules and a maintainer decision at merge. Retarget external work after both branches have the intended protections and the publication secrets have been isolated. + +The contributor replied and updated #354 to 26080da. Static review on that revision confirmed both editor keys are removed from the incremental child environment and the diagnostic uses a bounded fixed vocabulary. Keep the existing PR open for protected dev intake and review the retargeted candidate. + +All eleven main-required checks passed on 26080da. The maintainer [acknowledged both corrections](https://github.com/xeonvs/open-code-review-toolkit/pull/354#issuecomment-7311647605) and retained the PR for protected dev intake. + +After updating the installed Darwin OCR to 1.14.6 and granting outbound access, two actual ChatGPT incremental reviews completed in a disposable repository. The first saved one qualified file. After editing that file the second correctly performed fresh review and saved its new baseline. The local development firewall binds its allowance to an executable path and subsequently blocked another session copy. Maintainer self-review on this host uses the installed OCR path. A controlled provider exercised reuse of 21 of 23 files in a separate official-binary test. + +The approved 4b395cbe rerun completed with all 17 checks successful, including quality and both platform matrices. All five revised workflow log archives, the revised unpacked wheel/sdist and the SARIF artifact passed the redacted signature scan. Revised job banners again showed only read permissions. The SARIF contained zero results. These observations supersede the initial approval state below. The maintainer's comment is public; branch protections, remote settings and the PR base are still at their original values. + +At b93ec7d all five workflows ran on pull_request, attempt 2. Attempt 1 lists zero jobs. Six test jobs, build, scanners and dependency review passed. Quality stopped on Ruff RUF059 before mypy. At 4b395cbe Ruff passes on the exact revised test file; all five new workflows initially returned action_required. Local diff whitespace validation passed. A manual static review covered the changed files and supporting environment handoff. The managed diff scan rejected the resolvable worktree before creating a scan ID. Repeat it on the assembled release range before merge. + +All five observed job-log archives showed read-only token permissions, including SecurityEvents read for CodeQL. Redacted Gitleaks scans found no matches in the downloaded logs, SARIF and unpacked wheel/sdist streams. SARIF contained zero results. These observations cover recorded output and known detectors. Runner network traffic and private cache contents were not observed. + +Live metadata showed a public repository, no registered repository runners, default read token, Actions PR approvals disabled, mandatory SHA pinning, verified creators broadly allowed and approval only for first-time contributors. No repository Actions variables or environment secrets/variables were listed. A repository-level site dispatch secret exists. Main caches include setup-uv and Gitleaks; assume fork jobs can read base caches. No #354 merge cache was listed. Inspect cache producers and inputs, disable fork restore/save where unnecessary, and keep private packages, home directories and credentials out of every base cache. Review implicit setup-uv defaults in quality, build and security jobs. [GitHub cache scopes](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching). + +The active main ruleset requires PRs, signatures, strict checks and thread resolution, but zero approving reviews, no mandatory CODEOWNERS and a PR-only admin bypass. Its check list omits the Ubuntu 3.13 matrix job documented as blocking. Align it with intended gates. Only the owner appeared in the collaborator inventory. Both publication environments currently allow all protected branches. The notifier reads trusted metadata and a public receipt without checking out triggering source; strengthen the match between receipt run/attempt and publication, with the documented recovery path covered. Open secret-scanning and Dependabot alerts were zero. Four open Scorecard alerts concern CI tests, SAST, code review and branch protection; reconcile against live configuration after rollout. + +### Risks And Recovery + +Protect dev before admitting any external code. A PR from dev in the same repository has a different trust context from a fork and may reference repository secrets. Restrict sensitive credentials first. Retain the protected-main path for bootstrap and recovery. If dev filters, scope isolation or branch protections fail, keep intake pending, correct trusted policy, and repeat affected checks. Never copy a fork build artifact into a privileged publishing job. Re-read PR heads and settings on resume. + +### Resume Point + +Review the corrective range from its protected development base to the fix head. Before promotion, validate the entire release diff from protected main to the final dev head and record both SHAs. WQ-08 gates release promotion. Keep the validation record with the private corrective PR until coordinated disclosure. + +The maintainer bootstrap merged into protected `dev` in #357. All three environments select only `main`. The site dispatch credential is environment-scoped and the repository Actions secret list is empty. The fork workflow approval policy covers all external contributors. All twelve required checks passed on #354 at `75bedaf` against `ef5f376`. GitHub attributed its verified squash commit `feafbf7` to @ahmedpdf445-stack. + +#359 merged the #358 fix and its regression tests into protected `dev` at +`f65053e`. This is the base of the private corrective PR. Keep the milestone +and release issues open through release verification. Obtain explicit release +authorization after the corrective work lands on `dev`. + +### Plan Fidelity Check + +REQ-001–007 cover the selected inputs, full release scope, public contributor guidance, CI isolation, verification and attribution. Queue items identify owners and acceptance evidence at each boundary. + +### Reconciliation Check + +The hosted settings above describe the observed pre-rollout state. The current intake target is protected `dev`. No release authorization or external delivery has occurred. + +### Closure Gate + +Archive in the protected release PR after promotion, development publication, current required checks, signed release markers, release notes, authorized issues and indexes are reconciled. Preserve pending external facts. + +### Post-Close Delivery + +Verify stable registry artifacts, supported Python installs, provenance, annotated tag, immutable release and receipt readback. Confirm tracked issue and milestone closure only after the release workflow records the receipt. + +### Handoff Notes + +Use bare issue references in promotion and release text. Preserve contributors' public attribution across squash or maintainer revisions. Raw logs and profile investigation are unnecessary in release notes. + +If #354 ships, the proposed Contributors entry is “Thanks to @ahmedpdf445-stack for fixing incremental local review when Git editor settings are present ([#354](https://github.com/xeonvs/open-code-review-toolkit/pull/354)).” Verify the handle, contribution and final merged change when preparing the release. + ## Recently Completed - [x] 2026-11-30: Completed Toolkit 0.16.0 — GitLab telemetry and local review recovery; [full archived plan](docs/engineering/execution_history/plans/2026-11-30-toolkit-0-16-0-gitlab-telemetry-and-local-review-recovery.md). diff --git a/README.md b/README.md index d26546c5..db021135 100644 --- a/README.md +++ b/README.md @@ -116,7 +116,9 @@ Accepted tradeoffs can be recorded in `.opencodereview/accepted-decisions.md`; t ## Project architecture -The shipped Repository Evidence Engine reads immutable base/head Git objects, stores bounded typed facts and deltas, creates the compact bootstrap used by OCR, and exposes detailed facts, literal search, scoped absence checks, and base/head changes through the mandatory built-in read-only MCP server. GitLab reviews can also expose a bounded, separately labelled actual-target snapshot for relevant code context; it does not become policy or another reviewed delta. The internal server is always present and cannot be removed or replaced by operator configuration. Protected-policy enriched reviews can also acquire stable GitLab discussions, verified remediation history, and protected same-revision CI outcomes before OCR. Optional external tools use the governed registry-v2 federation gateway: the toolkit freezes explicit allowlists, validates schemas, origins, DLP and budgets, and reconciles content-free usage receipts while OCR remains the only model loop. Local review permits explicit HTTPS or stdio upstreams; GitLab permits HTTPS only. +The shipped Repository Evidence Engine reads immutable base/head Git objects, stores bounded typed facts and deltas, creates the compact bootstrap used by OCR, and exposes detailed facts, literal search, scoped absence checks, and base/head changes through the mandatory built-in read-only MCP server. GitLab reviews can also expose a bounded, separately labelled actual-target snapshot for relevant code context; it does not become policy or another reviewed delta. The internal server is always present and cannot be removed or replaced by operator configuration. Protected-policy enriched reviews can also acquire stable GitLab discussions, verified remediation history, and protected same-revision CI outcomes before OCR. Optional external tools use the governed federation gateway: the toolkit freezes explicit allowlists, exposes only operator-authored closed descriptions and input schemas, validates arguments, origins, DLP and budgets, and reconciles content-free usage receipts while OCR remains the only model loop. Local review permits explicit HTTPS or stdio upstreams; GitLab permits HTTPS only. + +Existing registry v2 configurations require an operator-authored description and closed input schema for each tool before upgrading to v3. [Registry migration and example](docs/configuration.md#governed-mcp-federation-and-trust-boundary). - [Toolkit strategy](docs/engineering/toolkit_strategy.md) - durable product boundaries, architecture, invariants, and non-goals. - [Bounded review context](docs/review-context.md) - protected policy, GitLab discussions and same-revision CI outcomes, legacy reference migration, opaque handles, DLP, receipt, and cleanup contracts. diff --git a/changelog.d/346.maintenance.md b/changelog.d/346.maintenance.md new file mode 100644 index 00000000..6e108a9e --- /dev/null +++ b/changelog.d/346.maintenance.md @@ -0,0 +1 @@ +Update the locked Hypothesis, Ruff, regex stubs, certifi, regex, httpx2, and httpcore2 versions from the reviewed Dependabot updates in PRs #346–349. diff --git a/changelog.d/350.security.md b/changelog.d/350.security.md new file mode 100644 index 00000000..7fe3d8b3 --- /dev/null +++ b/changelog.d/350.security.md @@ -0,0 +1 @@ +Update the pinned GitHub Actions, including Scorecard's upstream security fixes. Require SHA-256 verification of the uv release archive in CI and use uv 0.13.10 for CI and the local dependency audit. [GHSA-vjvj-3m3f-fgmm](https://github.com/astral-sh/uv/security/advisories/GHSA-vjvj-3m3f-fgmm) diff --git a/changelog.d/351.bugfix.md b/changelog.d/351.bugfix.md new file mode 100644 index 00000000..00a2c814 --- /dev/null +++ b/changelog.d/351.bugfix.md @@ -0,0 +1 @@ +Accept `GIT_EDITOR` and `GIT_SEQUENCE_EDITOR` in incremental local review qualification, and name any rejected Git setting in the fallback message. diff --git a/changelog.d/352.feature.md b/changelog.d/352.feature.md new file mode 100644 index 00000000..a217a06e --- /dev/null +++ b/changelog.d/352.feature.md @@ -0,0 +1 @@ +`ocr-ci review --local --incremental` now shows how many groups qualified for reuse and counts why other groups need fresh review in the terminal and local report. diff --git a/changelog.d/353.feature.md b/changelog.d/353.feature.md new file mode 100644 index 00000000..9f5e02e3 --- /dev/null +++ b/changelog.d/353.feature.md @@ -0,0 +1 @@ +After independent Markdown or JSON edits, `ocr-ci review --local --incremental` can reuse unchanged groups. It verifies source reads and repeats supported searches, diff reads and built-in evidence queries before reusing a group. diff --git a/changelog.d/354.contributor.md b/changelog.d/354.contributor.md new file mode 100644 index 00000000..097e8e05 --- /dev/null +++ b/changelog.d/354.contributor.md @@ -0,0 +1 @@ +Thanks to @ahmedpdf445-stack for fixing incremental local review when Git editor settings are present. diff --git a/changelog.d/355.bugfix.md b/changelog.d/355.bugfix.md new file mode 100644 index 00000000..92981136 --- /dev/null +++ b/changelog.d/355.bugfix.md @@ -0,0 +1 @@ +Keep mixed GitLab and local reviews running when OCR reports tracked paths excluded by `.gitignore` alongside a changed submodule pointer. Only eligible files count as completed review work, and the repository summary still reports partial coverage. diff --git a/changelog.d/355.maintenance.md b/changelog.d/355.maintenance.md new file mode 100644 index 00000000..e9718b20 --- /dev/null +++ b/changelog.d/355.maintenance.md @@ -0,0 +1 @@ +Recommend checksum-verified Open Code Review 1.14.6 for local and GitLab reviews. diff --git a/changelog.d/356.maintenance.md b/changelog.d/356.maintenance.md new file mode 100644 index 00000000..c6a4b07d --- /dev/null +++ b/changelog.d/356.maintenance.md @@ -0,0 +1 @@ +Separate draft and ready pull-request checks and prepare protected `dev` intake, with reduced fork CI storage and release notification bound to the verified publication attempt. diff --git a/changelog.d/356.security.md b/changelog.d/356.security.md new file mode 100644 index 00000000..5ba49e4a --- /dev/null +++ b/changelog.d/356.security.md @@ -0,0 +1,4 @@ +Pin the GitLab example’s official Python 3.12 slim image to a reviewed Docker Hub manifest digest. The example requires a `linux/amd64` runner for its OCR binary. + +- Require fresh, verified coverage before GitLab auto-approval and preserve earlier findings during incomplete reviews. Check external tool data before model delivery and review text before publication. +- **Migration for federated installations** — For each tool in `OCR_MCP_SERVERS_JSON`, review and supply an operator-authored `description` and closed `input_schema`, then change the registry’s `version` from 2 to 3. Identity-only installations need no external registry. diff --git a/changelog.d/358.bugfix.md b/changelog.d/358.bugfix.md new file mode 100644 index 00000000..978cceb9 --- /dev/null +++ b/changelog.d/358.bugfix.md @@ -0,0 +1 @@ +Publication DLP keeps findings that quote supported ISO date ranges, dated local Markdown anchors and power-of-two size assignments. Phone numbers and sensitive material elsewhere in the finding still prevent publication. diff --git a/changelog.d/README.md b/changelog.d/README.md index 4a349e4f..cf1a40eb 100644 --- a/changelog.d/README.md +++ b/changelog.d/README.md @@ -1,9 +1,11 @@ # Changelog fragments -Every user-visible 0.x change needs one fragment named `..md`, where type is `feature`, `bugfix`, `maintenance`, `refactor`, `doc`, `rules`, `security`, `deprecation`, or `removal`. Use a numeric GitHub issue or pull-request identifier so generated links remain valid. +Every user-visible 0.x change needs one fragment named `..md`, where type is `feature`, `bugfix`, `maintenance`, `refactor`, `doc`, `rules`, `security`, `deprecation`, `removal`, or `contributor`. Use a numeric GitHub issue or pull-request identifier so generated links remain valid. Use one fragment per issue and change type. A single sentence is preferred for one outcome. When one issue delivers several closely related user-visible outcomes, write a short introductory sentence followed by concise Markdown bullets; Towncrier preserves that formatting in the generated section. Do not copy implementation steps or unfinished work into a fragment: future work belongs in the backlog, and unrelated release-note entries need their own issue and fragment. +For accepted external work, maintainers add a `.contributor.md` acknowledgment with the contributor's public GitHub handle and a short description of the shipped change. Towncrier generates a numbered issue link. Include a direct link to each accepted PR in the acknowledgment body and group multiple contributions from the same person together. An empty category produces no heading. + Before handoff or release, render the pending notes with `towncrier build --draft --version ` and inspect the complete generated section for grouping, links, punctuation, and readability. Use `rules` when the effective rules contract changes in any supported layer: the toolkit-owned `examples/gitlab/rules.json`, built-in rules in the recommended OCR release, or OCR's allowlist of reviewable file types. Omit the fragment when none of those contracts changed. Name the affected layer in each entry and write ordinary readable text without conventional-commit prefixes such as `feat(rules)` or `fix(allowlist)`. diff --git a/compatibility/evidence/ocr-1.14.6-local-review.json b/compatibility/evidence/ocr-1.14.6-local-review.json new file mode 100644 index 00000000..bdd42eaf --- /dev/null +++ b/compatibility/evidence/ocr-1.14.6-local-review.json @@ -0,0 +1,31 @@ +{ + "runs": [ + { + "executable": { + "name": "opencodereview-darwin-arm64", + "sha256": "24d043eefd63dadfbf64b1dcc49eb3430bf63c518d6b4d7627985a4e5f0c87a8", + "size": 61029138 + }, + "native_handoffs": { + "local_review_continuation": { + "consumer": "toolkit-local", + "requested": 14, + "reused": 3, + "rule_change_requests_full_range": true, + "selected": 17 + }, + "local_review_incremental": { + "analysis_seeds_primary_review": true, + "consumer": "toolkit-local", + "native_source_dependencies_requalify": true, + "requested": 2, + "reused": 15, + "rule_change_requests_full_range": true, + "selected": 17 + } + } + } + ], + "schema_version": 1, + "version": "1.14.6" +} diff --git a/compatibility/evidence/ocr-1.14.6.json b/compatibility/evidence/ocr-1.14.6.json new file mode 100644 index 00000000..8bfe5baf --- /dev/null +++ b/compatibility/evidence/ocr-1.14.6.json @@ -0,0 +1,421 @@ +{ + "assets": [ + { + "name": "opencodereview-darwin-amd64", + "sha256": "2b2e0ca708615f83970d3bb4713c6ac1a18bf22fb455816db33661ea3053bc9d", + "size": 64304384 + }, + { + "name": "opencodereview-darwin-arm64", + "sha256": "24d043eefd63dadfbf64b1dcc49eb3430bf63c518d6b4d7627985a4e5f0c87a8", + "size": 61029138 + }, + { + "name": "opencodereview-linux-amd64", + "sha256": "a91fea039d7070f8155e8bdaac3b8324e97104fb510ac0fa97de40e622ee3fff", + "size": 62451874 + }, + { + "name": "opencodereview-linux-arm64", + "sha256": "14178ea02994a1857181ce8cba26cb0fd3ca7c9fbaf95cddd6e356d96314b9c3", + "size": 58785954 + }, + { + "name": "opencodereview-windows-amd64.exe", + "sha256": "15793e1bc2ca115d42db6001888f51670166161b4cd8f45d46f5ab6a41cadf57", + "size": 64001536 + }, + { + "name": "opencodereview-windows-arm64.exe", + "sha256": "289a12a3595a42b3c9ca89d3f189ea7c69b2c602d2126c9094050cd43c6b81e6", + "size": 59575808 + }, + { + "name": "sha256sum.txt", + "sha256": "923a4dec75cec46cbcf5224e1d66d56ebd6af7eb735c73032f8d3bc1e9752cb0", + "size": 572 + } + ], + "classification": "automatic-safe", + "classification_reasons": [ + "same-minor patch passed all probes with maintenance-only notes" + ], + "comparison_version": "1.14.5", + "contracts": { + "checks": { + "budget_partial": "passed", + "identity": "passed", + "mcp": "passed", + "numeric_controls": "passed", + "provider_controls": "passed", + "publication": "passed", + "range_preview": "passed", + "review_result": "passed", + "user_exclusion": "passed" + }, + "native_handoffs": [ + "analysis", + "chatgpt_auth", + "diagram_output", + "gitlink_projection", + "local_review_continuation", + "local_review_incremental" + ], + "observations": { + "budget": { + "completed": 2, + "failed_budget": 1, + "partial_findings_preserved": true, + "result": "passed", + "selected": 3 + }, + "builtin_selection": { + "fixture_paths": [ + ".cpcache/cache.edn", + ".shadow-cljs/build.edn", + "BUILD", + "WORKSPACE", + "app/src/Program.cs", + "bazel/config.star", + "bazel/defs.bazel", + "bazel/rules.bzl", + "config/settings.jsonc", + "deps.edn", + "dist/generated.js", + "infra/main.tofu", + "native/header.hxx", + "native/object.mm", + "native/source.cxx", + "nested/BUILD", + "nested/WORKSPACE", + "node_modules/example/index.ts", + "policies/authz.rego", + "resources/public/js/compiled/app.js", + "resources/public/js/compiled/config.edn", + "rtl/entity.vhd", + "rtl/entity.vhdl", + "rtl/include.vh", + "rtl/module.sv", + "rtl/module.v", + "scripts/check.fsx", + "scripts/module.psd1", + "scripts/module.psm1", + "scripts/setup.kts", + "scripts/setup.nu", + "scripts/setup.ps1", + "shaders/main.glsl", + "shaders/main.hlsl", + "shaders/main.metal", + "shaders/main.wgsl", + "src/Main.scala", + "src/Program.fs", + "src/Program.fsi", + "src/WidgetTest.fs", + "src/component.re", + "src/component.rei", + "src/config.dhall", + "src/contract.move", + "src/core.clj", + "src/core_test.cljs", + "src/kernel.cu", + "src/kernel.hip", + "src/model.rb", + "src/module.cjs", + "src/module.mjs", + "src/nested/view.cljs", + "src/parser.ml", + "src/parser.mli", + "src/query.sql", + "src/shared.cljc", + "src/test/kotlin/scripts/Example.kts", + "src/test_helpers.py", + "src/types.cts", + "src/types.mts", + "test/nested/core.clj", + "test/parser.ml", + "types/interface.pyi", + "views/component.j2", + "views/page.ejs", + "views/page.erb", + "views/page.haml", + "views/page.jinja2", + "views/page.liquid", + "views/page.njk", + "views/page.pug", + "views/page.slim" + ], + "selected": [ + "BUILD", + "WORKSPACE", + "app/src/Program.cs", + "bazel/config.star", + "bazel/defs.bazel", + "bazel/rules.bzl", + "config/settings.jsonc", + "deps.edn", + "infra/main.tofu", + "native/header.hxx", + "native/object.mm", + "native/source.cxx", + "nested/BUILD", + "nested/WORKSPACE", + "policies/authz.rego", + "rtl/entity.vhd", + "rtl/entity.vhdl", + "rtl/include.vh", + "rtl/module.sv", + "rtl/module.v", + "scripts/check.fsx", + "scripts/module.psd1", + "scripts/module.psm1", + "scripts/setup.kts", + "scripts/setup.nu", + "scripts/setup.ps1", + "shaders/main.glsl", + "shaders/main.hlsl", + "shaders/main.metal", + "shaders/main.wgsl", + "src/Main.scala", + "src/Program.fs", + "src/Program.fsi", + "src/component.re", + "src/component.rei", + "src/config.dhall", + "src/contract.move", + "src/core.clj", + "src/kernel.cu", + "src/kernel.hip", + "src/model.rb", + "src/module.cjs", + "src/module.mjs", + "src/nested/view.cljs", + "src/parser.ml", + "src/parser.mli", + "src/query.sql", + "src/shared.cljc", + "src/types.cts", + "src/types.mts", + "types/interface.pyi", + "views/component.j2", + "views/page.ejs", + "views/page.erb", + "views/page.haml", + "views/page.jinja2", + "views/page.liquid", + "views/page.njk", + "views/page.pug", + "views/page.slim" + ] + }, + "comment_arguments": { + "comments_per_batch": 2, + "failure_arguments_preserved": true, + "intact_cases": [ + "array", + "serialized", + "repaired" + ], + "repair_warning": true, + "result": "passed", + "suspect_batch_rejected": true + }, + "comparison_sides": { + "default_side": "new", + "deleted_paths": "old-only", + "invalid_sides_rejected": true, + "new_ref": "resolved-head", + "old_ref": "resolved-base", + "renamed_paths": "side-relative", + "result": "passed", + "target_tip": "not-used", + "tools": [ + "file_read", + "file_find", + "code_search" + ], + "worktree": "preserved" + }, + "completion_cap": { + "explicit": 4096, + "inherited": 16384, + "result": "passed", + "wire_field": "max_completion_tokens" + }, + "local_review_executable": { + "name": "opencodereview-linux-amd64", + "sha256": "a91fea039d7070f8155e8bdaac3b8324e97104fb510ac0fa97de40e622ee3fff", + "size": 62451874 + }, + "local_review_unsupported": [], + "native_handoffs": { + "analysis": { + "citations_verified": true, + "status": "completed" + }, + "chatgpt_auth": { + "login_required": true, + "store_admitted": true + }, + "diagram_output": { + "consumer": "toolkit-local", + "rendered": true + }, + "gitlink_projection": { + "consumer": "toolkit-local", + "immutable_range": true + }, + "local_review_continuation": { + "consumer": "toolkit-local", + "requested": 14, + "reused": 3, + "rule_change_requests_full_range": true, + "selected": 17 + }, + "local_review_incremental": { + "analysis_seeds_primary_review": true, + "consumer": "toolkit-local", + "native_source_dependencies_requalify": true, + "requested": 2, + "reused": 15, + "rule_change_requests_full_range": true, + "selected": 17 + } + }, + "numeric_cli": { + "grace_rounds": { + "no_task_done": { + "completed": false, + "limit_warning": true + }, + "task_done": { + "completed": true, + "limit_warning": true + } + }, + "max_tokens_budget": { + "cases": { + "invalid_below": { + "effective": null, + "input": -1, + "outcome": "rejected" + }, + "minimum": { + "effective": 1, + "input": 1, + "outcome": "accepted" + }, + "omitted": { + "effective": "unlimited", + "input": null, + "outcome": "accepted" + }, + "representative": { + "effective": 30000, + "input": 30000, + "outcome": "accepted" + }, + "sentinel": { + "effective": "unlimited", + "input": 0, + "outcome": "accepted" + } + }, + "maximum": null, + "owner": "ocr-cli" + }, + "max_tools": { + "cases": { + "invalid_below": { + "effective": null, + "input": -1, + "outcome": "rejected" + }, + "lower_override": { + "effective": 75, + "input": 75, + "outcome": "accepted" + }, + "minimum": { + "effective": 50, + "input": 50, + "outcome": "accepted" + }, + "minimum_minus_one": { + "effective": 50, + "input": 49, + "outcome": "normalized", + "reported_normalization": 50 + }, + "omitted": { + "effective": 100, + "input": null, + "outcome": "accepted" + }, + "representative": { + "effective": 125, + "input": 125, + "outcome": "accepted" + }, + "sentinel": { + "effective": 100, + "input": 0, + "outcome": "accepted" + }, + "template_value": { + "effective": 100, + "input": 100, + "outcome": "accepted" + } + }, + "manifest_limit_verified": true, + "maximum": null, + "owner": "ocr-cli-or-template-default", + "reported_minimum": 50 + }, + "result": "passed" + }, + "reasoning_effort": { + "efforts": [ + "unset", + "none", + "high" + ], + "protocols": [ + "openai", + "openai-responses" + ], + "provider_acceptance": "not-tested", + "responses_siblings_preserved": true, + "result": "passed" + }, + "stream_override": { + "explicit_false": "preserved", + "non_boolean": "omitted", + "protocols": [ + "openai", + "openai-responses", + "anthropic" + ], + "provider_acceptance": "not-tested", + "result": "passed", + "unset": "omitted" + } + }, + "optional_capabilities": [ + "llm_result_identity", + "per_run_model_override", + "per_run_provider_override", + "review_effort", + "semantic_grouping" + ] + }, + "published_at": "2026-12-01T06:13:37Z", + "release_changes": "## 🐛 Bug Fixes\n\n- fix(diff): report gitignored files as excluded instead of dropping them (#1805)\n- fix(viewer): show a live review as running instead of aborted (#1757)\n- fix(diff): honor negated gitignore directories (#1794)\n\n## 📖 Documentation\n\n- docs(ci): standardize review-language configuration (#1293)\n\n**Full Changelog**: https://github.com/alibaba/open-code-review/compare/v1.14.5...v1.14.6", + "release_notes_sha256": "79b9fcebc035e23e15328050bada9bff01e959a92ddbe887e785dc7f7724c249", + "result": "compatible", + "schema_version": 5, + "tag": "v1.14.6", + "tested_baseline_version": "1.14.5", + "upstream_repository": "alibaba/open-code-review", + "version": "1.14.6" +} diff --git a/compatibility/ocr-support.json b/compatibility/ocr-support.json index e88a8414..1fb61910 100644 --- a/compatibility/ocr-support.json +++ b/compatibility/ocr-support.json @@ -1,6 +1,6 @@ { - "monitoring_floor": "1.14.5", - "recommended_version": "1.14.5", + "monitoring_floor": "1.14.6", + "recommended_version": "1.14.6", "releases": [ { "assets": [ @@ -3632,6 +3632,63 @@ "release_url": "https://github.com/alibaba/open-code-review/releases/tag/v1.14.5", "status": "tested", "version": "1.14.5" + }, + { + "assets": [ + { + "name": "opencodereview-darwin-amd64", + "sha256": "2b2e0ca708615f83970d3bb4713c6ac1a18bf22fb455816db33661ea3053bc9d", + "size": 64304384 + }, + { + "name": "opencodereview-darwin-arm64", + "sha256": "24d043eefd63dadfbf64b1dcc49eb3430bf63c518d6b4d7627985a4e5f0c87a8", + "size": 61029138 + }, + { + "name": "opencodereview-linux-amd64", + "sha256": "a91fea039d7070f8155e8bdaac3b8324e97104fb510ac0fa97de40e622ee3fff", + "size": 62451874 + }, + { + "name": "opencodereview-linux-arm64", + "sha256": "14178ea02994a1857181ce8cba26cb0fd3ca7c9fbaf95cddd6e356d96314b9c3", + "size": 58785954 + }, + { + "name": "opencodereview-windows-amd64.exe", + "sha256": "15793e1bc2ca115d42db6001888f51670166161b4cd8f45d46f5ab6a41cadf57", + "size": 64001536 + }, + { + "name": "opencodereview-windows-arm64.exe", + "sha256": "289a12a3595a42b3c9ca89d3f189ea7c69b2c602d2126c9094050cd43c6b81e6", + "size": 59575808 + }, + { + "name": "sha256sum.txt", + "sha256": "923a4dec75cec46cbcf5224e1d66d56ebd6af7eb735c73032f8d3bc1e9752cb0", + "size": 572 + } + ], + "capabilities": [ + "llm_result_identity", + "per_run_model_override", + "per_run_provider_override", + "review_effort", + "semantic_grouping" + ], + "evidence": "compatibility/evidence/ocr-1.14.6.json", + "evidence_sha256": "55710402a0ec4446a7760196ee24f18af577718d0610a00098445a9050673344", + "human_conclusion": "The hosted Linux amd64 contracts passed. The toolkit accepts the new gitignore preview reason for independently verified ordinary diff records in mixed gitlink reviews. Native matching honors reopened directories and excludes tracked paths under a still-ignored parent. The toolkit sets its configured review language explicitly, and the viewer liveness change stays within native session storage.", + "local_review_evidence": { + "evidence": "compatibility/evidence/ocr-1.14.6-local-review.json", + "evidence_sha256": "32033351108062da67d65ca7e1473114b669759e0a01a902e2762dfff9b2943c" + }, + "published_at": "2026-12-01T06:13:37Z", + "release_url": "https://github.com/alibaba/open-code-review/releases/tag/v1.14.6", + "status": "tested", + "version": "1.14.6" } ], "runtime_support": { diff --git a/docs/README.md b/docs/README.md index b9e6ad21..4403e034 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,6 +6,7 @@ This page routes readers to the canonical document for each topic. It does not r - [codex/README.md](codex/README.md) - [compatibility.md](compatibility.md) - [configuration.md](configuration.md) +- [contributor-intake.md](contributor-intake.md) - [development.md](development.md) - [diagrams.md](diagrams.md) - [dlp-audit.md](dlp-audit.md) @@ -34,6 +35,7 @@ This page routes readers to the canonical document for each topic. It does not r ## Contribute and release - [Development guide](development.md) — local environment, tests, quality gates, and implementation checks. +- [Protected contributor intake](contributor-intake.md) — maintainer setup, dependency ownership, and merge checks. - [Private DLP audits](dlp-audit.md) — offline corpus diagnosis, exact expectations, replay and owned source cleanup. - [Release process](release.md) — release classification, qualification, publication, and reconciliation. - [Contributing guide](../CONTRIBUTING.md) and [security policy](../SECURITY.md) — contribution and vulnerability-reporting routes. diff --git a/docs/codex/ENGINEERING_WORKFLOW_STATE.yaml b/docs/codex/ENGINEERING_WORKFLOW_STATE.yaml index 31192278..5c7c4908 100644 --- a/docs/codex/ENGINEERING_WORKFLOW_STATE.yaml +++ b/docs/codex/ENGINEERING_WORKFLOW_STATE.yaml @@ -32,7 +32,7 @@ plan_archive_indexes: - docs/engineering/execution_history/README.md - docs/engineering/README.md - docs/README.md -active_plan: null +active_plan: PLANS.md runtime_agent_config_managed: true instruction_contract_version: 3 planning_contract_version: 2 diff --git a/docs/codex/TASKS_BACKLOG.md b/docs/codex/TASKS_BACKLOG.md index 2b488df4..725b0cd5 100644 --- a/docs/codex/TASKS_BACKLOG.md +++ b/docs/codex/TASKS_BACKLOG.md @@ -31,12 +31,12 @@ The [signal-ownership audit](../engineering/review_signal_ownership.md) remains - **Status:** conditional - **Priority:** low - **Roadmap theme:** External integrations -- **Dependencies:** Established M7 registry-v2 federation gateway and its bounded HTTPS transport. Authentication must preserve gateway admission and upstream tenant/object authorization; the historical BL-011 direct-composition envelope is not a current fallback. +- **Dependencies:** Established M7 governed federation gateway and its bounded HTTPS transport. Authentication must preserve gateway admission and upstream tenant/object authorization; the historical BL-011 direct-composition envelope is not a current fallback. - **Activation trigger:** A reviewed HTTPS upstream requires authorization-code OAuth rather than static environment-backed headers, and the existing gateway authentication contract is insufficient for pilot operations. - **Next safe action:** Capture the concrete upstream OAuth requirement and credential/callback ownership before selecting an implementation. - **Goal:** Add a provider-neutral authentication lifecycle without placing long-lived OAuth material in repository content or OCR config; object authorization remains server-owned and separate. - **Scoped deliverables:** Define authorization-code plus PKCE, browser callback ownership, refresh/revocation, secure token persistence, tenant/resource binding, dynamic-client-registration policy, sanitized audit events, and provider conformance fixtures before selecting an implementation boundary. -- **Acceptance criteria:** Tokens never enter argv, repository files, generated context, or logs; refresh/revocation and tenant changes fail closed; synthetic static-header and browser-OAuth fixtures preserve registry-v2 gateway admission, bounded HTTPS transport, and upstream resource authorization without direct OCR passthrough. +- **Acceptance criteria:** Tokens never enter argv, repository files, generated context, or logs; refresh/revocation and tenant changes fail closed; synthetic static-header and browser-OAuth fixtures preserve federation gateway admission, bounded HTTPS transport, and upstream resource authorization without direct OCR passthrough. - **Exclusions:** Resource authorization by token presence, automatic reference discovery, writes, generic web access, or treating a permanent token as OAuth lifecycle support. - **Validation:** Threat-model review plus synthetic authorization, PKCE, callback, refresh, revocation, tenant mismatch, persistence-permission, redaction, and OCR integration cases. - **Release classification expectation:** `release-required` once public authorization behavior is selected. diff --git a/docs/compatibility.md b/docs/compatibility.md index 15894ae3..7770c02b 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -15,6 +15,8 @@ python -m pip install --upgrade --only-binary=:all: open-code-review-toolkit ocr-ci --version ``` +Toolkit 0.16.0 uses OCR 1.14.5. The 1.14.6 instructions below apply to builds containing the 0.16.1 qualification. Match the manifest from the installed toolkit release before changing the binary. + On Linux amd64, verify the download in a private directory before installing the executable: @@ -24,8 +26,8 @@ download in a private directory before installing the executable: cd "$(mktemp -d)" mkdir -p "$HOME/.local/bin" curl --fail --location --proto '=https' --proto-redir '=https' \ - -o ocr https://github.com/alibaba/open-code-review/releases/download/v1.14.5/opencodereview-linux-amd64 - echo '4bfb9142dda07c38e120c83ceeaed3e86697aa401e57d683df063a5b7c5d64d4 ocr' | sha256sum --check --strict + -o ocr https://github.com/alibaba/open-code-review/releases/download/v1.14.6/opencodereview-linux-amd64 + echo 'a91fea039d7070f8155e8bdaac3b8324e97104fb510ac0fa97de40e622ee3fff ocr' | sha256sum --check --strict install -m 0755 ocr "$HOME/.local/bin/ocr" ) ``` @@ -36,9 +38,9 @@ the wheel, check `ocr --version` and run `ocr-ci preflight --local` in the configured local environment or `ocr-ci preflight` in GitLab CI. Preflight rejects the former 1.13.x binary. The GitLab example verifies both downloads; use the example from the tag matching the installed toolkit. -[OCR 1.14.5 release assets](https://github.com/alibaba/open-code-review/releases/tag/v1.14.5) +[OCR 1.14.6 release assets](https://github.com/alibaba/open-code-review/releases/tag/v1.14.6) -## Changes in OCR 1.13.11 through 1.14.5 +## Changes in OCR 1.13.11 through 1.14.6 | OCR | Effect on toolkit users | Other upstream changes | | --- | --- | --- | @@ -51,6 +53,7 @@ use the example from the tag matching the installed toolkit. | [1.14.3](https://github.com/alibaba/open-code-review/releases/tag/v1.14.3) | Native `code_search` gives the model a recovery hint for an invalid Perl regular expression. The model can correct it or retry with literal matching. | OCR updates its embedded OpenTelemetry dependency. Upstream documents the extension override for rule includes and its own GitHub Actions trigger, and adds a French README. | | [1.14.4](https://github.com/alibaba/open-code-review/releases/tag/v1.14.4) | Default selection excludes common C and C++ test and benchmark paths, including `src/parser_test.cpp` and headers under `tests/`. Native code search preserves binary matches. OCR trims and validates the configured LLM URL. | Retry reports are stored in the private native session. The upstream GitHub review skill and Vietnamese translation do not change toolkit commands. | | [1.14.5](https://github.com/alibaba/open-code-review/releases/tag/v1.14.5) | Native OCR supports an absolute `OCR_HOME` for persistent storage. Local ChatGPT preflight checks the selected auth store. ChatGPT requests gain session affinity for cache routing. | Delegated execution belongs to the OpenCode plugin. Upstream CI reports include file coverage. Toolkit publishes its own MR summary. | +| [1.14.6](https://github.com/alibaba/open-code-review/releases/tag/v1.14.6) | Native previews retain tracked paths excluded by the committed root `.gitignore` and honor negated directory patterns. The production manifest can omit these previewed exclusions. For GitLab and qualified local gitlink review, the toolkit reconciles these exclusions against the preview. Ordinary GitLab posting requires a selection proof when the production manifest omits them. The partial gitlink route independently verifies its effective coverage. The affected review can publish comments and remains ineligible for automatic approval. | The native session viewer distinguishes running sessions from aborted sessions. The upstream `OCR_LANGUAGE` fallback applies when native config leaves the language empty. The toolkit writes its configured review language explicitly. | ## Qualification lanes @@ -64,13 +67,13 @@ recorded native handoff. Archived schema-4 receipts remain readable. [Qualificat Same-head continuation and changed-head incremental review each require their own native handoff. Supported OCR versions without the corresponding handoff -start a full review. The support manifest links separate observations from -loopback runs with the official 1.14.5 Darwin arm64 and Linux amd64 assets. +start a full review. The support manifest identifies the exact official assets +that passed each loopback handoff probe. The **OCR compatibility** workflow checks stable upstream releases every Monday at 07:15 UTC and qualifies candidates newer than the manifest monitoring floor. -Exact-tag manual dispatch is the -single-candidate path. A manual +Select the `main` branch when dispatching **OCR compatibility** manually. +Exact-tag manual dispatch is the single-candidate path. A manual `through_tag` instead qualifies the complete contiguous unseen chain only through that exact stable release, preventing a scoped maintenance run from absorbing a newer upstream release. The two inputs are mutually @@ -91,9 +94,23 @@ Before selecting a lane, classify every upstream changelog item as a toolkit-con Classify a pin-only promotion and its machine or human qualification evidence as Maintenance. If the qualification exposes an existing toolkit incompatibility and the delivery corrects it, classify that outcome as a Bug Fix. If the toolkit begins exposing or consuming an upstream capability, classify that outcome as a Feature. Effective built-in rule or reviewable-file changes remain Rules even when they arrive with an otherwise maintenance-only OCR promotion. -- `automatic-safe`: only an adjacent patch in the already-tested major/minor line, with every probe passing and maintenance-only release notes containing no material compatibility signal. When several releases are discovered together, each keeps the manifest recommendation as its tested baseline but is classified against its adjacent predecessor. The aggregation job prepares one cumulative compatibility patch only when the complete sequence is contiguous and every member is automatic-safe. The patch covers the manifest, evidence and runtime preflight version. GitLab example version/checksum pins move together in the release PR. It never writes directly to `main`. +- `automatic-safe`: only an adjacent patch in the already-tested major/minor line, with every probe passing and maintenance-only release notes containing no material compatibility signal. When several releases are discovered together, each keeps the manifest recommendation as its tested baseline but is classified against its adjacent predecessor. The aggregation job prepares one cumulative compatibility patch when every candidate job succeeds, the complete chain is contiguous and automatic-safe, and `qualification_only` is off. The patch covers the manifest, evidence and runtime preflight version. GitLab example version/checksum pins move together in the release PR. It never writes directly to `main`. - `human-review-required`: every minor/major release, skipped or non-increasing patch, changed contract requiring operator review, feature-bearing release, material/security/deprecation/config/provider signal, or ambiguous release notes. The workflow creates or refreshes one qualification issue with machine evidence, a bounded plain-text release-change excerpt, and a human checklist. +Check `ocr-chain-assessment.json` and `ocr-chain-update.patch` in the +`ocr-compatibility-chain` artifact before preparing a maintainer-owned +compatibility PR. The `assess-complete-chain` job summary records the aggregate +classification, qualification mode, patch generation and artifact upload +outcomes. A `qualification_only` run uploads the assessment when available and +skips patch generation. Investigate failed, missing or human-review-required +chain results through their qualification evidence. + +To regenerate a missing or expired patch, first confirm the chain was eligible +and its final release is still unseen above the current `monitoring_floor`. +Dispatch from `main` with `tag` and `after_tag` empty and `qualification_only` +off. Set `through_tag` to that final release. Review the new chain assessment +and artifact before applying the patch. + For local attempts that request `--status-output`, choose a fresh output directory for each run. Each directory preserves one candidate outcome and its matching evidence. Discovery qualifies up to ten releases per run. To continue a longer queue, dispatch @@ -208,7 +225,11 @@ The historical 1.11.2 Linux amd64 evidence verifies SHA-256 `fad3c62314478822c1e The contiguous 1.9.7 through 1.9.8 promotion combines the repository-owned hosted Linux qualification with adjacent upstream source review. It also repeats the required 1.9.8 contract probes through the checksum-verified Darwin arm64 artifact. Multi-tool MCP initialization, fixed tool discovery and dispatch, and owner-only session persistence remain compatible with the M5 design: the toolkit may expose several fixed tools from its one built-in process, while an isolated `HOME` contains OCR's `.opencodereview/sessions` state for deterministic cleanup. Gemini and Bedrock are optional upstream provider capabilities that the toolkit neither selects nor configures; mirror-aware installation is outside the toolkit-owned download path; native severity retains the structured result fields already consumed; and human-audience progress routing does not affect the toolkit's agent-audience invocation. Therefore this promotion requires no toolkit CI behavior adaptation beyond version and checksum pins. These source observations establish capability only; the M5 production-path tests remain responsible for proving the toolkit's composition and containment. -An automatic-safe result is not an automatic stable release. It must still pass a normal protected compatibility PR and a separate signed stable-release PR. If a dedicated OCR update bot credential is not configured, the workflow publishes the exact patch as an artifact and records the resume action in the issue; the default `GITHUB_TOKEN` is intentionally not used to create a PR that would fail to trigger the full protected workflow set. +For a complete automatic-safe chain with successful candidate jobs and +`qualification_only` off, the workflow publishes the exact patch as an +artifact and records the next step on the issue. A maintainer reviews the patch +and opens the compatibility PR through protected intake. Stable publication +requires a separate signed release PR. ### OCR 1.11.3 — toolkit 0.9.0 target @@ -572,8 +593,7 @@ Official Linux amd64 and Darwin arm64 assets pass the current controlled-peer contracts. OCR 1.13.9 adds `coverage.excluded`: reasons and unique item identities remain separate from selected files and their completed/reused/failed/waived partition. Exclusions have no source fingerprint and do not turn a complete -selected review into a partial one. The list covers files reaching native -selection, rather than every path the native diff provider may ignore earlier. +selected review into a partial native result. Request-scoped tool declarations preserve normal evidence, diagram and federation calls. An undeclared tool is rejected; a registered read absent from the restricted diff --git a/docs/configuration.md b/docs/configuration.md index 69a3d764..22499e4e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -47,8 +47,8 @@ These are the complete supported toolkit-owned runtime inputs. `Required` is sco | `OCR_TELEMETRY_EXPORTER` | Operator / `ocr-ci configure` | No | Empty string | Exporter name written only when telemetry is enabled. | | `OCR_TELEMETRY_OTLP_ENDPOINT` | Operator / `ocr-ci configure` | No | Unset | OTLP endpoint written only when telemetry is enabled and the value is non-empty. | | `OCR_REVIEW_CONTEXT_MODE` | Operator / review launcher | No | `off` | Closed selector: `off`, `metadata`, or protected-policy `enriched`. | -| `OCR_REVIEW_CONTEXT_ADAPTERS_JSON` | Removed legacy input | No | Removed; setting it is an error | Executable context adapters are not supported. Migrate external tools to governed registry v2. | -| `OCR_MCP_SERVERS_JSON` | Operator / governed federation | No | Empty version 2 registry | Strict registry-v2 object. GitLab accepts HTTPS upstreams; local accepts HTTPS or explicit stdio. Unknown fields and legacy shapes fail before OCR. | +| `OCR_REVIEW_CONTEXT_ADAPTERS_JSON` | Removed legacy input | No | Removed; setting it is an error | Executable context adapters are not supported. Migrate external tools to governed registry v3. | +| `OCR_MCP_SERVERS_JSON` | Operator / governed federation | No | Unset or blank | Closed operator registry. GitLab accepts HTTPS upstreams; local accepts HTTPS or explicit stdio. Unknown fields and legacy shapes fail before OCR. | | `OCR_MCP_REPLACE` | Removed legacy input | No | Removed; setting it is an error | Replacement/restoration semantics are not supported; the mandatory internal evidence MCP is unreplaceable. | | `OCR_DLP_ENABLED` | Operator / shared review launcher | No | `true` | Strict boolean: `true`, `1`, `yes`, or `on`; `false`, `0`, `no`, or `off`; case-insensitive. Unset/empty is enabled. False disables context/federation and publication DLP for one run, emits a prominent warning, and makes the run approval-ineligible. Other values fail before OCR. | | `OCR_POST_MODE` | Operator / posting | No | `draft` | `draft` is normal transactional publication; `direct` is the emergency fallback. | @@ -193,7 +193,7 @@ GitLab supplies the `CI_*` values in merge-request pipelines. The operator suppl | **`CI_COMMIT_SHA`** | GitLab predefined | Yes for detached MR review | None | Checked-out source head H; must match the authenticated current MR source. It never replaces the diff base. | | **`CI_MERGE_REQUEST_EVENT_TYPE`** | GitLab predefined | Yes for GitLab MR review | None | Must be `detached`. `merged_result`, `merge_train`, missing, and unknown forms stop before model execution because their checkout can be a synthetic merge commit. The operator does not add this variable. | | `CI_PIPELINE_ID` | GitLab predefined | No | Omitted | Optional bounded invocation identity stored as non-authoritative evidence. | -| `CI_JOB_ID` | GitLab predefined | No | Omitted | Bounded job identity stored as non-authoritative invocation evidence and, when present, bound into receipt v13 or note-capable private status so `post` rejects another job's handoff. | +| `CI_JOB_ID` | GitLab predefined | No | Omitted | Bounded job identity stored as non-authoritative invocation evidence and, when present, bound into the ordinary receipt or note-capable private status so `post` rejects another job's handoff. | | **`CI_PIPELINE_SOURCE`** | GitLab predefined / example rules | Yes for example job selection | None | The public example runs review jobs only for `merge_request_event`. | | `OCR_GITLAB_TARGET_PROTECTION_MODE` | Operator / GitLab snapshot acquisition | No | `auto` | Closed selector: `auto` uses the actual target when protected, or the same project's protected default branch as policy authority when the actual target is unprotected. `required` rejects an unprotected target; `unprotected` retains the earlier constrained profile. An explicitly assigned empty, whitespace, mixed-case, malformed, or unknown value fails closed. | @@ -226,7 +226,7 @@ for that toolkit release; an older toolkit does not automatically accept a newer ## Dynamic adapter and MCP inputs The adapter names are removed runtime inputs documented above; this table lists -only credential names dynamically referenced by current registry v2. +only credential names dynamically referenced by operator registry. | Variable | Source / owner | Required | Exact default | Behavior | | --- | --- | --- | --- | --- | @@ -245,19 +245,19 @@ guides OCR to read available intent before considering useful allowlisted tools. References in MR text remain untrusted data; they do not authorize tools or cause automatic acquisition. Configured tools may remain unused. -`OCR_MCP_SERVERS_JSON` accepts only the closed version-2 registry. Server and tool names use ASCII letters, digits, underscore or hyphen, begin with a letter, and cannot contain `__`; aliases cannot collide with toolkit tools. Each tool policy defaults to `assurance: "advisory"`; use explicit `review_read` only after the operator has established that the tool is a bounded read whose successful use may remain approval-eligible. This assurance is operator policy, not a server annotation. +`OCR_MCP_SERVERS_JSON` accepts only the closed version-3 registry. Server and tool names use ASCII letters, digits, underscore or hyphen, begin with a letter, and cannot contain `__`; aliases cannot collide with toolkit tools. Each tool policy requires an operator-authored `description` and closed `input_schema`; the gateway exposes and validates those values instead of the upstream's live description or input schema. Declare a root object and one explicit type per schema node. Every object schema must set `additionalProperties: false`. For arrays, supply an item schema or set `items: false` to allow only an empty array. Argument schemas reject `allOf`, `anyOf`, `oneOf` and `prefixItems`. Use ASCII IDNA A-labels for internationalized hosts in HTTPS endpoints and resource origins. Each tool policy defaults to `assurance: "advisory"`; use explicit `review_read` only after the operator has established that the declared fields and data classes are a bounded read whose successful use may remain approval-eligible. This assurance is operator policy, not a server annotation. Registry v2 is rejected rather than reinterpreted; migrate each selected tool by reviewing and adding its operator-owned interface fields, then set `version` to `3`. A GitLab-MR external server therefore looks like: ```json -{"version":2,"servers":{"review_evidence":{"transport":{"type":"https","url":"https://review-evidence.example.invalid/v1/mcp"},"auth":{"scheme":"Bearer","token_from":"REVIEW_EVIDENCE_MCP_TOKEN"},"tools":{"read_review_evidence":{"assurance":"advisory","resource_origins":["https://review-evidence.example.invalid"]}}}}} +{"version":3,"servers":{"review_evidence":{"transport":{"type":"https","url":"https://review-evidence.example.invalid/v1/mcp"},"auth":{"scheme":"Bearer","token_from":"REVIEW_EVIDENCE_MCP_TOKEN"},"tools":{"read_review_evidence":{"assurance":"advisory","description":"Read one operator-authorized review-evidence record by exact identifier.","input_schema":{"type":"object","properties":{"id":{"type":"string","maxLength":128}},"required":["id"],"additionalProperties":false},"resource_origins":["https://review-evidence.example.invalid"]}}}}} ``` GitLab accepts only `{type:"https",url:...}`. Local review also accepts `{type:"stdio",command:...,args:[...],env_from:{...}}` with an absolute operator-selected executable, no shell or setup hook, and owned child-process cleanup. HTTPS secrets use `auth.token_from` or `headers_from`; missing variables fail preflight. Literal secrets, redirects, ambient proxy trust, arbitrary link retrieval, resource/media projection, server-directed headers, sampling, roots, elicitation and OAuth are not supported. The official Python MCP SDK v2 is the primary toolkit integration boundary. SDK major versions do not select the wire protocol: the gateway negotiates each upstream independently and supports the explicitly qualified SDK v1/v2 peers and protocol revisions. Unsupported capabilities or revisions fail explicitly. -Receipt v13 embeds a content-free `ocr.federation/v2` receipt and independently reconciles OCR attempts with gateway terminal outcomes for every exported alias. Used advisory tools, known denied/failed calls, or an accounting mismatch make the run comment-only. Missing, corrupt, unfinalized or cleanup-uncertain federation evidence blocks normal publication. Configured-but-unused services and successful `review_read` use do not independently block approval when the actual target is protected. Commands, URLs, arguments, results, credentials, paths, identifiers and raw errors never enter the receipt. +The ordinary receipt embeds a content-free `ocr.federation/v2` receipt and independently reconciles OCR attempts with gateway terminal outcomes for every exported alias. Used advisory tools, known denied/failed calls, or an accounting mismatch make the run comment-only. Missing, corrupt, unfinalized or cleanup-uncertain federation evidence blocks normal publication. Configured-but-unused services and successful `review_read` use do not independently block approval when the actual target is protected. Commands, URLs, arguments, results, credentials, paths, identifiers and raw errors never enter the receipt. Federation v2 records closed argument/result DLP gate and reason counts. A result gate denial means the external context was unavailable to the review. Legacy @@ -278,11 +278,11 @@ Explicit `--local` continues without GitLab metadata, protection or default-bran reads. The new GitLab default does not turn a local review into a provider review or change local operator-file Rules. -For `auto` with an actually unprotected target T, the authenticated current MR must have matching positive source/target project IDs equal to `CI_PROJECT_ID`. The provider reads that project's default branch from authenticated project metadata, confirms that branch is protected, captures its immutable commit P, and uses P for repository-relative Rules, context policy, guidance, and accepted decisions. The code review remains the current MR's validated diff base B through source head H; B may differ from the current target head T. Code evidence keeps its actual code revisions, and policy evidence is labelled with P, never with T. An omitted `--rule` or absolute rule outside the checkout is rejected on this path because neither proves protected Rules provenance. Missing, unreadable or unprotected authority, contradictory project/diff identity, and unavailable policy objects stop with an explicit diagnostic; the toolkit does not choose another branch or promote source Rules. `off`, `metadata`, and `enriched` retain their meanings, and an existing registry-v2 federation configuration can run under its normal authorization, DLP, origin, and budget gates. Policy selection grants no new tool or credential authority. +For `auto` with an actually unprotected target T, the authenticated current MR must have matching positive source/target project IDs equal to `CI_PROJECT_ID`. The provider reads that project's default branch from authenticated project metadata, confirms that branch is protected, captures its immutable commit P, and uses P for repository-relative Rules, context policy, guidance, and accepted decisions. The code review remains the current MR's validated diff base B through source head H; B may differ from the current target head T. Code evidence keeps its actual code revisions, and policy evidence is labelled with P, never with T. An omitted `--rule` or absolute rule outside the checkout is rejected on this path because neither proves protected Rules provenance. Missing, unreadable or unprotected authority, contradictory project/diff identity, and unavailable policy objects stop with an explicit diagnostic; the toolkit does not choose another branch or promote source Rules. `off`, `metadata`, and `enriched` retain their meanings, and an existing federation configuration can run under its normal authorization, DLP, origin, and budget gates. Policy selection grants no new tool or credential authority. Exact `unprotected` with an actually unprotected target keeps the limited profile: context `off` or bounded `metadata`, no enriched context or governed federation, mandatory repository evidence, repository Rules read as untrusted guidance from T, and no structured guidance or accepted decisions. An omitted or external rule is rejected. These restrictions do not apply to the protected-policy `auto` path. Neither path treats an unprotected target as approved for merging into the default branch. -Both unprotected-target paths are structurally ineligible for a **new** automatic approval regardless of `OCR_AUTO_APPROVE`; an existing bot approval is not revoked. Receipt v13 records the actual target and selected policy authority separately. Its trusted `auto` summary says the target was unprotected, names the captured protected policy anchor by full P SHA, and states that automatic approval was unavailable. Exact `unprotected` retains the historical *limited, comment-only mode* line. Neither line changes OCR coverage or the primary clean/findings/warning/partial/budget/filtered outcome. A protected target has no unprotected-target line. Older, malformed, or contradictory receipts cannot establish the new authority. +Both unprotected-target paths are structurally ineligible for a **new** automatic approval regardless of `OCR_AUTO_APPROVE`; an existing bot approval is not revoked. The ordinary receipt records the actual target and selected policy authority separately. Its trusted `auto` summary says the target was unprotected, names the captured protected policy anchor by full P SHA, and states that automatic approval was unavailable. Exact `unprotected` retains the historical *limited, comment-only mode* line. Neither line changes OCR coverage or the primary clean/findings/warning/partial/budget/filtered outcome. A protected target has no unprotected-target line. Older, malformed, or contradictory receipts cannot establish the new authority. ### Review-context selector @@ -341,7 +341,7 @@ not acceptable. This setting does not change summary outcomes, fingerprints, suppression, approval, limits, or posting transactions. `OCR_AUTO_APPROVE` defaults to `true` and adds a formal GitLab approval after a -complete review publishes. It accepts `true`, `1`, `yes`, or `on`; set `false`, +complete, all-selected review publishes. It accepts `true`, `1`, `yes`, or `on`; set `false`, `0`, `no`, or `off` to disable the approval attempt for that run. An empty value uses the enabled default. Any other value fails closed to disabled and emits a bounded diagnostic without printing the value. The toolkit never removes an @@ -353,11 +353,13 @@ The initial policy is fixed: zero findings, or at most three findings whose severity is exactly `low` and category is exactly `style`, `documentation`, or `maintainability`, are eligible. Missing, unknown, differently cased, or non-string metadata blocks approval, as do warnings, failed or waived coverage, -partial/budget outcomes, any receipt other than exact v13, an unprotected actual target, disabled DLP, degraded selected metadata, used advisory federation tools or uncertain federation accounting, required context degradation, a DLP-rejected selected source, admitted remediation context, -and findings omitted by `OCR_MAX_POST_COMMENTS`. For receipt v13 on a protected target, complete metadata, complete non-remediation enrichment, private-only sanitization, unused federation services, successful `review_read` use, and the built-in evidence/context MCP are not blockers. GitLab posting revalidates the bound source/diff, actual target, policy authority and author before publication and again before any eligible approval. A changed or unverifiable tuple preserves the prior review; a same protected default-policy branch may advance only with proven ancestry while the completed review remains bound to captured P. The read-before-write check leaves a provider race. There are intentionally no +excluded immutable changed paths, any reused GitLab coverage, partial/budget outcomes, any receipt other than +the current ordinary receipt, an unprotected actual target, disabled DLP, degraded selected metadata, +used advisory federation tools or uncertain federation accounting, required context degradation, a DLP-rejected selected source, admitted remediation context, +and findings omitted by `OCR_MAX_POST_COMMENTS`. For an ordinary receipt on a protected target, complete metadata, complete non-remediation enrichment, private-only sanitization, unused federation services, successful `review_read` use, and the built-in evidence/context MCP are not blockers. GitLab posting revalidates the bound source/diff, actual target, policy authority and author before publication and again before any eligible approval. A changed or unverifiable tuple preserves the prior review; a same protected default-policy branch may advance only with proven ancestry while the completed review remains bound to captured P. The read-before-write check leaves a provider race. There are intentionally no environment variables for policy thresholds or category lists in this release. -`ocr-ci review --result PATH --stderr PATH -- ...` executes OCR without posting, creates private artifacts, and prints a bounded redacted stderr excerpt to the CI log when OCR fails. It accepts only a regular, single-link result artifact and atomically replaces it with the admitted owner-only copy. A validated ordinary GitLab merge-request review receives receipt v13; qualified partial gitlink reviews receive exact receipt v14. A local review remains receipt-less because local Git state cannot establish GitLab protection. A detached GitLab CI post requires v13 for ordinary results or v14 for qualified partial gitlink results; the compatible receipt-less posting path is standalone outside that CI profile and cannot use receipt-derived federation status, the unprotected-target limitation, or automatic approval. Errors without an authenticated full review identity remain in the job rather than creating a potentially stale MR note. For local diagnosis, `--local --debug-dir PATH` retains a bounded private bundle before ordinary cleanup. It requires --local; the GitLab profile cannot create it. The normal successful result is still finalized and filtered. Inspect the bundle before considering `OCR_DLP_ENABLED=false`, never upload or post it, and remove it afterward. Disabling DLP can expose sensitive content through model/service egress, local Markdown or GitLab and cannot retract prior disclosure. +`ocr-ci review --result PATH --stderr PATH -- ...` executes OCR without posting, creates private artifacts, and prints a bounded redacted stderr excerpt to the CI log when OCR fails. It accepts only a regular, single-link result artifact and atomically replaces it with the admitted owner-only copy. A validated ordinary GitLab merge-request review receives a receipt bound to coverage of the immutable diff. Qualified partial gitlink reviews receive a separate receipt. A local review remains receipt-less because local Git state cannot establish GitLab protection. A detached GitLab CI post requires the current receipt for the corresponding review type; the compatible receipt-less posting path is standalone outside that CI profile and cannot use receipt-derived federation status, the unprotected-target limitation, or automatic approval. Errors without an authenticated full review identity remain in the job rather than creating a potentially stale MR note. For local diagnosis, `--local --debug-dir PATH` retains a bounded private bundle before ordinary cleanup. It requires --local; the GitLab profile cannot create it. The normal successful result is still finalized and filtered. Inspect the bundle before considering `OCR_DLP_ENABLED=false`, never upload or post it, and remove it afterward. Disabling DLP can expose sensitive content through model/service egress, local Markdown or GitLab and cannot retract prior disclosure. It does not disable bounded inert-Markdown projection, destination validation, or unsafe-presentation rejection. ## Repository evidence @@ -371,7 +373,7 @@ Complete coverage or a matching file count cannot substitute for that identity. Legacy results without a manifest have no confirmed range claim and cannot automatically approve. Reports show the admitted base, head and effective range. -`ocr-ci review` owns this lifecycle. Before OCR starts it collects the exact immutable `--from`/`--to` refs (or the parent/commit pair selected by `--commit`), validates the exact GitLab MR identity and lifecycle, writes bounded redacted schema-versioned evidence, builds OCR's MCP registry with the mandatory evidence entry plus each independently configured optional server, reads the registry back, self-queries the evidence summary/list/get contract, and supplies the matching compact bootstrap to OCR. An already `merged` or `closed` MR stops before evidence and OCR with only an identity-bound `ocr.pre-execution-status/v5`; `post` upserts the corresponding static toolkit note. Those parent-process preflight calls are not counted as model use. The same preflight-qualified OCR executable first receives the exact production refs, rules, selection options, and background under `review --preview`; there is no toolkit threshold setting or duplicated OCR threshold constant. An exact recognized OCR soft background diagnostic becomes a toolkit-authored numeric `ocr.toolkit-advisory/v1` value only after publication DLP and appears in the bounded CI log plus GitLab Technical details. It is not an OCR warning, receipt or DLP input, coverage signal, telemetry field, or approval blocker. An exact recognized hard character/file-size rejection stops before model execution and leaves only an identity-bound numeric `ocr.pre-execution-status/v5` outcome for static GitLab reporting; the private path and raw OCR diagnostic are not published. Unclassified preview diagnostics fail closed before model execution with only an identity-bound v5 stage and bounded count; qualified changed gitlinks use v6 for no-model or unqualified status and v14 for successful partial review. Neither retains raw stderr in the status. The actual review independently revalidates the background. During OCR, the built-in MCP records count-only attempted and completed `summary`, `list`, `get`, `search`, and `coverage` actions without arguments, queries, IDs, paths, results, or content. Unknown or malformed MCP-dispatched primary-tool actions increment only a closed `unattributed` attempt counter. OCR also counts a dynamic tool request before parsing its JSON arguments; a parse failure never reaches the MCP owner, so receipt finalization adds only that count-only by-tool residual to `unattributed`. The parent reads and removes private action receipt v3 before cleanup. Receipt v13 is approval-valid only when MCP-received attempts do not exceed OCR's authoritative `tool_calls.by_tool` entries and every residual OCR attempt is accounted as unattributed; failed or malformed attempts cannot satisfy the mandatory completed `summary`, become successful evidence use, or authorize approval. Missing, malformed, raced, or mismatched attribution fails review finalization before a normal publishable result exists. OCR `--background-file` takes precedence over inline `--background`, so `ocr-ci review` rejects caller forms of both options, including split and `--option=value` syntax, and remains the sole owner of the bootstrap input; caller `--preview` is likewise rejected because the toolkit owns this gate. OCR provides `--output`, but `ocr-ci review` rejects its long, equals, short, and attached forms because the toolkit must remain the sole owner of the private result descriptor, atomic parsing, cleanup, and posting handoff. The stage-grouped OCR terminal retry report remains private and does not enter toolkit telemetry, receipts, DLP, findings, severity, outcomes, or approval. A completed OCR review is accepted only when structured `tool_calls.by_tool` proves at least one `ocr_toolkit_evidence` attempt and action receipt v3 proves a completed summary; a legitimately skipped no-supported-files review remains exempt. +`ocr-ci review` owns this lifecycle. Before OCR starts it collects the exact immutable `--from`/`--to` refs (or the parent/commit pair selected by `--commit`), validates the exact GitLab MR identity and lifecycle, writes bounded redacted schema-versioned evidence, builds OCR's MCP registry with the mandatory evidence entry plus each independently configured optional server, reads the registry back, self-queries the evidence summary/list/get contract, and supplies the matching compact bootstrap to OCR. An already `merged` or `closed` MR stops before evidence and OCR with only an identity-bound `ocr.pre-execution-status/v5`; `post` upserts the corresponding static toolkit note. Those parent-process preflight calls are not counted as model use. The same preflight-qualified OCR executable first receives the exact production refs, rules, selection options, and background under `review --preview`; there is no toolkit threshold setting or duplicated OCR threshold constant. An exact recognized OCR soft background diagnostic becomes a toolkit-authored numeric `ocr.toolkit-advisory/v1` value only after publication DLP and appears in the bounded CI log plus GitLab Technical details. It is not an OCR warning, receipt or DLP input, coverage signal, telemetry field, or approval blocker. An exact recognized hard character/file-size rejection stops before model execution and leaves only an identity-bound numeric `ocr.pre-execution-status/v5` outcome for static GitLab reporting; the private path and raw OCR diagnostic are not published. Unclassified preview diagnostics fail closed before model execution with only an identity-bound v5 stage and bounded count; qualified changed gitlinks use v6 for no-model or unqualified status and v14 for successful partial review. Neither retains raw stderr in the status. The actual review independently revalidates the background. During OCR, the built-in MCP records count-only attempted and completed `summary`, `list`, `get`, `search`, and `coverage` actions without arguments, queries, IDs, paths, results, or content. Unknown or malformed MCP-dispatched primary-tool actions increment only a closed `unattributed` attempt counter. OCR also counts a dynamic tool request before parsing its JSON arguments; a parse failure never reaches the MCP owner, so receipt finalization adds only that count-only by-tool residual to `unattributed`. The parent reads and removes private action receipt v3 before cleanup. The ordinary receipt is approval-valid only when the preview and manifest exactly partition the immutable changed paths, no path is excluded, and MCP-received attempts do not exceed OCR's authoritative `tool_calls.by_tool` entries and every residual OCR attempt is accounted as unattributed; failed or malformed attempts cannot satisfy the mandatory completed `summary`, become successful evidence use, or authorize approval. Missing, malformed, raced, or mismatched attribution fails review finalization before a normal publishable result exists. OCR `--background-file` takes precedence over inline `--background`, so `ocr-ci review` rejects caller forms of both options, including split and `--option=value` syntax, and remains the sole owner of the bootstrap input; caller `--preview` is likewise rejected because the toolkit owns this gate. OCR provides `--output`, but `ocr-ci review` rejects its long, equals, short, and attached forms because the toolkit must remain the sole owner of the private result descriptor, atomic parsing, cleanup, and posting handoff. The stage-grouped OCR terminal retry report remains private and does not enter toolkit telemetry, receipts, DLP, findings, severity, outcomes, or approval. A completed OCR review is accepted only when structured `tool_calls.by_tool` proves at least one `ocr_toolkit_evidence` attempt and action receipt v3 proves a completed summary; a legitimately skipped no-supported-files review remains exempt. For a changed Git submodule pointer, the toolkit admits only pure pointer additions, updates, deletions, or unambiguous moves under an exact @@ -423,8 +425,7 @@ Evidence-store schema v5 retains v1-v4 readback and adds the separately labelled In `metadata` mode, GitLab MR acquisition normalizes only title, description, labels, optional source branch, and the reviewed source SHA into `review.merge_request_context/v1`. Values are complete-field bounded, NFC-normalized, control-stripped, redacted, source-head-bound invocation data. Raw values never enter bootstrap, argv, environment, diagnostics, or receipts; bootstrap supplies an opaque record ID for direct `action=get` without `action=list`, field statuses, and toolkit-authored comparison guidance. In `off` mode none of those mutable text fields reaches normalization or persistence. OCR may treat matching intent as evidence against an assumption-dependent concern, contradictory intent as mismatch evidence, and missing intent as unknown. The source-branch hint is weaker than an explicit description and cannot establish rollout intent by itself. Metadata cannot authorize tools, policy, suppression, posting, or approval. In `enriched`, native context is acquired before OCR under protected policy; optional external reads remain model-directed through the separate governed federation. There is no arbitrary URL-fetch path or automatic reference acquisition in the model loop. -For a validated GitLab merge-request profile, the review step writes closed -ordinary receipt v13 or partial gitlink receipt v14 after mandatory +For a validated GitLab merge-request profile, the review step writes an ordinary or partial gitlink receipt after mandatory cleanup and the inode-checked atomic publication transformation. It binds project/MR, current diff base/start/head/version, actual target T/protection, selected policy P/protection/mode, source H, author, CI job, context, DLP, diff --git a/docs/contributor-intake.md b/docs/contributor-intake.md new file mode 100644 index 00000000..7bc0490a --- /dev/null +++ b/docs/contributor-intake.md @@ -0,0 +1,15 @@ +# Protected contributor intake + +## Configure GitHub + +1. Before creating or protecting `dev`, restrict `testpypi-public-disclosure`, `pypi-production` and `site-release-notification` to the named `main` branch. Confirm the registry Trusted Publishers match the expected workflows and environments, and scope the site dispatch credential to `site-release-notification`. Remove the repository-level copy of the site credential and verify the three environment selectors allow only the named branch. [Release configuration](release.md#required-configuration) · [GitHub deployment environments](https://docs.github.com/en/actions/concepts/workflows-and-actions/deployment-environments) +2. Keep `main` as the default branch. After credential isolation, create `dev` at the current protected `main` commit. Retarget the maintainer bootstrap PR to `dev` and verify fresh ready checks against that base. For external PRs, use the reviewed CI policy once it has landed on `dev`. Apply branch rulesets to both branches before retargeting any contributor PR. Require PRs, resolved conversations and the current ready-PR checks with strict base synchronization. Protect both refs from force pushes and deletion. Enable Allow merge commits in the repository settings, keep signed linear history on `main` and allow reviewed merge commits on `dev` for synchronization from `main`. Limit any administrator bypass to audited PR recovery. [GitHub branch rulesets](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets) +3. Require approval for all outside collaborators' workflow runs, keep the default `GITHUB_TOKEN` read-only and keep Actions PR approvals disabled. Use GitHub-hosted pull-request CI with pinned actions. Check effective runner permissions and confirm fork CI has no publishing environment, credentials, OIDC or artifact handoff to publishing jobs. Rebuild reviewed source for publication. [GitHub Actions repository settings](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/enabling-features-for-your-repository/managing-github-actions-settings-for-a-repository#controlling-changes-from-forks-to-workflows-in-public-repositories) Before opening intake, verify actual draft and ready checks on both routes. Confirm a bare dev push starts no publisher. On a dev-to-main PR update, inspect the runner permissions and confirm PR jobs have no OIDC or site credential. + +## Review and merge a PR + +1. Inspect GitHub's live PR metadata before approving its workflows. Confirm the author, source repository and branch, target branch, base SHA and head SHA. Fork PRs go to `dev`. A maintainer promotes repository-owned `dev` to `main` or prepares a stable release from a repository-owned `release/vX.Y.Z` branch with the exact title `Release vX.Y.Z`. Retarget or decline an external PR aimed at `main`. [Contributor guide](../CONTRIBUTING.md) · [Stable release](release.md#stable-release) +2. Review the full diff at those revisions before approving fork CI. Check workflow and executable changes, dependency and lockfile sources, installation and container inputs, Action pins and OCR qualification integrity values. Review additions and removals and both paths of renames and copies. Confirm a human updater's maintainer role in GitHub's repository access settings. For Dependabot updates to `dev`, verify the configured bot account, repository-owned branch and GitHub-verified commits through the reviewed head. Treat labels and branch names as context. Have a maintainer prepare dependency changes requested by an outside contributor. [Dependency audit and upstream review](development.md#dependency-audit-before-push) +3. Mark the PR ready and verify the full applicable protected CI ran and passed for the live base and head. Repeat review and checks when either revision changes. The maintainer verifies the author, source, target and revisions immediately before manual merge. Require an independent approval and dismiss stale approvals when there are two eligible maintainers. With a sole maintainer, record the exact revision reviewed and retain protected PR checks for maintainer-authored work. Squash eligible fork changes into `dev` with contributor attribution. For a CLI squash merge, supply the reviewed head with `gh pr merge "$PR_NUMBER" --squash --match-head-commit "$REVIEWED_HEAD"`. Whenever current main is no longer an ancestor of dev, including after a squash promotion or stable release, create a maintainer sync branch at the current `dev` tip, merge current `main` into it with a signed merge, and open a PR back to `dev`. Use a merge commit to preserve ancestry. Check that the current `main` tip is an ancestor of `dev` before the next promotion. [GitHub CLI merge options](https://cli.github.com/manual/gh_pr_merge) + +Dependabot's `target-branch: dev` applies to scheduled version updates. GitHub opens security update PRs against the default branch. Retarget those to `dev` for review or prepare the fix there on a maintainer branch. [Dependabot target-branch behavior](https://docs.github.com/en/code-security/reference/supply-chain-security/dependabot-options-reference#target-branch) diff --git a/docs/development.md b/docs/development.md index 123977f7..96e33f7a 100644 --- a/docs/development.md +++ b/docs/development.md @@ -30,28 +30,89 @@ A high combined result cannot hide a weak group. Individual DLP/audit, source syntax, shared credential material/completion, diagram-source metadata and orientation owners have 90% floors in the local and hosted coverage gates. Structural evidence sizing, bounded store serialization and optional target admission each have an independent 90% floor. -Hosted pull requests run source and contract +Ready hosted pull requests run source and contract tests on all six supported OS/Python combinations. The expensive clean-install wheel/sdist behavioral test runs once in the required Ubuntu/Python 3.12 job; the separate required build job smoke-tests both distribution paths. The five matrix jobs start alongside Python 3.12 rather than waiting for it. -The four Linux jobs are release-blocking, with Ubuntu on Python 3.14 as the sole -coverage owner. The two macOS endpoint jobs are best-effort compatibility +Each of the four Linux jobs can fail the CI workflow, with Ubuntu on Python +3.14 as the sole coverage owner. Effective branch rules determine which +individual checks GitHub requires before merge. The two macOS endpoint jobs are best-effort compatibility diagnostics: they remain visible for follow-up, but a platform-only failure does not block a Linux-priority release. Bandit scans only the supported runtime package at medium-or-higher severity and confidence; tests and synthetic fixtures are outside that bounded gate. +The Ubuntu/Python 3.14 coverage job installs the official Linux amd64 OCR +binary into its runner's temporary directory. It verifies the asset size and +SHA-256 recorded for the tested recommended version before making it available +to the native integration tests. All PRs use the committed target-base pin, +including repository-owned branches and Dependabot. Qualify new pins through +the OCR qualification workflow. A manual CI dispatch tests the committed +version of its selected revision. Native tests use isolated workspaces and +synthetic peers. Keep the compatibility manifest and capability records +synchronized when promoting OCR. The candidate must still recognize the exact +base asset during PR validation. A change that removes or replaces its recorded +digest requires a separate compatibility and recovery decision. + +Draft pull requests to `main` and `dev` run formatting, lint, type checking, +dependency review, and the secret scan under distinct draft check names. +The test matrices, package build and install smoke, Bandit, installed dependency +audit, and CodeQL wait for review readiness. Marking a pull request ready, +reopening it, updating its head, or editing its base starts checks for the +current GitHub test merge. Converting it to draft cancels in-progress review +CI on that pull request and uses the draft jobs. Manual and scheduled job +names also differ from the ready pull request contexts. Keep the existing +ready jobs required and confirm the successful jobs for the current candidate +and target before merging. See the [protected release path](release.md#stable-release) +for the additional release authorization. + Runtime code must remain compatible with the Python range and runtime dependencies declared in `pyproject.toml`; `uv.lock` owns the resolved dependency set. Tests must use synthetic data; public examples must use safe placeholder hosts and credentials while describing the real operating behavior rather than labelling the feature itself as synthetic. User-visible changes require a fragment in `changelog.d/`. Repository-only qualification tools and evidence live under `scripts/` and `compatibility/`; they are excluded from both published distributions. Validate the manifest with `PYTHONPATH=src python scripts/ocr_compat.py validate`. -For package, executable-integration, or release-machinery changes, install the wheel and sdist into separate temporary virtual environments, run `pip check`, and exercise the changed installed runtime entry point outside the checkout with repository paths removed from `PYTHONPATH`. `ocr-ci --help` proves console entry-point availability only; it does not prove dependency completeness or runtime execution. The official recipe and registry smoke share the hash-locked binary runtime installation and installed MCP/schema checks; dependency metadata changes must preserve that clean-install contract. Ordinary runtime changes rely on the pull request's single `Build artifacts` owner instead of rebuilding packages inside both CI jobs. Repeat deterministic builds locally only when reproducibility or release machinery is in scope. Before every commit, stage the intended files and run `scripts/gitleaks.sh --staged` to scan the exact candidate index for secrets and concrete local paths. Before every push, run `scripts/gitleaks.sh --tree` and the history gate below, plus the [dependency audit](#dependency-audit-before-push). The tree mode includes tracked and non-ignored untracked files without following symlinks; neither mode replaces the history scan. Failed or incomplete scanning blocks the commit or push. Install the exact Gitleaks version printed by `scripts/gitleaks.sh --version`, then run `scripts/gitleaks.sh` before pushing and `scripts/quality.sh check` for the Python quality matrix. The Gitleaks wrapper fails closed when the scanner version or base ref is unavailable, scans the complete first-parent feature history, and is also the single source for the hosted secrets job's version pin. TestPyPI and stable-release workflows do not duplicate that Gitleaks job. +For package, executable-integration, or release-machinery changes, install the wheel and sdist into separate temporary virtual environments, run `pip check`, and exercise the changed installed runtime entry point outside the checkout with repository paths removed from `PYTHONPATH`. Use `ocr-ci --help` to establish entry-point availability and exercise the changed installed behavior to establish runtime correctness. The official recipe and registry smoke share the hash-locked binary runtime installation and installed MCP/schema checks. Dependency metadata changes must preserve that clean-install contract. Ordinary runtime changes rely on the ready pull request's `Build artifacts` job. Repeat deterministic builds locally only when reproducibility or release machinery is in scope. + +Before every commit, run `scripts/gitleaks.sh --staged` on the intended index. +Before every push, fetch the upstream repository's intended PR target and pass +its refreshed ref to the history scan. Run `scripts/gitleaks.sh origin/dev` for +a PR targeting `dev` or `scripts/gitleaks.sh origin/main` for one targeting +`main`. Substitute the correct upstream remote name when working in a fork. +If the target is no longer an ancestor of your head, synchronize the candidate +with that target through its [PR workflow](contributor-intake.md) and rerun the +scan. Also run `scripts/gitleaks.sh --tree`, the +[dependency audit](#dependency-audit-before-push) and the applicable quality +checks. The tree mode includes tracked and non-ignored untracked files without +following symlinks. History mode scans the full base-to-head range, including +side-branch commits and each merge's diff against its first parent. It reads +scanner policy from the selected base commit and scans through candidate inline +suppressions. Failed or incomplete scanning blocks the commit or push. +Install the exact engine printed by `scripts/gitleaks.sh --version`. + +The hosted Secrets job reads the same version from the protected base checkout +and verifies the upstream binary archive against its reviewed checksum. It +fetches GitHub's public PR head ref without checkout credentials, checks its +SHA against the event, and scans the complete candidate range as Git objects +while leaving the base policy checked out. Trusted base +configuration and ignore files apply. Candidate inline suppressions are +disabled. The job reports a redacted result in the runner log and uploads no +scanner artifact. If the PR head has moved, inspect the run for its latest +revision. Review changes to the hosted workflow before approving each new +external head. + +When upgrading Gitleaks, add the new reviewed Linux x64 archive checksum to +`security.yml` alongside every version selected by a protected target base. +Update the local wrapper pin in the upgrade PR. Its hosted check still scans +with the base version. Verify the new engine locally and keep the older +checksum entries until both `main` and `dev` have advanced to the new wrapper +pin and old-base PR runs have been refreshed. `tests/test_installed_policy_e2e.py` builds both the direct wheel path and the sdist-to-wheel path, installs each into a clean environment, and exercises target decisions and nested guidance through the real stdio MCP. The required Ubuntu/Python 3.12 PR job owns this expensive behavioral check once; the other Python/OS jobs retain source tests, and the build and registry gates retain their distinct installed-artifact checks. It runs with a hostile repository shadow package, restricted `PATH`, owner-only artifacts, and the installed console entry point; keep package-boundary changes inside that test rather than replacing it with editable-install mocks. -GitHub Actions storage is repository-owned infrastructure. The repository's Actions setting retains new checks, workflow runs, statuses, artifacts and logs for two days; this setting does not retroactively shorten existing records. Individual artifact uploads also specify two days. Pull-request CI restores setup-uv caches but does not save branch-specific entries; protected-main publication may refresh shared dependency state. CodeQL TRAP caching and the separately controlled v4 overlay-database mode are disabled, so the small repository receives a full analysis without per-run CodeQL cache writes. The weekly **Actions storage maintenance** workflow grants `actions: write` only to its cleanup job and deletes all CodeQL caches, non-main or superseded setup-uv caches, superseded Gitleaks caches, artifacts older than two days, and completed runs after two days. Deleting a run removes its metadata, logs, artifacts and check metadata. Active and newer runs remain untouched. The scheduled collector reads a closed 16-day UTC window in daily shards, retaining a fail-closed ten-page limit per day instead of applying that limit to the aggregate run history. Manual dispatch is a dry run unless `execute` is selected; the same plan is available locally with `python scripts/actions_cleanup.py`, requires `--execute` for deletion, and accepts `--include-all-old-logs` for a deliberate one-time historical cleanup. +GitHub Actions storage is repository-owned infrastructure. The repository's Actions setting applies two-day retention to new checks, workflow runs, statuses, artifacts and logs. Individual artifact uploads also specify two days. First-party PR jobs can restore setup-uv caches, with saving disabled. Fork jobs disable both operations, and their distribution smoke check keeps artifacts local to the job. Keep base caches free of private packages and credentials. Protected-main publication may refresh shared dependency state. CodeQL TRAP caching and the separately controlled v4 overlay-database mode are disabled. Ready PRs receive full analysis and SARIF reporting to GitHub code scanning. Gitleaks downloads its verified binary without a cache. + +The weekly **Actions storage maintenance** workflow grants `actions: write` to its cleanup job on `main`. It deletes all CodeQL caches, non-main or superseded setup-uv caches, superseded Gitleaks caches, artifacts older than two days, and completed runs after two days. Deleting a run removes its metadata, logs, artifacts and check metadata. Active and newer runs remain untouched. The scheduled collector reads a closed 16-day UTC window in daily shards, retaining a fail-closed ten-page limit per day. Manual dispatch on `main` is a dry run until the operator selects `execute`. The local `python scripts/actions_cleanup.py` plan requires `--execute` for deletion and accepts `--include-all-old-logs` for a deliberate one-time historical cleanup. -For documentation-only or bookkeeping changes that do not alter runtime, packaging, dependencies, or CI behavior, run the existing contracts for the affected documents and review the instructions against representative tasks. The full local Python matrix is not required for that scope. Preserve applicable results for unchanged inputs; rerun affected checks after a material edit or failure. The hosted documentation-only classifier accepts only an exact nonempty commit range of explicitly allowed Markdown paths, rejects detected renames and uncertain Git evidence, and lets required Python, build, Bandit, and dependency-audit job names succeed without redundant work. Secrets, dependency review, CodeQL, and the pinned pre-push secret gate still run; any code, workflow, marker, artifact, or unknown path takes the full route. +For documentation-only or bookkeeping changes that do not alter runtime, packaging, dependencies, or CI behavior, run the existing contracts for the affected documents and review the instructions against representative tasks. The full local Python matrix is not required for that scope. Preserve applicable results for unchanged inputs; rerun affected checks after a material edit or failure. The hosted documentation-only classifier accepts only an exact nonempty commit range of explicitly allowed Markdown paths, rejects detected renames and uncertain Git evidence, and lets required Python, build, Bandit, and dependency-audit job names succeed without redundant work. Ready pull requests still run secrets, dependency review, and CodeQL for documentation-only changes. The pinned pre-push secret gate remains required. Any code, workflow, marker, artifact, or unknown path takes the full route once ready. During an authorized implementation task, run the scoped local tests that use synthetic fixtures and temporary resources, fix failures caused by the change, and rerun affected tests without asking for approval at each step. This does not authorize live provider calls, OCR execution, production access, or publication; follow the user's current constraints for those actions. @@ -524,11 +585,12 @@ Apply the [cohesive-module invariant](engineering/project_principles.md#product- ## Review reporting and provider adapters -`ocr_result.TOOLKIT_RESULT_SCHEMA_VERSION` owns ordinary receipt v13; +`ocr_result.TOOLKIT_RESULT_SCHEMA_VERSION` owns the current ordinary receipt format; `PARTIAL_TOOLKIT_RESULT_SCHEMA_VERSION` owns the qualified gitlink partial receipt v14. Posting accepts the exact current form for each result route; -automatic approval accepts only eligible v13 with verified native range. -The frozen v9-v12 result readback rules, shared tuple parser, and pre-execution +automatic approval accepts only an eligible ordinary receipt with verified native range and +complete immutable changed-path coverage. The frozen v9-v13 result readback +rules, shared tuple parser, and pre-execution status v5/v6 with unchanged embedded v11/v12 tuples are separate version-specific contracts. Evidence-budget status v7 also binds the existing v11 tuple and is not a completed review receipt. When a new receipt version is introduced, preserve @@ -624,7 +686,7 @@ Parser changes need legacy-format, duplicate-ID, malformed-field, unknown-field, `src/ocr_toolkit/context/` is independent from `ocr_toolkit.evidence`: contracts and normalization point downward; protected policy and fixed recognizers are pure; `broker.py` composes forge-context authorization, DLP, limits, and admission; `store.py` owns separate atomic hostile-read persistence and handle binding; `mcp.py` serves only the committed local store. `providers/gitlab_discussions.py` owns forge pagination, stable repeated snapshots, provider account classification, and run-local pseudonyms. Optional model-directed external tools belong to the separate governed `federation/` package, never the context store. `review_runner.py` is the sole orchestration owner that combines repository evidence, bounded forge context and federation into one OCR execution. -A new forge-context source must keep provider acquisition before OCR and enter the same broker/store/handle/MCP/publication/cleanup lifecycle. Do not restore executable adapters or policy-selected endpoints. A model-directed external read belongs in operator registry v2 behind the federation gateway, with an explicit allowlist, schema/origin/DLP/budget controls and content-free accounting. Neither path may add arbitrary link retrieval, a second store budget charged to evidence, or a second OCR/model pass. Schema discriminators on policy, store, registry, status and receipt boundaries prevent cross-contract interpretation; ephemeral M5/M7 state has no migration path. +A new forge-context source must keep provider acquisition before OCR and enter the same broker/store/handle/MCP/publication/cleanup lifecycle. Do not restore executable adapters or policy-selected endpoints. A model-directed external read belongs in operator registry behind the federation gateway, with an explicit allowlist, operator-owned interface, schema/origin/DLP/budget controls and content-free accounting. Neither path may add arbitrary link retrieval, a second store budget charged to evidence, or a second OCR/model pass. Schema discriminators on policy, store, registry, status and receipt boundaries prevent cross-contract interpretation; ephemeral M5/M7 state has no migration path. Boundary evidence must cross the production owner with a real Git repository, child process, local TLS peer, atomic file, stdio MCP client, installed artifact, or actual OCR as appropriate. Keep unavailable outcomes uniform across denial/not-found/foreign-tenant cases, and preserve explicit non-claims for adapter truth, broader service credentials, host compromise, semantic paraphrase, and model judgment. Update the public [bounded-context contract](review-context.md), threat model, test-evidence matrix, strategy, roadmap status, and Towncrier fragments whenever this lifecycle changes. @@ -653,4 +715,8 @@ Performance evidence must separate cold-start validation from steady-state reque ## Dependency Audit Before Push -Before every push, run `scripts/dependency-audit.sh`. This is the same `pip-audit` entry point as the pull request's `dependency-audit` security job: it synchronizes the committed lock with `uv sync --locked`, then audits the installed environment with `uv run --no-sync pip-audit`. It uses a dedicated ignored environment under `.quality-logs/`, preserving the caller's active environment, and runs with the CI-pinned uv 0.13.8 (using `uvx` when the installed `uv` differs). A stale lock, unavailable tool, vulnerability, or failed audit blocks the push; do not treat an incomplete scan as clean. The stable-release job separately audits its installed release environment with `--skip-editable`. +Before every push, check dependency and GitHub Actions freshness alongside the vulnerability audit. Inspect the locked Python tree with `uv tree --frozen --universal --outdated`, then compare the pinned Actions revisions with the upstream maintainers' supported releases and their exact commit SHAs. Review the open Dependabot PRs for both ecosystems and any applicable security advisories. A monthly Dependabot schedule can lag an upstream release. Apply applicable security updates through the maintainer or Dependabot path before pushing affected release work. Track ordinary available upgrades in their dedicated PRs, with compatibility or qualification reasons for retaining a pin. + +Repository maintainers own changes to dependency sources and integrity values, manifests and lockfiles, build backends and build tools, Python and uv pins, Actions, and installer scripts. The configured Dependabot integration can update its governed uv locks and fixed-SHA Action references. Review executable installation and workflow paths alongside manifests. Verify the upstream source, pinned object, permissions and combined lock resolution before merge. An external contributor can identify a needed update and link its evidence. The OCR qualification workflow prepares the evidence and patch for a maintainer to review and submit through protected intake. + +Before every push, run `scripts/dependency-audit.sh`. This is the same `pip-audit` entry point as the pull request's `dependency-audit` security job: it synchronizes the committed lock with `uv sync --locked`, then audits the installed environment with `uv run --no-sync pip-audit`. It uses a dedicated ignored environment under `.quality-logs/`, preserving the caller's active environment, and runs with the CI-pinned uv 0.13.10 (using `uvx` when the installed `uv` differs). The hosted workflows require an explicit release archive checksum for each runner platform. A stale lock, unavailable tool, vulnerability, or failed audit blocks the push; do not treat an incomplete scan as clean. The stable-release job separately audits its installed release environment with `--skip-editable`. diff --git a/docs/engineering/README.md b/docs/engineering/README.md index 1515250b..e632cf24 100644 --- a/docs/engineering/README.md +++ b/docs/engineering/README.md @@ -22,7 +22,7 @@ This index routes maintainers to canonical engineering owners without duplicatin ## Contracts and evidence - [Historical review-context design checkpoint](execution_history/review_context_design_checkpoint.md) — M5 foundation and its M7 supersession boundary. -- [Governed federation contracts](governed_federation_contracts.md) — current registry-v2 gateway, protocol, DLP, accounting, and approval boundaries. +- [Governed federation contracts](governed_federation_contracts.md) — current federation gateway, protocol, DLP, accounting, and approval boundaries. - [Historical evidence migration matrix](execution_history/evidence_migration_matrix.md) — completed evidence-contract replacement and parity record. - [Test evidence matrix](test_evidence_matrix.md) — coverage ownership for evidence domains and installed behavior. diff --git a/docs/engineering/governed_federation_contracts.md b/docs/engineering/governed_federation_contracts.md index 4047c8dc..5abeab1d 100644 --- a/docs/engineering/governed_federation_contracts.md +++ b/docs/engineering/governed_federation_contracts.md @@ -14,7 +14,7 @@ tools. Configuration parses the registry; federation owns schema validation, transport, dispatch, cache and lifecycle; review_runner coordinates admission; shared receipt/reporting owners interpret content-free results. -For GitLab, the current `auto` profile may use an already configured registry-v2 +For GitLab, the current `auto` profile may use an already configured federation gateway when the actual MR target T is unprotected and the same project's captured default branch P is protected. The registry and the gateway retain their independent operator/tenant/object/origin/DLP/budget gates; P does not @@ -24,8 +24,9 @@ retains its historical limited profile without federation. Local review keeps its own explicit configuration and does not initiate GitLab policy selection. Before OCR starts, an owned background async worker connects to configured -upstreams, discovers and freezes their allowlisted tools, validates schemas and -metadata, and reports readiness. The same sessions remain alive for execution. +upstreams, discovers and freezes their allowlisted tool names, validates the +operator-owned schemas and metadata, and reports readiness. The same sessions +remain alive for execution. OCR connects through a minimal fixed stdio relay to a private Unix socket. The socket directory is owner-only and the session accepts one bound client. No upstream secrets are serialized into OCR configuration or relay arguments. @@ -36,21 +37,24 @@ cleanup permits finalized receipt admission. Unknown cleanup blocks publication. This is process ownership, not a sandbox against an operator executable escaping its process group or a compromised host. -## Registry version 2 +## Registry version 3 -`OCR_MCP_SERVERS_JSON` is a strict object with `version: 2` and a `servers` object. +`OCR_MCP_SERVERS_JSON` is a strict object with `version: 3` and a `servers` object. Each server has `transport`, `tools`, optional HTTPS `auth` and `headers_from`. HTTPS transport is `{type: https, url: ...}`. Local-only stdio transport is `{type: stdio, command: ..., args: [...], env_from: {...}}`; the executable is an absolute operator-selected path and env_from maps child names to source names. GitLab accepts only HTTPS. An empty registry configures no external services. -Tool keys are upstream tool names; values hold optional `assurance` (default -`advisory`, or explicit `review_read`) and `resource_origins`. Origins default to -the configured HTTPS endpoint origin; explicit additional origins authorize only -URL-shaped arguments, never toolkit link retrieval. Registry fields contain no -credential values. Auth uses scheme `Bearer` and token_from naming an environment -variable; headers_from maps header names to variable names. +Tool keys are upstream tool names; values require an operator-authored `description` +and closed `input_schema`, and hold optional `assurance` (default `advisory`, or +explicit `review_read`) and `resource_origins`. The gateway exports and validates +only that operator interface; a live upstream description or input schema has no +model or argument authority. Origins default to the configured HTTPS endpoint +origin; explicit additional origins authorize only URL-shaped arguments, never +toolkit link retrieval. Registry fields contain no credential values. Auth uses +scheme `Bearer` and token_from naming an environment variable; headers_from maps +header names to variable names. Server/tool components start with an ASCII letter, contain ASCII letters, digits, underscore or hyphen, and cannot contain `__`. Exported `server__tool` aliases are @@ -84,9 +88,12 @@ process cleanup; the stock unbounded line reader is not an admission boundary. Initial limits are fixed, named product defaults: 16 servers, 128 exported tools, 64 KiB registry, 16 KiB per schema, schema depth 12, 512 nodes, 64 object properties, -32 enum values and eight combinator branches. Reject references, regex constraints, -dynamic/executable schema extensions and unsupported keywords rather than ignoring -them. Validate the admitted JSON Schema profile before model execution. +32 enum values and eight combinator branches for response schemas. Reject references, +regex constraints, dynamic/executable schema extensions and unsupported keywords +rather than ignoring them. Operator input schemas additionally require an explicit +top-level object, `additionalProperties: false` on every object, explicit item +schemas for arrays, and one concrete JSON type per node; combinators cannot broaden +argument data classes. Validate this profile before model execution. Arguments have 32 KiB, depth 16 and 1,024-node bounds. Responses have 256 KiB, 128K-character and 128-item limits, with 2 MiB admitted run aggregate. There are @@ -94,12 +101,34 @@ Arguments have 32 KiB, depth 16 and 1,024-node bounds. Responses have 256 KiB, deadline. Wire traffic is independently bounded to 256 requests and 8 MiB. Cache holds at most 32 entries and 1 MiB. Metadata totals at most 128 KiB. -Every argument crosses schema/origin/outbound DLP before upstream dispatch. Every -response crosses content-kind/bounds/inbound DLP before delivery. Descriptions -are external data too. Rejected, truncated or incomplete content is never returned -partially. Returned links remain inert. Reuse context.dlp rather than another -secret/PII detector; fixed authority instructions and lifecycle code prevent -external text from becoming policy or publication authority. +Every argument crosses the operator schema, origin policy and outbound DLP before +upstream dispatch. Every response crosses content-kind/bounds/inbound DLP before +delivery. The gateway validates every operator description and input schema before +opening any upstream connection, with DLP applied when enabled. Live upstream +descriptions and input schemas are never exported. Rejected, truncated or incomplete +content is never returned partially. Returned links remain inert. Reuse context.dlp +rather than another secret/PII detector; fixed authority instructions and lifecycle +code prevent external text from becoming policy or publication authority. + +Every delivered result string is also bound to its source server, including text +content and structured keys and values. Before dispatch, a destination rejects raw +exact matches, normalized exact matches and bounded long excerpts from both forms +learned from every other server. Excerpt matching requires at least one non-whitespace +character. The closed argument schema authorizes the argument keys, and the +provenance check applies to model-selected values. A queued call +checks again when it can dispatch to the upstream. Tools on the source server +may reuse their own results. The gateway registers provenance when delivering both +cached and shared-flight results. + +Every selected description and model-visible input-schema string is also registered +as external publication provenance before OCR starts. The bounded schema projection +exempts fixed JSON Schema keywords and type names at schema-node positions; dynamic +property names and keys inside defaults, examples and other data remain external. +Every delivered result registers text plus structured keys and values. Final +publication DLP matches short structural keys as whole tokens and attributes the +private material to `external_context`. The long-excerpt scan budget counts indexed +windows and source-corpus passes. A scan that exceeds its independent work or +representation limits fails closed. The federation receipt remains content-free. Cache only fully admitted successes, using server/tool/canonical arguments within one run. Each caller, including a cache hit or shared-flight waiter, gets its own @@ -120,9 +149,9 @@ this receipt. Historical v1 receipts remain readable, but their aggregate `dlp_rejected` count cannot identify a gate or reason and must not be retrospectively attributed. -Toolkit receipt v13/v14 binds federation reconciliation to the authenticated -B/H/T/P review identity and independently admitted native range. Frozen v9-v12 -remain historical readback and cannot authorize a current-result publication. External +The applicable toolkit receipt binds federation reconciliation to the authenticated +B/H/T/P review identity and independently admitted native range. Historical receipts +remain readable and cannot authorize a current-result publication. External gateway counts cannot prove source, target or protected-policy freshness; those checks occur separately before provider writes. @@ -153,7 +182,7 @@ Technical-details warning are emitted per accepted legacy policy. `OCR_REVIEW_CONTEXT_ADAPTERS_JSON`, its request/response protocol, `OCR_MCP_REPLACE`, inherited direct OCR MCP entries and legacy registry shapes -fail closed. Operators migrate reviewed external tools into registry v2 and +fail closed. Operators migrate reviewed external tools into registry v3 and reassess schemas, origins, assurance and credentials; federation is model-directed and is not a field-for-field conversion of pre-OCR adapter records. @@ -162,11 +191,12 @@ and is not a field-for-field conversion of pre-OCR adapter records. `OCR_DLP_ENABLED` is resolved once before acquisition and defaults to enabled. The strict boolean families are `true|1|yes|on` and `false|0|no|off`, case-insensitively; another value fails before OCR. False bypasses context and -federation ingress/egress DLP plus publication DLP only. Schema, size, time, -origin, identity, evidence, cleanup and posting-transaction gates remain active. +federation ingress/egress DLP plus publication DLP only. Cross-server result +provenance, schema, size, time, origin, identity, evidence, cleanup and +posting-transaction gates remain active. Disabled mode emits a prominent private warning and bounded Technical-details -warning, records the effective state in current receipt v13/v14, and is always comment-only. +warning, records the effective state in current ordinary or partial receipt, and is always comment-only. It may expose sensitive material through service/model egress, local Markdown or GitLab publication, and later re-enablement cannot retract prior disclosure. Operators should use the complete [local debug invocation](../local.md#private-debug-bundle) before this diff --git a/docs/engineering/review_signal_ownership.md b/docs/engineering/review_signal_ownership.md index b377be8f..388e01a7 100644 --- a/docs/engineering/review_signal_ownership.md +++ b/docs/engineering/review_signal_ownership.md @@ -7,24 +7,24 @@ telemetry API. The v0.12 receipt v10 was the earlier publication-accounting boundary. Its closed counts remain historical readback data; current provider writes require -the independently bound v13/v14 review identity, native range and separate freshness checks. +the independently bound review identity, native range and separate freshness checks. ## Source-to-signal matrix | Signal | Authoritative source | Toolkit projection | Privacy and authority boundary | | --- | --- | --- | --- | | Optional change diagram | Model proposal through the fixed private output collector; runner-owned source/DLP admission | Closed mode/state/counts and one admitted typed flow/sequence candidate; deterministic Mermaid in the report | Bounded labels/conditions/references may be retained after whole-unit admission. No raw source blobs, raw Mermaid, output destination or provider-write authority. Diagram faults/omission do not change findings, coverage or approval. | -| Provider/model identity, request/session correlation, retries, latency, HTTP outcome, and cost | OCR and its configured provider telemetry | One closed provider-failure class for static GitLab text; on failure, at most one local toolkit-authored line may add closed protocol detail, one shared HTTP status, and non-zero bounded retry counters | Raw identities, request IDs, response text, provider codes, URLs, paths, warnings, and stderr do not enter the projection, GitLab notes, receipt v13, DLP signals, toolkit telemetry, or approval. HTTP detail does not prove a provider business cause. | +| Provider/model identity, request/session correlation, retries, latency, HTTP outcome, and cost | OCR and its configured provider telemetry | One closed provider-failure class for static GitLab text; on failure, at most one local toolkit-authored line may add closed protocol detail, one shared HTTP status, and non-zero bounded retry counters | Raw identities, request IDs, response text, provider codes, URLs, paths, warnings, and stderr do not enter the projection, GitLab notes, ordinary receipt, DLP signals, toolkit telemetry, or approval. HTTP detail does not prove a provider business cause. | | Prompt, completion, cached, reasoning, and total tokens | OCR result and OCR telemetry | Closed non-negative provider-neutral token buckets in the result summary and canonical publication comparison | Unknown fields are ignored; malformed or contradictory counters are unavailable. Token counts never authorize approval or automatic routing. | | Review effort and executed rounds | Operator-owned root `effort` config and OCR runtime | `OCR_REVIEW_EFFORT` writes one closed `low`, `medium`, or `high` setting; the toolkit does not publish inferred round telemetry | Merge-request content cannot select effort. Budget or incomplete coverage remains approval-ineligible through the existing result contract. | -| Semantic grouping, group file membership, per-group spans, and filter activity | OCR runtime and OCR telemetry | Additive private result fields may be DLP-sanitized; no group or round field enters receipt v13, GitLab text, fingerprints, severity, lifecycle commands, toolkit telemetry, or approval | Group labels are model-produced. Group keys are sorted changed paths, so both are untrusted and potentially high-cardinality. | -| Tool requests and MCP use | OCR result for aggregate attempts; internal evidence and federation gateway for authenticated attempts/outcomes | Mandatory action-receipt-v3 accounting plus content-free per-alias federation reconciliation in receipt v13 | Arguments, paths, queries, scopes, IDs, results, headers and content are excluded. | -| Selection, completed/reused/failed/waived coverage, and aggregate-budget stop | OCR run manifest | Closed result outcome, summary, receipt validation, and approval blockers | Incomplete, malformed, failed, waived, or budget-stopped coverage fails closed; no duplicate toolkit budget metric is needed. | +| Semantic grouping, group file membership, per-group spans, and filter activity | OCR runtime and OCR telemetry | Additive private result fields may be DLP-sanitized; no group or round field enters ordinary receipt, GitLab text, fingerprints, severity, lifecycle commands, toolkit telemetry, or approval | Group labels are model-produced. Group keys are sorted changed paths, so both are untrusted and potentially high-cardinality. | +| Tool requests and MCP use | OCR result for aggregate attempts; internal evidence and federation gateway for authenticated attempts/outcomes | Mandatory action-receipt-v3 accounting plus content-free per-alias federation reconciliation in ordinary receipt | Arguments, paths, queries, scopes, IDs, results, headers and content are excluded. | +| Selection, completed/reused/failed/waived coverage, and aggregate-budget stop | Toolkit immutable Git inventory, native preview and terminal manifest | Path-free counts and digest bind the ordinary partition. Qualified preview-only exclusions require a separate proof and block approval. | Incomplete, malformed, failed, waived, or budget-stopped coverage fails closed; no duplicate toolkit budget metric is needed. | | Findings, severity, fingerprints, suppression, resolution, and repeated discussions | OCR findings plus toolkit-owned posting snapshots and human commands | GitLab discussions, summary, exact fingerprints, and closed lifecycle state | Remediation text and additive group metadata cannot change severity, prove resolution, suppress findings, or issue commands. | -| Context admission, degradation, mutation, and evidence use | Toolkit broker/store and fixed MCP receipts | Count-only receipt-v13 context/evidence state | Raw merge-request title, description, discussions, CI provider identities/payloads, rejected text, and record contents do not enter the receipt or telemetry event. | -| Current MR and policy authority identity | Authenticated GitLab provider snapshot plus bounded Git ancestry check | Receipt v13 binds source H, diff B/version, actual target T and protected policy P independently; closed preflight and post-time stale/unavailable reasons | B..H is the review range, T code context is untrusted, and P grants review capabilities only. A newer protected P needs same-branch fast-forward proof; unprotected T never grants approval. Branch names and provider text do not enter trusted diagnostic prose. | +| Context admission, degradation, mutation, and evidence use | Toolkit broker/store and fixed MCP receipts | Count-only receipt context/evidence state | Raw merge-request title, description, discussions, CI provider identities/payloads, rejected text, and record contents do not enter the receipt or telemetry event. | +| Current MR and policy authority identity | Authenticated GitLab provider snapshot plus bounded Git ancestry check | The ordinary receipt binds source H, diff B/version, actual target T and protected policy P independently; closed preflight and post-time stale/unavailable reasons | B..H is the review range, T code context is untrusted, and P grants review capabilities only. A newer protected P needs same-branch fast-forward proof; unprotected T never grants approval. Branch names and provider text do not enter trusted diagnostic prose. | | Actual-target repository context | Immutable Git reader and evidence store v5 | Bounded T records served through the existing evidence MCP as `target_repository` code evidence | T neither replaces B/H/P, changes deltas or proves absence nor makes unprotected rules authoritative. An incomplete T stays explicit and cannot evict base/head/policy evidence. | -| Publication DLP and posting transaction state | Toolkit result projection and GitLab transaction owner | Receipt-v13 stage-aware state, one parseable summary marker, and one local count-only log event | OCR coverage, DLP omission and posting outcomes remain separate; source-class counts can overlap and no rejected value or location is emitted. | +| Publication DLP and posting transaction state | Toolkit result projection and GitLab transaction owner | Stage-aware receipt state, one parseable summary marker, and one local count-only log event | OCR coverage, DLP omission and posting outcomes remain separate; source-class counts can overlap and no rejected value or location is emitted. | | OCR compatibility qualification | Compatibility workflow and checksum-pinned evidence | Canonical issue plus bounded success or failure artifact | Public failure status contains only closed phase/reason/version/run fields. Raw qualification exceptions stay in the job log. | ## OCR telemetry privacy diff --git a/docs/engineering/test_evidence_matrix.md b/docs/engineering/test_evidence_matrix.md index 303df8f9..885e3f21 100644 --- a/docs/engineering/test_evidence_matrix.md +++ b/docs/engineering/test_evidence_matrix.md @@ -2,6 +2,14 @@ This matrix records what the repository test suite proves and, equally importantly, what it does not prove. The governing rule is [Test doubles and integration proof](project_principles.md#test-doubles-and-integration-proof): a double may replace a collaborator beyond the production owner under test, but it may not replace that owner and still be cited as integration evidence. +## Immutable ordinary-review coverage + +| Boundary | Evidence | Limit | +| --- | --- | --- | +| Immutable Git range to native selection | `plan_review_input` and `make_gitlink_projection` derive the complete ordinary `B..H` delta; `qualify_review_preview` requires an exact disjoint selected/excluded partition with closed reasons. `test_ordinary_projection_binds_exclusion_to_manifest` uses a real temporary Git repository containing a tracked ignored file. | The preview and OCR result remain native claims; this proves toolkit reconciliation, not model judgment. Unsupported tree modes and over-budget diffs fail closed rather than gaining a partial-review claim. | +| Native manifest to receipt and approval | `qualify_review_manifest` binds selected fingerprints, excluded identities/reasons, source-artifact digest and range. The ordinary receipt carries path-free counts and a partition digest; `automatic_approval_metadata_reason` and `evaluate_approval_policy` reject every exclusion while the all-selected control remains eligible. | Synthetic manifests and receipts prove parser and policy behavior. Exact native producer behavior remains owned by checksum-qualified OCR compatibility evidence. | +| Persisted result to GitLab posting | `verified_review_coverage` rebuilds the immutable range and partition before any write, including path-free DLP-filtered handoffs. Partial coverage renders as incomplete, preserves prior findings and cannot authorize approval. | Posting tests replace GitLab mutations; no live provider write, merge-policy enforcement or concurrent read-after-check guarantee is claimed. | + ## Local GitLab telemetry | Boundary | Evidence | Limit | @@ -364,10 +372,11 @@ availability and routing, not natural model choice or private service behavior. | Requirement or boundary | Production owner and entry point | Required observable result | Evidence | Double boundary and claim limit | State | | --- | --- | --- | --- | --- | --- | -| Registry v2 and mandatory internal evidence | `federation.registry.parse_registry`; `mcp_config.compose_mcp_servers` | closed registry, reserved-name/collision rejection, environment-backed credentials, and an unreplaceable independent evidence MCP | `test_mcp_config_v2.py`, admission tests, exact config round-trip/redaction tests, and installed wheel/sdist review | parser/config tests prove toolkit authority; they do not prove an upstream service's authorization | proven | +| Registry v3 and mandatory internal evidence | `federation.registry.parse_registry`; `federation.gateway.Gateway.prepare`; `mcp_config.compose_mcp_servers` | closed operator descriptions/input schemas remain model and argument authority despite hostile live-definition drift; reserved names/collisions reject, credentials stay environment-backed, and evidence MCP remains independent | `test_mcp_config_v3.py`, closed argument-schema admission tests, real TLS description/schema-drift tests, exact config round-trip/redaction tests, and installed wheel/sdist review | parser/config and controlled peers prove toolkit authority; they do not prove an upstream service's authorization or truth | verified with controlled peers | | HTTPS/stdio gateway and independently negotiated peers | `federation.transport`, `federation.start_gateway`, private relay | real TLS and child-process sessions cross byte/request/deadline/schema/origin/DLP bounds; SDK-v1/v2 peers and OCR negotiate independently; cleanup uncertainty blocks receipts | `tests/federation/` real TLS/stdio/relay tests, opt-in SDK-v1/v2 matrix, and checksum-verified OCR qualification | controlled peers sit beyond production transports; they prove interoperability and containment, not service truth or model judgment | proven for qualified peers and OCR | | Cache, single-flight, cancellation and content-free accounting | `Gateway.call`, run-local cache, `reporting.federation` and receipt v10 (compatible v9) | each caller has one reconciled terminal outcome; cancelled waiters do not cancel shared work; only admitted successes cache; hostile receipts fail closed | gateway concurrency/cancellation tests, hostile receipt validators, OCR-attempt reconciliation and approval tests | deterministic peers select timing and outcomes; no performance or availability claim for production upstreams | proven | -| Default-on and explicitly disabled DLP | shared `context.dlp` mode, context store, federation gateway, publication projection and reporting | one resolved mode crosses parent and isolated evidence child; false bypasses only DLP, emits warnings, records receipt state and blocks approval while structural gates remain | DLP attribution/toggle tests, real stdio context subprocess with opposing ambient environment, local/GitLab formatter and approval regressions | deliberately unsafe sample values prove the escape-hatch path; disabling DLP cannot make external egress safe or retract it | proven for toolkit behavior | +| Cross-server result provenance | `Gateway.call_tool` result delivery -> source matcher -> destination argument admission | delivered result material may return to its source server. Other servers reject whole matching argument values and long matching excerpts, including material delivered from cache or shared-flight calls | `test_cross_server_result_egress_is_denied_without_blocking_source_reuse`, `test_result_provenance_includes_structured_keys_and_values` and `test_dlp_disabled_relay_preserves_exact_result_provenance_and_admits_unrelated_inputs` | controlled calls cover exact matches and bounded long excerpts. Cache and shared-flight callers share the same delivery path; these tests do not isolate their first registration. Semantic paraphrases and service authorization remain external | verified with controlled peers | +| Default-on and explicitly disabled DLP | shared `context.dlp` mode, context store, federation gateway, publication projection and reporting | one resolved mode crosses parent and isolated evidence child; false bypasses semantic material rejection but keeps bounded inert-Markdown projection and unsafe-destination rejection, emits warnings, records receipt state and blocks approval | DLP attribution/toggle tests, disabled-mode safe-markup composition, real stdio context subprocess with opposing ambient environment, local/GitLab formatter and approval regressions | deliberately unsafe sample values prove the escape-hatch path; disabling DLP cannot make external egress safe or retract it | proven for toolkit behavior | | Policy migration and actual-use approval | policy v1-v4 parser, legacy degradation, receipt v10 (compatible v9) and posting policy | v1-v3 references never execute; required legacy work degrades; unused/review-read federation can remain eligible while advisory use/failure/mismatch is comment-only and cleanup uncertainty blocks | policy, runner, installed-package, receipt, posting and approval suites plus public-contract tests | no legacy vendor service is contacted; live GitLab writes and configured-model quality remain external handoff gates | proven with stated non-claims | ## v0.6.3 context, approval, and GitLab write reconciliation evidence @@ -394,7 +403,7 @@ The M5 negative suite is an attacker matrix, not merely a replay of observed rev | BOLA/confused deputy/service credential mismatch | `context.adapters.authorize_and_resolve` plus `context.broker.acquire_external_records` before handle minting | real stdio and local-TLS peers exercise operator tenant/resource allowlists, request/run mismatch, uniform unavailable, replacement, and cross-tenant denial | proven for toolkit broker/protocol; adapter service truth remains a deployment non-claim | | Arbitrary URL/ID, SSRF, redirects, traversal, writes | `context.recognizers.recognize`, broker admission, redirect-free fixed transports, and `context.mcp.call_context_tool` | fixed-grammar/malformed-authority/config/redirect tests plus real one-process stdio MCP prove only committed handles reach `context_get`; arbitrary IDs, URLs, malformed/tampered cursors, unknown args/tools and source-bound cursors fail before store access | deterministic toolkit path and real local MCP proven; the real OCR run advertised both tools but made zero context calls, so model-driven list/get is not claimed | | Oversize, omission, TOCTOU, replay | separate request/admission/streaming limits, repeated bounded GitLab digest, aggregate orchestration, and `context.store.ContextStore` binding | real child/TLS no-read, request-write timeout, oversize, partial/multiple frame and bounded-pagination mutation; authorization-before-budget, exact/changed duplicate, hard-link/persistence/recursive-readback, version, lifetime and replay cases | proven through production transport owners, committed store, and local MCP readback | -| PII/secret leakage and output laundering | `context.dlp.check_text`, `review_runner._publication_projection`, and `ocr_result.transform_ocr_result` own one inode-checked sink/private-retention projection and receipt replacement after cleanup; explicit local preservation may add only the bounded value-free `_private_dlp_decisions` attribution | multibyte/line/PII/secret, bare SHA/build and separator-bearing technical-ID false-positive classes, whole-value, 24-character exact excerpt, hidden-only/nested HTML source, inline/reference/autolink Markdown, private-key/value sanitization, path/decision bounds, and work-bound tests cover retrieval and raw OCR result; unsafe sink units disappear while private-only fields are sanitized without losing a valid manifest; prior review, one-for-one fingerprint matching, approval blocking, summary marker and log event remain | corrected publication behavior and value-free local attribution are proven deterministically through the production transform/sidecar/posting owners. The real triggering run predates the final correction and is not cited as exact-final-tree proof; operators must compare sidecar digests to separately retained private data before classifying a conservative match | +| PII/secret leakage and output laundering | `context.dlp.check_text`, context provider/broker admission, `context.store.validate_model_projection`, `context.mcp.call_context_tool`, `review_runner._publication_projection`, and `ocr_result.transform_ocr_result` own model-egress, sink/private-retention and receipt replacement boundaries; explicit local preservation may add only the bounded value-free `_private_dlp_decisions` attribution | multibyte/line/PII/secret, raw/decimal/hexadecimal/nested entity contacts, decoded markup destinations, harmless entity preservation, hostile store readback and final in-memory MCP revalidation join the existing technical-ID, exact-excerpt, hidden HTML, Markdown, sanitization and work-bound cases; unsafe sink units disappear while private-only fields are sanitized without losing a valid manifest | deterministic tests cover acquisition through final model projection and publication transform without claiming natural model choice. The real triggering run predates the final correction and is not cited as exact-final-tree proof; operators must compare sidecar digests to separately retained private data before classifying a conservative match | | Identity spoofing | `providers.gitlab_discussions.acquire_discussions` provider class plus run-local pseudonym; unknown fails closed | repeated real-TLS provider classification, ordered pagination, unknown actor, mutation, and display-identity exclusion | proven for GitLab acquisition | | Same-revision CI identity and scope | `providers.gitlab_ci.acquire_gitlab_ci_outcomes` plus `context.ci_outcomes.prepare_ci_outcome_records`; protected policy v3 owns exact check names and path prefixes | exact-head/current-versus-other-pipeline, stale, duplicate retry, pagination, mutation, hostile payload, DLP, store replay, MCP list/get, bootstrap, and approval-independence tests | proven for bounded GitLab acquisition and provider-neutral projection; job truth and model use remain service/model non-claims | | Prompt injection and authority escalation | fixed adapter fields, static bootstrap authority text, exact marker preambles, and fixed `context_list`/`context_get`; context cannot alter policy/tools/commands/suppression/approval | hostile schema/description and marker-smuggling tests, fixed MCP declarations, separate evidence-call accounting, and receipt approval tests pass; the real OCR run saw the fixed three-tool declaration but did not call context tools | deterministic authority boundaries proven; model judgment and model context consumption remain non-claims | @@ -511,7 +520,7 @@ Every top-level test module is classified below. A module can contain more than | `test_posting_helpers.py` | pure formatting/workflow policy, real Git reads, real local HTTP create serialization and paginated reconciliation reads, real result-file boundaries | mocked GitLab API owner cases prove response/error/workflow behavior only; local peers prove transport/completeness mechanics, not live GitLab semantics | | `test_posting_no_write_diagnostics.py` | invalid/stale/unavailable handoff classification, cross-job static-status rejection, and static-note gating | captured note writes prove no-write boundaries, not live provider delivery | | `test_posting_suggestions.py` | pure proof-bound suggestion decisions | fake readers are collaborators beyond the pure decision owner; no Git blob integration claim | -| `test_posting_v11_flow.py` | current v13 normal, partial, stale and approval ordering plus frozen pre-execution tuple handoffs | provider/API doubles prove decisions and payload shape, not live mutation or race elimination | +| `test_posting_v11_flow.py` | current normal, partial, stale and approval ordering plus frozen pre-execution tuple handoffs | provider/API doubles prove decisions and payload shape, not live mutation or race elimination | | `test_provider_failure.py` | strict bounded retry-report v1 parsing and closed provider-neutral reason projection | fixture records prove the toolkit parser only; actual OCR request behavior is separately observed by the compatibility probe | | `test_python_support.py` | static metadata/CI support range | supported interpreters are proven by the quality matrix, not this test alone | | `test_quality_script.py` | real synthetic Git history for Gitleaks range plus static wrapper policy | fake scanner proves wrapper invocation/range, not secret-detection efficacy; pinned real Gitleaks runs before push | @@ -522,7 +531,7 @@ Every top-level test module is classified below. A module can contain more than | `test_review_context.py` | real store persistence/hostile reload and MCP component projection | direct dispatcher is not stdio; stdio proof is installed/full-preflight E2E | | `test_review_runner.py` | private result/filesystem owner, real child-process launcher, receipt parser; separate wiring tests | patched subprocess/orchestration tests are explicitly unit evidence only | | `test_review_receipt_v11.py` | hostile v11 review identity, policy capability and historical compatibility parsing | synthetic receipt values prove validation, not authenticated producer truth | -| `test_review_receipt_v13.py` | current range/diagram grammar, optional failure accounting, approval neutrality and v14 partial proof | synthetic receipts prove validation; native and installed producer boundaries are covered separately | +| `test_review_receipt_v13.py` | range and diagram grammar, optional failure accounting, approval neutrality and v14 partial proof | synthetic receipts prove validation; native and installed producer boundaries are covered separately | | `test_runtime_helpers.py` | config filesystem boundaries and real local preflight HTTP transport; MCP/config parsing | mocked binary and `URL_OPENER` cases prove version/request/error policy only, not executable/network integration | | `test_testpypi_preview.py` | registry-manifest parser and static workflow contract | fixture index payloads do not prove publication; live TestPyPI/PyPI verification is a release gate | diff --git a/docs/engineering/toolkit_strategy.md b/docs/engineering/toolkit_strategy.md index 5a9e6596..7e670a9c 100644 --- a/docs/engineering/toolkit_strategy.md +++ b/docs/engineering/toolkit_strategy.md @@ -50,13 +50,13 @@ no review content. Reasoning effort is a protocol-specific configuration overlay not a model-profile router. These capabilities do not activate a second forge, repository scanning, automatic profile routing or another telemetry layer. -The M1 implementation provides a schema-versioned Repository Evidence Engine with bounded immutable base/head reads, typed dependency/runtime/image/guidance records and deltas, redaction-before-storage, a compact bootstrap, and the built-in read-only `ocr_toolkit_evidence` MCP server. MCP configuration always registers that server independently from optional registry-v2 federation. +The M1 implementation provides a schema-versioned Repository Evidence Engine with bounded immutable base/head reads, typed dependency/runtime/image/guidance records and deltas, redaction-before-storage, a compact bootstrap, and the built-in read-only `ocr_toolkit_evidence` MCP server. MCP configuration always registers that server independently from optional federation. The legacy `context/*` Markdown renderer, its CLI/environment contract, and its parity-only bridge have been removed. The evidence store and compact bootstrap are private artifacts owned by `ocr-ci review`, not separately configured workflows. -The built-in evidence MCP is mandatory for ordinary evidence-backed reviews. Optional HTTPS or local stdio upstreams remain behind one toolkit-owned federation gateway; operator registry v2 cannot remove, replace or shadow the built-in server. The compact bootstrap is generated from the same validated capability inventory that is written to OCR. +The built-in evidence MCP is mandatory for ordinary evidence-backed reviews. Optional HTTPS or local stdio upstreams remain behind one toolkit-owned federation gateway; operator registry cannot remove, replace or shadow the built-in server. The compact bootstrap is generated from the same validated capability inventory that is written to OCR. -GitLab result normalization and posting are implemented behind provider-oriented modules. They bound and neutralize model-controlled text, use stable finding fingerprints, preserve human-owned discussions, and expose no forge write tools or forge credentials in OCR configuration/arguments; the trusted OCR child can still inherit operator environment credentials. Receipt v13 retains the v10 publication, DLP, evidence and federation contracts while binding the current MR diff version, actual code target, and policy authority independently. Actual target protection controls approval; a separate protected policy snapshot can authorize review context and governed tools for an unprotected target without conferring approval. OCR coverage, public-projection integrity, published findings, core advisories, reconciled count-only evidence use, privacy-safe normalized token buckets, multi-finding Recommended focus ranking, and collapsed technical details are separate implemented concepts. The current recommended and tested OCR baseline belongs in the operational compatibility contract, not this durable strategy. +GitLab result normalization and posting are implemented behind provider-oriented modules. They bound and neutralize model-controlled text, use stable finding fingerprints, preserve human-owned discussions, and expose no forge write tools or forge credentials in OCR configuration/arguments; the trusted OCR child can still inherit operator environment credentials. The ordinary receipt retains the v13 publication, DLP, evidence and federation contracts while binding the complete immutable changed-path partition, current MR diff version, actual code target, and policy authority independently. Actual target protection controls approval; a separate protected policy snapshot can authorize review context and governed tools for an unprotected target without conferring approval. OCR coverage, public-projection integrity, published findings, core advisories, reconciled count-only evidence use, privacy-safe normalized token buckets, multi-finding Recommended focus ranking, and collapsed technical details are separate implemented concepts. The current recommended and tested OCR baseline belongs in the operational compatibility contract, not this durable strategy. ## Implemented Repository Evidence Engine @@ -131,10 +131,11 @@ Version-specific library documentation belongs to a separate future documentatio ## Governed MCP federation -M7 supersedes the historical M3 direct-composition boundary. Operator registry v2 +M7 supersedes the historical M3 direct-composition boundary. Operator registry configures reviewed upstreams behind one toolkit-owned gateway; external entries -are never passed directly into OCR. The gateway freezes allowlisted tools and -schemas, validates arguments/origins/DLP/bounds, owns transport lifecycle and +are never passed directly into OCR. The gateway freezes allowlisted tools, exports +operator-owned descriptions and closed input schemas, validates +arguments/origins/DLP/bounds, owns transport lifecycle and reconciles a content-free receipt. The mandatory internal evidence MCP remains a separate unreplaceable server and successful evidence use remains required. @@ -142,7 +143,7 @@ GitLab accepts HTTPS upstreams only; local review may also use an explicit absolute stdio executable with no shell or setup hook. The official SDK v2 is the primary integration boundary, while wire revisions are negotiated independently with explicitly supported SDK v1/v2 peers. Upstreams retain tenant/object -authorization responsibility. Current receipt v13 retains the v0.12/v10 federation contract: used advisory tools, known +authorization responsibility. The current ordinary receipt retains the v0.12/v10 federation contract: used advisory tools, known failures/denials and accounting mismatches comment-only; uncertain cleanup or an invalid federation receipt blocks normal publication. Unused services and successful `review_read` use are not independent approval blockers. @@ -151,15 +152,16 @@ successful `review_read` use are not independent approval blockers. M5's foundation is established in v0.7.0. It extends the v0.6.3 selection/approval foundation with protected-target policy, stable GitLab discussions, deterministic references, provider-neutral adapters, a separate private context store, opaque handles, fixed `context_list`/`context_get`, isolated OCR sessions, publication DLP, receipt v4, and closed setup/CI-uncertainty outcomes. Receipt v5 in v0.7.1 superseded the result/posting contract without changing the established acquisition boundary. The v0.8.0 release tree adds policy v2 remediation selection, private context-store v2, authenticated toolkit-root ownership, fixed remediation projections, live-username mention commands, and explicit provider-neutral forge views. Toolkit 0.8.7 advanced output to receipt v6 and action receipt v2 for two additional fixed evidence search/coverage tools without reopening provider access or approval authority. Toolkit 0.9.0 advanced the then-current result boundary to receipt v8, advanced the private action receipt to v3 with separately authenticated attempted and completed counters, and added a separately constrained path for an explicitly permitted unprotected GitLab target. That path is comment-only, rejects enriched context, adapters, protected policy acquisition, and direct or inherited external MCP before OCR, omits accepted decisions and structured project guidance, and exposes only immutable repository evidence plus bounded target Rules. It is not protected-policy equivalence and cannot authorize approval. The owner waived the separate enriched OCR+LLM qualification: no receipt proves model-time `context_list`/`context_get`, still-present/evidence-resolved scenarios, or receipt-level raw provider-data leakage inspection. The protected release workflow and independent registry/GitHub readback remain mandatory delivery proof but do not substitute for that absent qualification. -For the current GitLab profile, a closed receipt v13 binds source H, authenticated current MR diff base/version B, actual target branch/head T and protection, and protected policy project/branch/commit P as separate identities. An absent `OCR_GITLAB_TARGET_PROTECTION_MODE` selects `auto`: a protected actual target supplies P itself, while an unprotected target can use the same project's captured protected default branch P for rules and eligible context/tool policy without gaining approval authority. Explicit `required` still rejects an unprotected target; explicit `unprotected` keeps the historical limited comment-only profile. The actual review remains B..H even when B differs from T. Detached MR source identity is required; synthetic merged-results and merge-train commits are not silently treated as H. The local entry point does not select GitLab policy or create a platform receipt. +For the current GitLab profile, a closed ordinary receipt binds source H, authenticated current MR diff base/version B, the complete ordinary changed-path selection partition, actual target branch/head T and protection, and protected policy project/branch/commit P as separate identities. An absent `OCR_GITLAB_TARGET_PROTECTION_MODE` selects `auto`: a protected actual target supplies P itself, while an unprotected target can use the same project's captured protected default branch P for rules and eligible context/tool policy without gaining approval authority. Explicit `required` still rejects an unprotected target; explicit `unprotected` keeps the historical limited comment-only profile. The actual review remains B..H even when B differs from T. Detached MR source identity is required; synthetic merged-results and merge-train commits are not silently treated as H. The local entry point does not select GitLab policy or create a platform receipt. -Receipt v14 extends that exact tuple only for a proven partial repository -review containing safely separable changed gitlinks. A private immutable-tree +The partial gitlink receipt shares the B/H/T/P identity. It binds a separate +repository coverage claim for reviews containing safely separable gitlinks. A private immutable-tree plan and qualified OCR projection identify selected ordinary work, while the native manifest keeps its OCR coverage meaning. The public receipt carries only closed effective-coverage counts; no skipped pointer or submodule -contents gain finding or approval authority. Receipt v13 retains its ordinary -review meaning. A v6 pre-execution status records a no-model gitlink stop. +contents gain finding or approval authority. Historical receipt v13 retains its +frozen readback meaning but cannot satisfy current posting. A v6 pre-execution +status records a no-model gitlink stop. When a protected policy authority is available, the review acquires only the current MR's authorized forge context before OCR. An immutable `.opencodereview/review-context-policy.json` read only from captured P controls admission, retrieval, model egress, publication, and retention. Protected policy is separate from untrusted source/target code, MR prose, and target-context evidence. The provider authorizes the exact project and current MR, normalizes bounded fields through DLP, and commits admitted records to a run-local context store before opaque handles are minted. Handles bind run, source, projection and expiry without exposing upstream identifiers. diff --git a/docs/gitlab.md b/docs/gitlab.md index c46381e7..a4e34101 100644 --- a/docs/gitlab.md +++ b/docs/gitlab.md @@ -6,7 +6,11 @@ GitLab is the toolkit's first forge provider. The provider layer owns GitLab API Install `open-code-review-toolkit` from PyPI and install Open Code Review separately. Use the exact recommended OCR version and asset checksum from the [compatibility manifest](../compatibility/ocr-support.json); the toolkit package never downloads OCR. -Start with the [complete checksum-pinned pipeline](../examples/gitlab/ocr-review.gitlab-ci.yml), then choose one configuration from the [GitLab mode matrix](../examples/gitlab/README.md). The pipeline keeps the repository's lint/test stage ahead of AI review, verifies the release runtime lock and toolkit wheel, installs hash-locked binary dependencies followed by the wheel, checks dependency consistency, runs preflight and configuration, performs one production `ocr-ci review`, and makes `ocr-ci post` the sole GitLab write boundary. The rules pack adds Jinja, conventional Ansible-role templates, and Twig to the recommended OCR file selection; project exclusions still win. +Start with the [complete checksum-pinned pipeline](../examples/gitlab/ocr-review.gitlab-ci.yml), then choose a mode from the same toolkit release tag. The default identity-only mode requires no external registry. If you enable federation, use the registry format and mode file from the tag named by `OCR_TOOLKIT_VERSION` in the linked pipeline. To adopt the operator-authored v3 recipe, take both files from a release tag that ships it. See the [GitLab mode matrix](../examples/gitlab/README.md). The pipeline keeps the repository's lint/test stage ahead of AI review, verifies the release runtime lock and toolkit wheel, installs hash-locked binary dependencies followed by the wheel, checks dependency consistency, runs preflight and configuration, performs one production `ocr-ci review`, and makes `ocr-ci post` the sole GitLab write boundary. The rules pack adds Jinja, conventional Ansible-role templates, and Twig to the recommended OCR file selection; project exclusions still win. + +Use a `linux/amd64` runner with an executor that honors the GitLab `image:` setting, such as the Docker executor. The job starts the official Python +image at a pinned Docker Hub manifest digest and installs the Linux amd64 OCR +binary. ## Required configuration @@ -74,7 +78,7 @@ The collapsed technical details keep aggregate input/output/cache token usage se ## Choose one operating mode -`OCR_REVIEW_CONTEXT_MODE` selects `off`, `metadata`, or `enriched`; governed federation is configured independently through registry v2. +`OCR_REVIEW_CONTEXT_MODE` selects `off`, `metadata`, or `enriched`; governed federation is configured independently through registry. | Mode | Context admitted to OCR | Network/tool boundary | Approval posture | | --- | --- | --- | --- | @@ -83,16 +87,16 @@ The collapsed technical details keep aggregate input/output/cache token usage se | [Explicit limited unprotected target](../examples/gitlab/modes/unprotected-target.gitlab-ci.yml) | `off` or bounded `metadata`; exact-target Rules are untrusted guidance | Built-in immutable evidence only; no protected policy or federation | Structurally comment-only when the actual target is unprotected | | [Enriched discussions](../examples/gitlab/modes/enriched-discussions.gitlab-ci.yml) | Metadata plus protected-policy generic discussions and verified remediation threads | Stable double-read GitLab snapshot before OCR | Recipe is explicitly comment-only | | [Same-revision CI outcomes](../examples/gitlab/context/policy-ci-outcomes.json) | Protected-policy exact check names and path prefixes | Twice-read exact-head GitLab pipeline/job metadata; no logs or artifacts | Context only; never suppression or approval authority | -| [Governed MCP federation](../examples/gitlab/modes/direct-mcp.gitlab-ci.yml) | Metadata plus model-selected admitted tool results | Registry-v2 HTTPS upstream through the bounded gateway | Used advisory tools are comment-only; unused services and successful `review_read` use are not independent blockers | +| [Governed MCP federation](../examples/gitlab/modes/direct-mcp.gitlab-ci.yml) | Metadata plus model-selected admitted tool results | Registry-v3 HTTPS upstream through the bounded gateway | Used advisory tools are comment-only; unused services and successful `review_read` use are not independent blockers | Approval in this table is available only when the actual target is protected; an unprotected target remains comment-only under either selector profile. The [bounded-context recipes](../examples/gitlab/context/) implement the [protected policy v4](review-context.md#protected-policy-v4) contract for -discussions, remediation history, and exact same-revision CI outcomes. Copy one template to `.opencodereview/review-context-policy.json` and merge it into the selected protected policy branch before selecting `enriched`: the target when protected, or the default branch in `auto` for an unprotected target. A source-branch copy cannot expand authority. Missing or invalid policy stops before OCR. Legacy v1-v3 policies remain parse-only: safe selectors continue, optional references are skipped, and required references make the run comment-only. Configure external tools separately with registry v2. DLP rejection and required-source degradation block approval; every admitted remediation thread does too. +discussions, remediation history, and exact same-revision CI outcomes. Copy one template to `.opencodereview/review-context-policy.json` and merge it into the selected protected policy branch before selecting `enriched`: the target when protected, or the default branch in `auto` for an unprotected target. A source-branch copy cannot expand authority. Missing or invalid policy stops before OCR. Legacy v1-v3 policies remain parse-only: safe selectors continue, optional references are skipped, and required references make the run comment-only. Configure external tools separately with registry. DLP rejection and required-source degradation block approval; every admitted remediation thread does too. -Governed federation is operator-owned and GitLab accepts only registry-v2 HTTPS upstreams. The gateway freezes the allowlist, validates schemas, arguments, origins, DLP and bounds, and reconciles content-free outcomes. Use dedicated least-privilege credentials and service-side tenant/object/field/operation authorization; gateway controls do not make an overprivileged service identity safe. +Governed federation is operator-owned and GitLab accepts only allowlisted HTTPS upstreams. The gateway freezes the allowlist, exports operator-owned interfaces, validates arguments, origins, DLP and bounds, and reconciles content-free outcomes. Use dedicated least-privilege credentials and service-side tenant/object/field/operation authorization; gateway controls do not make an overprivileged service identity safe. For an unprotected target under default `auto`, the protected default commit P supplies repository-relative Rules, context policy, accepted decisions, and eligible guidance. The current MR diff base B, actual target head T, and source head H remain separate: OCR reviews `B..H`, including when `B != T`. Code evidence retains its actual revision and is never relabelled as policy evidence; this single-MR review does not review a parent MR. `off`, `metadata`, `enriched`, and configured governed federation retain their established acquisition, DLP, object/tenant authorization, and budget gates. No repository policy field or new CI variable is needed. An omitted `--rule` or an external absolute Rules file cannot claim P provenance and is rejected on this path. Failed target or policy reads never cause a guessed fallback. @@ -104,7 +108,7 @@ and possible omission stay explicit; it supplies code context only and cannot make a parent or future integration review claim. [Repository evidence](configuration.md#repository-evidence) owns the exact admission bounds. -The explicit `unprotected` recipe retains the earlier limited profile: only `off` or bounded `metadata`, no enriched context or federation, required repository Rules read from T as untrusted guidance, and no structured guidance or accepted decisions. It also stays comment-only. A valid v13 `auto` summary identifies the captured protected policy anchor by full P SHA and states that automatic approval was unavailable; explicit `unprotected` retains the *limited, comment-only mode* line. Neither status changes OCR completeness; old or contradictory receipts cannot assert the new authority. [Environment configuration](configuration.md#gitlab-target-protection-selector) owns the exact selector rules. +The explicit `unprotected` recipe retains the earlier limited profile: only `off` or bounded `metadata`, no enriched context or federation, required repository Rules read from T as untrusted guidance, and no structured guidance or accepted decisions. It also stays comment-only. A validated ordinary `auto` summary identifies the captured protected policy anchor by full P SHA and states that automatic approval was unavailable; explicit `unprotected` retains the *limited, comment-only mode* line. Neither status changes OCR completeness; old or contradictory receipts cannot assert the new authority. [Environment configuration](configuration.md#gitlab-target-protection-selector) owns the exact selector rules. ## First integration sequence @@ -115,7 +119,7 @@ Use two merge requests for the recommended setup: If review of the integration merge request itself is unnecessary, adding Rules and the CI job together can stop before OCR with a recognized setup-pending note when the configured repository Rules are absent from the selected protected policy commit and the bounded source candidate is safe. Retrying that same merge request cannot make source-branch Rules authoritative; subsequent merge requests work after the setup change merges. Explicit `unprotected` with missing target Rules still fails closed. A missing, malformed, stale, or mismatched private status stops posting without a merge-request note and leaves the earlier review intact; the error remains in the job. -An exact merge-request lifecycle read also precedes evidence collection. If the identity-bound MR is already `merged` or `closed`, no OCR/model work starts and one toolkit-owned plain status note is created or updated without replacing findings, summaries, suppression, discussions, or approval state. Every path that could otherwise return advisory success confirms the exact MR is still terminal; close/reopen timing therefore fails and requires a new review even after a note-side error. Its marker is recognized only in a reserved control preamble, never from finding text. `merged` is irreversible and may finish successfully; `closed` stays advisory-only, while `OCR_STRICT_POSTING=true` remains nonzero so a required gate cannot be reused after reopening. If the MR becomes terminal after v13 review, posting reports stale state before a normal publication write, preserves the prior review, and adds no approval. Unknown states, provider failures, and identity mismatches likewise fail closed before publication. +An exact merge-request lifecycle read also precedes evidence collection. If the identity-bound MR is already `merged` or `closed`, no OCR/model work starts and one toolkit-owned plain status note is created or updated without replacing findings, summaries, suppression, discussions, or approval state. Every path that could otherwise return advisory success confirms the exact MR is still terminal; close/reopen timing therefore fails and requires a new review even after a note-side error. Its marker is recognized only in a reserved control preamble, never from finding text. `merged` is irreversible and may finish successfully; `closed` stays advisory-only, while `OCR_STRICT_POSTING=true` remains nonzero so a required gate cannot be reused after reopening. If the MR becomes terminal after the review, posting reports stale state before a normal publication write, preserves the prior review, and adds no approval. Unknown states, provider failures, and identity mismatches likewise fail closed before publication. GitLab Code Owners and code-owner approval rules are separate project merge policy. They are not prerequisites for OCR execution and cannot give unprotected repository content policy authority. Likewise, a green advisory pipeline or allowed-to-fail OCR job proves neither that `ocr-ci review` completed nor that OCR or its model executed. Inspect the review result, manifest coverage, receipt, and published status. @@ -160,13 +164,19 @@ merge-train, missing or contradictory event/commit identities stop before model execution; no project variable or merge-strategy change is required. An intentionally absent toolkit receipt retains a compatible standalone -direct-posting path outside GitLab CI, without automatic approval or a v13 -freshness claim. A detached GitLab MR job requires v13/v14 for normal result +direct-posting path outside GitLab CI, without automatic approval or a current ordinary receipt +freshness claim. A detached GitLab MR job requires the applicable receipt for normal result publication: a missing receipt stays in the job and cannot publish findings or -replace the previous review. A present v9-v12 receipt remains readable for +replace the previous review. A present v9-v13 receipt remains readable for historical diagnostics but blocks a new current MR publication. -The provider validates same-project ownership, the current MR diff base/start/head/version, source H, actual target branch/T/protection, and selected policy branch/P/protection before OCR. Missing, pending, malformed, or contradictory diff data is unavailable or stale, not an empty review; a valid empty delta is a normal no-change case. `ocr-ci review` collects immutable evidence from actual code revisions, admits context under the selected policy capability, applies DLP and budgets, runs OCR once, reconciles federation, validates the result, cleans private state, and attaches receipt v13. `ocr-ci post` hostile-reads that receipt rather than reconstructing authority from a later environment and rejects another `CI_JOB_ID` in a current-review result or preview/setup status when present. A successful result covers this MR only: no parent-MR lookup, chain review, integration claim, extra pipeline trigger, or merge is performed. Arbitrary valid branch names and a target with no parent MR are supported. +The GitLab checkout must contain a direct `.git` directory so the toolkit can +bind the selection rules used by preview and production. A linked worktree or +an external Git configuration include stops the review before OCR runs. The +ordinary projection accepts regular files. Changed symlink entries and +unsupported Git file-type transitions also stop before OCR. + +The provider validates same-project ownership, the current MR diff base/start/head/version, source H, actual target branch/T/protection, and selected policy branch/P/protection before OCR. Missing, pending, malformed, or contradictory diff data is unavailable or stale, not an empty review; a valid empty delta is a normal no-change case. `ocr-ci review` collects immutable evidence from actual code revisions, admits context under the selected policy capability, applies DLP and budgets, binds every immutable changed path to OCR's selected/excluded partition, runs OCR once, reconciles federation, validates the result, cleans private state, and attaches the ordinary receipt. `ocr-ci post` hostile-reads that receipt and independently checks the supplied selection against the Git diff; it rejects another `CI_JOB_ID` in a current-review result or preview/setup status when present. A successful result covers this MR only: no parent-MR lookup, chain review, integration claim, extra pipeline trigger, or merge is performed. Arbitrary valid branch names and a target with no parent MR are supported. `off` still validates the source/diff, actual target and selected policy authority, merge-request author, and live bot identity while withholding mutable MR text. `metadata` admits only bounded DLP-checked title, description, labels, and optional source branch. Treat those fields as claims to compare with the diff, never as instructions, policy, or proof. A comment claiming “approved” or asking to skip security checks cannot authorize a tool, waive a gate, or grant consent, regardless of who authored it. @@ -178,7 +188,7 @@ Remediation text is untrusted review history. It may locate a claim that OCR mus A protected CI pass is narrower than a general green-pipeline claim: it applies only to its exact reviewed head, exact protected job name, and declared path prefixes. It may challenge an unconditional claim about code that the job actually exercised, but it cannot suppress a finding, prove unrelated absence, change severity/lifecycle, or authorize approval. Stale, advisory, skipped, canceled, failed, unknown, incomplete, mutated, or ambiguous data cannot be treated as a required pass. The toolkit does not fetch job logs, artifacts, URLs, users, runners, variables, or raw IDs. -Provider configuration is forge-neutral. Configure and preflight share one normalized absolute HTTPS API root, explicit protocol, headers, request-body controls, and optional models URL. A protocol-mismatched terminal endpoint, embedded credential, or fragment fails before OCR. A classified provider failure stays in the job because no completed v13 review identity can authorize an MR note; raw provider/model fields, response bodies, request IDs, paths, warnings, and stderr remain private. The review log may contain one toolkit-authored line of closed HTTP detail and non-zero aggregate retry counts from a fully validated retry report. `rate-or-spending-limit` job guidance suggests lowering native concurrency (`ocr-ci review ... -- --concurrency N`) and/or `OCR_LLM_MAX_COMPLETION_TOKENS`, starting a new merge request pipeline, and then checking provider request/account limits without claiming either setting caused the failure. The previous successful review remains visible, no failed-result findings are posted, and approval is not attempted. +Provider configuration is forge-neutral. Configure and preflight share one normalized absolute HTTPS API root, explicit protocol, headers, request-body controls, and optional models URL. A protocol-mismatched terminal endpoint, embedded credential, or fragment fails before OCR. A classified provider failure stays in the job because no completed review identity can authorize an MR note; raw provider/model fields, response bodies, request IDs, paths, warnings, and stderr remain private. The review log may contain one toolkit-authored line of closed HTTP detail and non-zero aggregate retry counts from a fully validated retry report. `rate-or-spending-limit` job guidance suggests lowering native concurrency (`ocr-ci review ... -- --concurrency N`) and/or `OCR_LLM_MAX_COMPLETION_TOKENS`, starting a new merge request pipeline, and then checking provider request/account limits without claiming either setting caused the failure. The previous successful review remains visible, no failed-result findings are posted, and approval is not attempted. When a merge request introduces a repository-owned OCR rules path absent from both selected protected policy baselines, `review` stops before OCR and `post` may publish only the static setup-pending message after hostile identity validation. The source file never becomes policy evidence for its own merge request. Under explicit `unprotected` with an actually unprotected target, target Rules are still mandatory but remain untrusted guidance; a missing target blob fails before OCR without promoting the source copy. diff --git a/docs/local.md b/docs/local.md index 6405d7aa..ea6ffefb 100644 --- a/docs/local.md +++ b/docs/local.md @@ -157,7 +157,7 @@ ocr-ci review --local --incremental --analysis \ --stderr "$review_dir/first.stderr" -- --from "$base" --to HEAD ``` -Open `first.md` for the findings and the status of Behavior/Impact Analysis. This first command reviews the full selected range. After the report is written, look for `OCR incremental baseline saved` in the terminal. The message gives the number of files whose dependencies could be verified. Zero means the next run must review every file again. The impact assessment describes this commit. +Open `first.md` for the findings and the status of Behavior/Impact Analysis. This first command reviews the full selected range. After the report is written, look for `OCR incremental baseline saved` in the terminal. The terminal and report show how many groups qualified and count the reasons each unqualified group needs fresh review. One group can count toward several reasons. Zero qualified groups means the next run must review every file again. The impact assessment describes this commit. After committing your fix, run the second command in the same shell: @@ -173,7 +173,33 @@ If the toolkit cannot revalidate a carried finding, the result is incomplete. The report names the groups that require fresh review and the command exits with status 1 after writing the available findings. -The second run can review the whole range. Reuse currently covers identifiable independent edits inside Python functions. Changes to the selected files, shared context, rules or model can require fresh work. If the model searched across the repository, the toolkit may need to review that group again. A direct source read can qualify when the toolkit can verify the exact file it supplied and establish that the input is unchanged. The report explains why a full review was selected. You can also request fresh Analysis on the second run by adding `--analysis`; the toolkit will review the full range again. If you enabled Analysis via `OCR_ANALYSIS`, unset it for a file-only follow-up. +Groups can qualify for file-level reuse across the file types OCR selects, +including Markdown and JSON. Every file in a reused group must have the same +blob and mode. The toolkit follows file references across formats and +resolves supported local Markdown links and reference definitions. It +checks Python dependencies around edited function bodies and can narrow a +review after independent Markdown edits or JSON value edits that preserve +the data shape. JSON edits also recheck selected executable consumers and +files that refer to affected keys. An unresolved or out-of-selection link in unchanged Markdown requires fresh +review for connected groups. When edited Markdown contains such a link in +either revision, the toolkit selects a full review. Unsupported +source semantics or changes to shared selection, context, rules or model +can require a full review. + +A direct source read can qualify when the toolkit verifies its result against +an immutable file and the file remains unchanged. This includes a verified +request for a line range beyond the end of the file. The toolkit can repeat +bounded literal `code_search`, `file_find`, `file_read_diff` and built-in +evidence queries over the new inputs. The group qualifies when every replay +produces the same complete result. Changed results, incomplete evidence +pages and ambiguous or unsupported tool requests require fresh review for +that group. Groups newly reviewed in a narrowed run need fresh review again +because OCR gave them a shorter comparison inventory. +Dependency verification uses locally available Git objects before OCR runs. +The report's native tool counters describe calls made by the fresh OCR +execution. The report explains why a full review was selected. Request fresh Analysis +with `--analysis` to review the full range again. If you enabled Analysis via +`OCR_ANALYSIS`, unset it for a file-only follow-up. The terminal prints the private baseline path after each successful save. Each physical worktree uses one owner-only slot under @@ -181,6 +207,9 @@ physical worktree uses one owner-only slot under branch, or to the detached state when HEAD is detached. A full review on a different branch replaces the slot after successful delivery. Switching back then starts with a full review. A separate linked worktree has its own slot. +The slot retains the reason counts, the tool arguments that passed disclosure +checks and digests of the verified responses. Diagnostic summaries contain +reason names and counts. The reviewed revision must be the checkout's current HEAD. Copy the printed path if you want to delete that exact slot later, including after removing its worktree. Use `rm -i -- "$baseline_path"` with the exact path you copied and @@ -194,8 +223,12 @@ for that invocation. With `--incremental`, the full run can save its primary file-review baseline even when it also runs Analysis. A later file-only review can reuse groups when the file-review instructions, evidence and dependencies match. The group responsible for the full-change diagram requires fresh review. -External MCP tools prevent reuse and baseline creation. An ordinary full review -without `--incremental` does not save an incremental baseline. +With a governed external MCP registry, `--incremental` runs the full review with +the configured tools and skips reuse and baseline creation. The reason appears +in the terminal, the Markdown report, and `toolkit_incremental.full_reason` in +the JSON when it fits the result size limit. The federation line in Markdown +reports OCR attempts and gateway outcomes from that run. An ordinary full +review without `--incremental` does not save an incremental baseline. For pre-push acceptance, run a full local review with the intended diagram and Analysis. Incremental reports are for local use. When the result-size limit @@ -320,7 +353,7 @@ leave the review and findings usable. The mandatory repository-evidence MCP remains enabled. Registry validation and the toolkit's self-query do not substitute for the review's completed evidence summary call: the result's claimed usage must reconcile with the real action -record. Operator-configured registry-v2 upstreams remain optional and cannot +record. Operator-configured registered upstreams remain optional and cannot replace mandatory evidence. Local permits reviewed HTTPS and explicit stdio transports; their trust boundaries are described in [governed MCP federation](configuration.md#governed-mcp-federation-and-trust-boundary). @@ -348,7 +381,7 @@ Standard output contains shared review health, coverage, warnings, tool/token an verified MCP facts, DLP admission status, and every admitted finding. It has no posting caps, remote badges, HTML disclosures or platform publication claims. Admitted finding prose uses the shared safe Markdown presentation; source code -stays in literal fences. Raw or DLP-disabled reports also fence finding text. +stays in literal fences. This presentation also applies with semantic DLP disabled. Unprepared finding text uses a literal fence. Diagnostics use standard error; JSON stays in the private `--result` artifact. The same complete Markdown is published to `--report PATH`, defaulting to the @@ -398,11 +431,13 @@ host, keep it out of commits and shared artifacts, and remove it after diagnosis `OCR_DLP_ENABLED=false` is a strict per-run escape hatch. It disables context/federation and publication DLP, emits a prominent Markdown and console -warning, and makes the result approval-ineligible. Local Markdown may then +warning, and makes the result approval-ineligible. Bounded inert-Markdown +projection, destination validation, and unsafe-presentation rejection remain +mandatory. Local Markdown may then contain sensitive repository, service, model, or credential-adjacent data. The same setting in GitLab can publish such data, and re-enabling DLP cannot retract anything already sent or written. Invalid non-boolean values fail before OCR; -non-DLP schema, size, origin, evidence, cleanup and output-safety gates remain. +schema, size, origin, cross-server result provenance, evidence, cleanup and output-safety gates remain active. ## Private debug bundle @@ -515,7 +550,7 @@ environment. Keep the example's stable toolkit pin unchanged until release. raw/safe separation, truncation and cleanup. Never publish raw private files. - Progress: compare enabled/disabled outcomes and artifact contents. Only bounded toolkit phases and heartbeats should be added to stderr. -- Federation: qualify each registry-v2 upstream through the toolkit gateway. +- Federation: qualify each registered upstream through the toolkit gateway. Local may use explicit HTTPS or stdio; GitLab uses HTTPS only. Verify SDK v1/v2 peers and negotiated wire revisions independently, bounded cleanup, and content-free receipt accounting. The mandatory internal evidence MCP remains diff --git a/docs/operations.md b/docs/operations.md index 190781be..01471d4b 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -98,11 +98,11 @@ This aggregate budget is separate from both OCR's prompt/context `max_tokens` ce The outcome wording distinguishes skipped, complete, complete-with-warnings, incomplete, token-budget, and failed reviews while preserving the finding state in that same line. A complete clean review is visibly positive; a complete review with findings or only reviewer-suppressed findings is neutral; warning, partial, budget, and failed states never look clean. Findings withheld by the posting limit remain counted even when the limit allows no individual finding note. Recommended focus areas ranks only its copy of already-published findings by the closed severity, category, safe repository location, and stable-identity order before its existing display cap; inline and fallback discussion order, suppression, counts, security focus, and approval policy remain unchanged. OCR manifest failures provide the canonical failed-file receipt; legacy warnings are a bounded fallback, and `summary.files_reviewed` is never treated as proof of successful coverage. Technical details label the aggregate as all OCR tool calls and retain the existing inline format while listing every admitted non-zero count for the closed native/context/evidence review set. An empty admitted list produces no tool-call line. The counts describe review activity, not per-tool token consumption: one read or search can return a different amount of context from another. Dynamic external tool names remain private; reconciled MCP-server attempt totals stay in their separate aggregate, and completed built-in evidence `summary`/`list`/`get` plus dedicated `search`/`coverage` counts appear only after action-receipt v3 accounts for every MCP-received or OCR-preparse attempted call. Failed and malformed attempts remain private, cannot appear as completed evidence, and cannot satisfy the mandatory summary. Zero completed action counters, unattributed attempts, queries, scopes, IDs, token counters, and configured-but-unused MCP servers are omitted. A present but incomplete or invalid receipt is rejected before prior comments are inspected or normal findings are published; an absent receipt selects the compatible direct-posting path only outside GitLab CI. Token usage renders only validated input/output/cached/reasoning/total/derived-other buckets; malformed or contradictory counters are unavailable and unknown provider keys are not published. Status and aggregate semantic-category emoji are enabled by default and can be disabled together with `OCR_POST_EMOJI=false`; finding labels remain text unless their separate badge mode is enabled. -When a fully validated receipt v13 records an actually unprotected target, the summary identifies its selected profile after the primary status line. `auto` says the target was unprotected, shows the captured protected policy anchor's full P SHA, and states that automatic approval was unavailable (comment-only); explicit `unprotected` retains *The target branch was not protected in GitLab. This review ran in limited, comment-only mode.* It appears without replacing or reclassifying clean, findings, warnings, partial, budget-stopped, failed-result, or publication-filtered outcomes. The limitation is a trust and approval boundary, not a coverage result. A protected target has no unprotected-target line; old, malformed, or contradictory receipts cannot assert the new protected authority. +When a fully validated current receipt records an actually unprotected target, the summary identifies its selected profile after the primary status line. `auto` says the target was unprotected, shows the captured protected policy anchor's full P SHA, and states that automatic approval was unavailable (comment-only); explicit `unprotected` retains *The target branch was not protected in GitLab. This review ran in limited, comment-only mode.* It appears without replacing or reclassifying clean, findings, warnings, partial, budget-stopped, failed-result, or publication-filtered outcomes. The limitation is a trust and approval boundary, not a coverage result. A protected target has no unprotected-target line; old, malformed, or contradictory receipts cannot assert the new protected authority. ## Current MR freshness -The v13 receipt keeps source H, current MR diff base/start/head/version, actual +The ordinary receipt keeps source H, current MR diff base/start/head/version, actual target branch/T/protection, and selected policy project/branch/P/protection/mode separate. Posting checks the authenticated current tuple before each current result write, draft publication, old-note cleanup, and eligible approval. A @@ -132,7 +132,7 @@ reset policy remain authoritative. ## Automatic approval lifecycle `OCR_AUTO_APPROVE=true` is the default. Approval is a separate transaction only -after every current review note publishes. A review is eligible only with exact closed receipt v13 for a protected actual target, enabled DLP, a supported complete manifest, no warnings, failures, waivers, token-budget stop, or omitted findings, no used advisory federation tool or uncertain federation accounting, no degraded metadata, no DLP-rejected selected source, no required context degradation, no admitted remediation context, and at most three findings. Receipt v9-v12 remains readable under its frozen historical invariants, but cannot publish or approve a new current review; v1-v8 remains unsupported. Receipt v13 binds the current MR diff and source H, actual target T/protection, selected policy authority P/protection, merge-request author ID, context mode/state, DLP mode, per-source completeness/degradation, admitted-mutable state, fixed context-tool use, mandatory evidence state, content-free federation reconciliation, stage-aware publication DLP, and cleanup. An actually unprotected target is structurally ineligible: orchestration does not call the approval executor, regardless of `OCR_AUTO_APPROVE` or whether the policy authority is protected. Unused federation services and successful `review_read` use do not independently block approval for protected targets. `private-sanitized` remains eligible only when its canonical publication/approval projection is byte-equivalent; `publication-filtered` is partial and ineligible. Complete `metadata` context, complete non-remediation enrichment, and the built-in evidence/context MCP do not independently block approval on a protected target. Every finding must have +after every current review note publishes. A review is eligible only with a valid ordinary receipt for a protected actual target, enabled DLP, a supported complete manifest, no excluded immutable changed paths, reused work, warnings, failures, waivers, token-budget stop, or omitted findings, no used advisory federation tool or uncertain federation accounting, no degraded metadata, no DLP-rejected selected source, no required context degradation, no admitted remediation context, and at most three findings. Receipt v9-v13 remains readable under its frozen historical invariants, but cannot publish or approve a new current review; v1-v8 remains unsupported. The ordinary receipt binds the current MR diff and source H, the complete selected/excluded ordinary-diff partition, actual target T/protection, selected policy authority P/protection, merge-request author ID, context mode/state, DLP mode, per-source completeness/degradation, admitted-mutable state, fixed context-tool use, mandatory evidence state, content-free federation reconciliation, stage-aware publication DLP, and cleanup. An actually unprotected target is structurally ineligible: orchestration does not call the approval executor, regardless of `OCR_AUTO_APPROVE` or whether the policy authority is protected. Unused federation services and successful `review_read` use do not independently block approval for protected targets. `private-sanitized` remains eligible only when its canonical publication/approval projection is byte-equivalent; `publication-filtered` is partial and ineligible. Complete `metadata` context, complete non-remediation enrichment, and the built-in evidence/context MCP do not independently block approval on a protected target. Every finding must have severity exactly `low` and category exactly `style`, `documentation`, or `maintainability`. A complete zero-finding review is eligible. Four findings, malformed metadata, or any other severity/category are not eligible. @@ -241,9 +241,9 @@ preserve valid review signal; genuine DLP failures in public fields still filter those fields and leave a safe summary. Raw OCR stderr remains private. See the [diagnostic decision flow](review-decision-flow.md#additive-failed-tool-diagnostic-states). -Receipt v13 is emitted only for a validated GitLab merge-request profile with a real `protected|unprotected` target observation. An ordinary local review still receives the same result parsing, evidence/federation reconciliation, and publication DLP, but remains receipt-less because local Git state cannot establish GitLab protection. The compatible standalone receipt-less posting path outside GitLab CI remains approval-ineligible and cannot render receipt-derived federation or target-protection claims; a CI result without v13 and any present malformed or incomplete receipt fail closed before prior review state is read. +The ordinary receipt is emitted only for a validated GitLab merge-request profile with a real `protected|unprotected` target observation. Ordinary local review checks the native result, evidence, federation and publication DLP. The independent ordinary-diff partition check belongs to GitLab. Local Git cannot establish GitLab target protection. Standalone receipt-less posting outside GitLab CI remains approval-ineligible. To publish a normal result, a detached GitLab MR job requires a valid current ordinary or partial gitlink receipt. A pre-execution status has its own restricted advisory-note route. The partial gitlink route publishes comments and preserves prior finding threads. Missing or invalid receipts stop before prior state is read. -Run OCR through `ocr-ci review --result PATH --stderr PATH -- ...`. The wrapper owns preview, one OCR model loop, mandatory evidence, governed federation lifecycle, result validation, stage-aware DLP, cleanup and receipt v13. It does not post to GitLab. A recognized soft background diagnostic is attached after publication DLP and rendered only with an exact receipt; hard rejection stops before the model. Mandatory-artifact cleanup or federation-receipt uncertainty blocks normal publication. DLP-filtered findings and fields are omitted without relabelling original OCR coverage; previous comments remain and the `ocr.publication-dlp-signal/v4` marker reports only closed public omission, private sanitization and source-class counts. Posting never reconstructs or republishes rejected values. Historical v3 signals contain aggregate fields whose public/private split cannot be recovered. +Run OCR through `ocr-ci review --result PATH --stderr PATH -- ...`. The wrapper owns preview, immutable changed-path partitioning, one OCR model loop, mandatory evidence, governed federation lifecycle, result validation, stage-aware DLP, cleanup and ordinary receipt. It does not post to GitLab. A recognized soft background diagnostic is attached after publication DLP and rendered only with an exact receipt; hard rejection stops before the model. Mandatory-artifact cleanup or federation-receipt uncertainty blocks normal publication. DLP-filtered findings and fields are omitted without relabelling original OCR coverage; previous comments remain and the `ocr.publication-dlp-signal/v4` marker reports only closed public omission, private sanitization and source-class counts. Posting never reconstructs or republishes rejected values. Historical v3 signals contain aggregate fields whose public/private split cannot be recovered. HTML-like syntax in optional `existing_code` or `suggestion_code` is admitted only when the exact code is proved against the immutable reviewed head and @@ -255,7 +255,7 @@ become ordinary links. Original/hidden material is checked before projection and the prepared model is checked again. A rejected optional code field can be omitted while safe findings survive; harmless escaping is not a filtered review. -OCR may add group labels, file membership, grouping-task records, round diagnostics, readable reasoning, and provider-native replay payloads to private session data. They remain outside the canonical finding/posting projection, receipt v13, DLP counts, toolkit telemetry, tool/token summary, and approval inputs. If they appear inside receipt v13, validation fails closed. Caller `--output`/`-o` is rejected before preview because the wrapper owns the result descriptor and posting handoff. +OCR may add group labels, file membership, grouping-task records, round diagnostics, readable reasoning, and provider-native replay payloads to private session data. They remain outside the canonical finding/posting projection, ordinary receipt, DLP counts, toolkit telemetry, tool/token summary, and approval inputs. If they appear inside ordinary receipt, validation fails closed. Caller `--output`/`-o` is rejected before preview because the wrapper owns the result descriptor and posting handoff. When OCR exits nonzero with a valid bounded `ocr.llm-retry-report/v1`, the toolkit reads only its closed error class, failure phase, terminal outcome, HTTP status, bounded retry delay, and schema counters. It maps those facts to `authentication`, `authorization`, `rate-or-spending-limit`, `overloaded`, `timeout`, `network`, `endpoint-or-model-not-found`, `request-rejected`, `provider-unavailable`, `invalid-response`, `cancelled`, `mixed`, or `unknown`, then reports the classification in the job. Provider diagnostics alone keep the failure in the job. With exit code 1, the runner must verify the native manifest shows an operational partial before publication DLP. Posting requires a current toolkit receipt and live MR freshness checks. If DLP removes the manifest, posting also requires valid evidence of that verified operational partial in the filtered handoff before it can deliver admitted findings. The job still exits 1 and previous findings remain visible. A runtime `404` remains `endpoint-or-model-not-found` because safely distinguishing the endpoint from the model would require trusting the raw response body. @@ -267,7 +267,7 @@ The `rate-or-spending-limit` job guidance keeps that intentionally broad reason Raw provider/model identities, response bodies, error codes and messages, request IDs, paths, warnings, and stderr remain in owner-only private artifacts for a classified provider failure. Normal findings from the failed result are ignored, the previous successful review is preserved, and automatic approval is not attempted. Missing, oversized, malformed, or internally contradictory retry reports keep the generic job-local failure path instead of guessing a classification. -For a local diagnosis, use `ocr-ci review --local --debug-dir PATH`, placing toolkit options before the `--` separator. The command captures bounded owner-only diagnostics; ordinary local review remains receipt-less. Inspect it locally before considering `OCR_DLP_ENABLED=false`, keep it out of commits and shared artifacts, and remove it afterward. The escape hatch can expose sensitive content through service/model egress, local Markdown or GitLab and cannot retract prior disclosure. +For a local diagnosis, use `ocr-ci review --local --debug-dir PATH`, placing toolkit options before the `--` separator. The command captures bounded owner-only diagnostics; ordinary local review remains receipt-less. Inspect it locally before considering `OCR_DLP_ENABLED=false`, keep it out of commits and shared artifacts, and remove it afterward. The escape hatch can expose sensitive content through service/model egress, local Markdown or GitLab and cannot retract prior disclosure. It leaves bounded inert-Markdown projection and unsafe-destination rejection active for every publication sink. The next admitted review in a checkout clears an earlier private status before runtime configuration validation, so an early failure cannot hand the previous @@ -276,7 +276,7 @@ in one checkout from sharing or deleting each other's fixed artifacts. If a review cannot claim that lock or safely clear prior status, it returns code `75`. The paired `post` step then stops before reading private state or GitLab configuration, preserving any status owned by the concurrent or earlier run. -Receipt v13 and note-capable status also carry GitLab's `CI_JOB_ID` when supplied; +The ordinary receipt and note-capable status also carry GitLab's `CI_JOB_ID` when supplied; `post` rejects another job's result or status even if B/H/T/P are unchanged. The public GitLab example uses job-specific result and stderr paths. Run one review/post pair per CI job; separate checkout and output paths are required for @@ -302,7 +302,7 @@ this allowed diagnostic. v5/v6 readback remains unchanged. Pre-execution outcomes have narrower static reporting. When the merge request introduces the configured repository-owned OCR rules path and that exact path is absent from both immutable policy-side baselines, `review` verifies only that the source object is a bounded regular blob, writes a closed private status, and stops before OCR. When installed OCR rejects the generated background during preview, the status instead carries the closed character/file-size reason plus actual, limit, and unit. When the exact identity-bound GitLab merge request is already `merged` or `closed`, the toolkit stops before evidence collection and OCR, then upserts one toolkit-owned plain status note. `post` hostile-validates the v5 status against the current source and diff-base identities; note-capable statuses also carry the full authenticated MR review tuple for live B/H/T/P revalidation, while the terminal variant checks the exact provider/project/MR target. Every non-strict success path re-reads that exact lifecycle before returning; a reopened, unavailable, unknown, or mismatched MR fails and requires a new review even when note collection or verification also failed. A `merged` MR is irreversible and may return success after exact note readback. A `closed` MR remains reopenable: advisory mode may report the expected skip successfully, but `OCR_STRICT_POSTING=true` keeps the required gate nonzero so reopening cannot reuse a green no-review result. The terminal note states that no model ran, no findings were produced, approval was not attempted, and prior review/reviewer state remains intact. Duplicate jobs update the same note; an ambiguous or multiply matched note fails closed. The terminal marker is control metadata only in its reserved preamble line, so marker-like finding text cannot select, overwrite, or delete a review note. A successful ordinary result removes a stale terminal note only after publication succeeds, including safe partial publication. -For an admitted receipt-v13 result, `post` re-reads the exact current MR identity and lifecycle before each current-result write and cleanup step. `opened` keeps ordinary behavior. If that MR became `merged` or `closed` after review, v13 posting stops further normal publication and approval while preserving the previous valid review. The separate pre-execution terminal-status path can still emit its own static note when review began on a terminal MR. Malformed, unknown, unavailable, or identity-mismatched lifecycle data stops publication. Already visible notes from an interrupted transaction may require operator cleanup because GitLab does not offer an atomic multi-note commit or a draft-ID-to-visible-note rollback guarantee. +For an admitted ordinary review result with a validated receipt, `post` re-reads the exact current MR identity and lifecycle before each current-result write and cleanup step. `opened` keeps ordinary behavior. If that MR became `merged` or `closed` after review, receipt-bound posting stops further normal publication and approval while preserving the previous valid review. The separate pre-execution terminal-status path can still emit its own static note when review began on a terminal MR. Malformed, unknown, unavailable, or identity-mismatched lifecycle data stops publication. Already visible notes from an interrupted transaction may require operator cleanup because GitLab does not offer an atomic multi-note commit or a draft-ID-to-visible-note rollback guarantee. A successful retry replaces only an earlier toolkit-owned setup-pending note; background rejection and job-local generic failures never replace previous review findings or summaries. Static outcomes include no rules/background path or raw stderr and trust no repository/provider display text. A present malformed, stale, unsafe, unknown, or identity-mismatched private status stops posting without a new note. `OCR_POST_EMOJI=false` removes the heading emoji. diff --git a/docs/release.md b/docs/release.md index 7d12ae97..a24d4ce7 100644 --- a/docs/release.md +++ b/docs/release.md @@ -64,6 +64,21 @@ Development builds never create tags or GitHub Releases and never publish to pro Prepare `release/vX.Y.Z` locally from synchronized `main`. Update `.release-version`, `.release-source-date-epoch`, package metadata, documentation, checksum-pinned examples and their `docs/configuration.md` default table, and the Towncrier changelog. Run `tests/test_environment_contract.py` with the focused release/documentation contracts before the release PR so the published example and documented pin agree. Reconcile the active plan and release history as described below. The pull request title must be exactly `Release vX.Y.Z`. Required CI, security, CodeQL, Dependency Review, and build checks must pass before squash merge. Because TestPyPI is public disclosure, the protected feature/release review includes the privacy and license gate before either publication path. +For external changes, record release credit after accepting the contribution +into the release tree. Use the conditional Towncrier `Contributors` category +and the public PR number. Verify the generated section occurs once in the +changelog and once in the extracted GitHub Release body, before the final +comparison link. + +After marking the pull request ready, verify the full ready-check jobs for its +current head and current `main` base. Before squash merge, verify the live +PR's source repository and release branch, title, target and reviewed revisions. +Follow the [protected review and merge procedure](contributor-intake.md#review-and-merge-a-pr). +Draft, manual and scheduled jobs use different GitHub Actions check names. +The release authorizer requires each strict main ruleset check's successful +conclusion from its configured app at the reviewed head, then reconciles the +squash parent and tree against the reviewed pair. + The focused release set includes `tests/test_release_authorization.py`, `tests/test_release_receipt.py`, `tests/test_release_notes.py`, `tests/test_environment_contract.py` and `tests/test_operations_docs.py`. @@ -83,7 +98,9 @@ Squash-merging that exact repository-owned release PR is the only human publicat 7. creates an annotated `vX.Y.Z` tag and GitHub Release with wheel, sdist, `runtime-requirements.txt`, `SHA256SUMS`, `artifact-hashes.json`, `release-receipt.json`, and the matching `CHANGELOG.md` section; 8. reads back the complete asset set and immutable Release before closing the tracked issues. -After a successful Release run that published a GitHub Release, the separate `site-release-notify.yml` workflow can request a promotional-site refresh. It tolerates a short, bounded GitHub jobs-API consistency delay by retrying only the read-only publication-job lookup, then checks the latest stable immutable Release and its v2 receipt before one dispatch of the site workflow. Missing, malformed, unsuccessful, or persistently unfinished job evidence fails closed. Runs that did not publish a release do not dispatch. The site owns its own checks, current-main identity and publication path; a site notification failure does not change the toolkit's published artifacts or release receipts. A release notification alone does not authorize an initial site launch. +After a successful Release run, the separate `site-release-notify.yml` workflow can request a promotional-site refresh. Its read-only verification job checks the Release workflow identity and the exact run, attempt and source commit in the jobs API. It retries an unfinished publication job for a bounded interval. A successful publication job records the tag and SHA-256 of the immutable v2 receipt it verified. The notifier checks that evidence against the latest stable GitHub Release before one dispatch. A fresh receipt must identify the triggering run and attempt. Recovery binds a reused, unchanged receipt to the current publication job through the recorded digest and retains the receipt's original identity. Missing, malformed, unsuccessful or persistently unfinished evidence blocks dispatch. The site owns its own checks, current-main identity and publication path, including any initial launch authorization. + +The dispatch job uses the `site-release-notification` GitHub Actions environment. Restrict its deployment policy to the `main` branch, place `OCR_SITE_DISPATCH_TOKEN` in that environment, and remove the repository-level copy before opening `dev` intake. Give the credential only the access needed to dispatch the site workflow. The verification job uses the repository's read-only Actions token. A site notification failure leaves the toolkit's published artifacts and release receipts in place. The runtime lock is exported once from the reviewed `uv.lock` without default dependency groups. The same workflow artifact supplies it to registry verification before the GitHub Release exists. `artifact-hashes.json` remains the exact wheel/sdist map; receipt v2 records the lock separately under `auxiliary_assets`. `SHA256SUMS`, GitHub attestations, draft recovery and immutable asset readback include the lock. Recovery rejects a missing or conflicting auxiliary digest in the receipt, a changed or extra asset, and a missing asset in a published Release; an incomplete draft may receive its missing exact asset and does not accept a v1 receipt for a v2 release. Historical published v1 receipts remain immutable and are handled by their original release workflow revision. @@ -96,7 +113,7 @@ Registry reruns are fail-closed. An absent release may be published and an exact - TestPyPI development Trusted Publisher: workflow `testpypi.yml`, environment `testpypi-public-disclosure`. - TestPyPI stable Trusted Publisher: workflow `release.yml`, environment `testpypi-public-disclosure`. - PyPI Trusted Publisher: workflow `release.yml`, environment `pypi-production`. -- Both environments restrict deployment to protected `main` and do not add a second manual approval after the release PR merge. +- Both environments explicitly allow only the `main` branch and retain the release PR merge as the human publication approval. - The `main` ruleset requires pull requests, linear history, signed commits, resolved conversations, required merge checks, and blocks deletion and force pushes. - Public security features include secret scanning and push protection, private vulnerability reporting, Dependabot, CodeQL, Dependency Review, OpenSSF Scorecard, and immutable releases. @@ -112,9 +129,18 @@ In the release PR, use the installed `engineering-workflow` plan lifecycle to ar After publication, independently verify the immutable release, workflow, tag, receipt, issue, milestone, branch and synchronized-main state. Keep those exact external facts in the immutable receipt and Actions-owned issue comments; the archived plan truthfully retains the pre-publication handoff as historical context. Do not revise older release sections opportunistically, publish another stable version, or mutate an existing release object. Use stable tags rather than calendar years as lookup keys. Recovery dispatch is bound to the original release PR, version, merge commit, -reviewed head, and protected reviewed base. It executes the same trusted-base -authorizer, accepts only exact registry bytes and the existing immutable -receipt's closed release identity, and rejects unknown receipt fields. Draft +reviewed head, and protected reviewed base. Before loading the historical +authorizer, the workflow confirms that the squash merge is on the first-parent +history of the exact `main` commit that started the dispatch. Recovery +evaluates the current effective `main` rules against the original reviewed +head. Reconcile outstanding releases before adding new required check +contexts, since the original reviewed head must still satisfy those checks. + +Recovery accepts only exact registry bytes and the existing immutable receipt's +closed release identity, and rejects unknown receipt fields. When a prior +dispatch created the receipt, resume through a new recovery dispatch +from `main`. A PR-triggered rerun can resume a receipt created by its own +workflow run. Draft GitHub Releases are retained and addressed by their numeric release ID until publication because tag lookup does not expose private drafts reliably. Every numeric-ID read, asset upload, and publication step revalidates the expected diff --git a/docs/review-context.md b/docs/review-context.md index 6572615a..b390a9c8 100644 --- a/docs/review-context.md +++ b/docs/review-context.md @@ -105,7 +105,7 @@ itself. New policy documents use `ocr.review-context-policy/v4`. V4 retains the bounded aggregate budgets, `forge_discussions`, `remediation_threads`, and `ci_outcomes` selectors from the established contracts. It does not accept `references`: external acquisition is -now governed by operator registry v2 rather than policy-selected executable +now governed by operator registry rather than policy-selected executable adapters. Discussion selectors define account classes, resolved/outdated selection, age, @@ -144,7 +144,7 @@ for an accepted legacy policy. Legacy `references` are never executed. No command, endpoint, adapter protocol, credential, candidate identifier, or legacy result is passed to OCR or converted -implicitly into registry v2. +implicitly into registry. - Optional legacy references are marked unavailable and skipped. Other safe selectors can still produce a review, subject to their normal gates. @@ -155,7 +155,7 @@ implicitly into registry v2. the run. It never restores legacy execution. Migrate by moving reviewed external services into the operator-owned -`OCR_MCP_SERVERS_JSON` registry v2 and then removing `references` while advancing +`OCR_MCP_SERVERS_JSON` [registry](configuration.md#governed-mcp-federation-and-trust-boundary) and then removing `references` while advancing the protected policy to v4. Registry tools are model-directed federation tools; they are not a field-for-field replacement for the old pre-OCR adapter records. Reassess schemas, origins, assurance and credentials rather than copying an old @@ -192,10 +192,16 @@ DLP. Private retention is checked separately. Publication filtering does not rewrite OCR coverage: a complete OCR manifest remains complete while omitted public fields and findings are reported as publication omissions. -Publication prepares admitted prose as bounded inert Markdown after checking -original, hidden and decoded material. The same prepared values reach local and -GitLab presentation; safe escaping alone is not an omission. Literal source and -typed diagram labels keep their separate sink contracts. The +Model-egress admission independently inspects bounded HTML-decoded, nested +decoded-markup, display/source, compatibility and reversible renderer views. +Those views are enforced during acquisition, hostile store readback and again +immediately before `context_get` returns the complete model projection; unlike +publication preparation, they do not rewrite harmless entity spelling. + +Publication always prepares prose as bounded inert Markdown. With semantic DLP +enabled, it first checks original, hidden and decoded material. The same prepared +values reach local and GitLab presentation; safe escaping alone is not an omission. +Literal source and typed diagram labels keep their separate sink contracts. The [security contract](security.md#dlp-and-publication) owns destination validation, representation bounds and hostile current-receipt readback. @@ -210,27 +216,29 @@ Previous review comments are preserved with the actual incomplete publication reason. Posting counters describe admitted findings only; DLP omissions are shown separately. Publication `ocr.publication/v2` separates public omitted fields and reasons from private-only sanitized fields and reasons. The -`ocr.publication-dlp-signal/v4` marker and receipt v13 carry only closed counts +`ocr.publication-dlp-signal/v4` marker and the receipt’s publication-accounting fields carry only closed counts and state, never protected content, paths, identifiers, URLs, or raw errors. Historical v3 aggregates do not establish this public/private split. `OCR_DLP_ENABLED=false` is a strict operator escape hatch. It disables context, federation and publication DLP for that run, adds a prominent local/GitLab warning, -and always blocks automatic approval. Sensitive data may leave through service -egress, local Markdown, or GitLab publication, and enabling DLP later cannot +and always blocks automatic approval. It does not disable bounded inert-Markdown +projection or destination validation; unsafe presentation fails result admission. +Sensitive data may leave through service egress, local Markdown, or GitLab +publication, and enabling DLP later cannot retract it. Use the complete [local debug invocation](local.md#private-debug-bundle) before considering this setting; non-DLP schema, size, origin, identity, cleanup, evidence and posting transaction gates remain enforced. ## Receipt and cleanup -Receipt v13 binds the current MR diff/version and source H, actual target +The ordinary receipt binds the current MR diff/version and source H, actual target branch/T/protection, selected policy project/branch/P/protection/mode, context mode and per-source state, legacy policy state, DLP mode, stage-aware publication accounting, mandatory evidence, governed federation reconciliation, and cleanup. Context/evidence/federation accounting remains content-free. The separately admitted optional typed diagram may carry bounded labels and source references; -see [diagram admission and delivery](diagrams.md). Exact v9-v12 receipts retain +see [diagram admission and delivery](diagrams.md). Exact v9-v13 receipts retain their frozen historical invariants but cannot publish a current result; v1-v8 remain unsupported. Ephemeral results have no migration path. diff --git a/docs/review-decision-flow.md b/docs/review-decision-flow.md index d14788f7..4fccf5a0 100644 --- a/docs/review-decision-flow.md +++ b/docs/review-decision-flow.md @@ -129,7 +129,7 @@ flowchart TD acquire --> evidence_budget{Complete mandatory evidence
fits hard resource bounds?} evidence_budget -- No --> evidence_budget_stop[Closed v7 evidence-budget status;
no model; fresh diagnostic only;
preserve previous review] evidence_budget -- Yes --> diagram_setup[Prepare optional run collector by mode
and qualified OCR capability;
closed feedback allows bounded corrections;
fault/conflict/budget omits only diagram] - diagram_setup --> registry[Parse registry v2; freeze schemas/tools;
start bounded federation gateway] + diagram_setup --> registry[Parse registry; freeze operator interfaces/tools;
start bounded federation gateway] registry --> acquire_ok{Mandatory evidence, context, and
federation readiness valid?} acquire_ok -- No --> preflight_error acquire_ok -- Yes --> gitlink_check{Changed gitlink?} @@ -137,8 +137,10 @@ flowchart TD gitlink_scope -- No --> gitlink[Closed v6 unqualified status;
model not started] gitlink_scope -- Yes --> gitlink_projection[Freeze original trees, ordinary diff,
Git inputs and child overrides] gitlink_projection --> preview[Run exact OCR preview with
toolkit-owned child environment] - gitlink_check -- No --> preview - preview --> preview_ok{Preview accepted?} + gitlink_check -- No, local --> preview + gitlink_check -- No, GitLab --> ordinary_projection[Freeze immutable ordinary diff
and Git selection inputs] + ordinary_projection --> preview + preview --> preview_ok{Preview accepted and applicable
Git partition verified?} preview_ok -- Unclassified diagnostics --> preview_unclassified[Closed stage/count status;
model not started] preview_ok -- Other failure --> preview_error[OCR not started; bounded failure path] preview_ok -- Yes --> selected{Qualified gitlink and
no ordinary file selected?} @@ -146,9 +148,14 @@ flowchart TD selected -- No --> continuation{Opted-in local continuation
with a matching checkpoint?} continuation -- Yes --> reconstruct[Reconstruct completed items in the disposable OCR home;
native OCR checks source and rule identity before dispatch] reconstruct -- Accepted --> review[Run OCR against exact from/to refs
with internal MCP plus fixed relay;
guide summary and direct MR intent read,
then relevant allowlisted tools when useful] - continuation -- No --> incremental{Opted-in local incremental review
with independently reusable files
and no full-range diagram or Analysis?} - incremental -- Yes --> incremental_preview[Qualify a second preview with exact exclusions;
use original selection if qualification fails] - incremental_preview --> review + continuation -- No --> federated_incremental{Opted-in local incremental review
with a governed external MCP registry?} + federated_incremental -- Yes --> incremental_federation_fallback[Use the full native review and real gateway;
record why incremental reuse is unavailable] + incremental_federation_fallback --> review + federated_incremental -- No --> incremental{Opted-in local incremental review
with independently reusable files
and no full-range diagram or Analysis?} + incremental -- Yes --> incremental_preview[Verify unchanged group files and replay dependencies;
qualify a second preview with exact exclusions] + incremental_preview -- Verified exclusions --> review + incremental_preview -- No eligible groups or preview mismatch --> incremental_federation_free[Keep full native selection] + incremental_federation_free --> review incremental -- No --> review review -. Opted-in full run with diagram or Analysis .-> baseline[Save eligible primary file groups for a later local review;
whole-range outputs are generated fresh] reconstruct -- Native input mismatch --> review @@ -166,22 +173,23 @@ flowchart TD successful_run -- Yes --> finalize[Enter result finalization] finalize --> analysis_admit{Native Analysis fields match request and main status?} analysis_admit -- No --> integrity_error - analysis_admit -- Yes --> core{Result, manifest exact B/H/range and reuse coverage,
mandatory cleanup, action and federation receipts valid?} + analysis_admit -- Yes --> core{Result, manifest exact B/H/range, full selection
and reuse coverage, mandatory cleanup,
action and federation receipts valid?} core -- No --> rejection_diag[Emit closed result shape and execution facts;
missing contract vs zero evidence;
independent summary counts when available] rejection_diag --> integrity_error core -- Yes --> diagram_admit[Admit optional typed candidate against native range,
bounded immutable text metadata and whole-unit DLP;
fault, conflict or budget omits whole diagram] diagram_admit --> diag[Classify additive failed-tool diagnostics;
validated diagram failures stay optional] diag --> dlp_mode{OCR_DLP_ENABLED?} - dlp_mode -- true --> dlp[Check original, hidden and decoded material;
prepare bounded inert prose and recheck it;
source roles refine keys, never confidentiality;
publication and private-field DLP] - dlp_mode -- false --> disabled[Keep prominent risk warning;
force comment-only] - disabled --> publishable + dlp_mode -- true --> dlp[Check original, hidden and decoded material;
prepare bounded inert prose and recheck it;
check registered external metadata, result keys and values;
source roles refine keys, never confidentiality;
publication and private-field DLP] + dlp_mode -- false --> disabled[Skip semantic material rejection;
prepare bounded inert prose;
reject unsafe presentation;
keep risk warning and force comment-only] + disabled -- Unsafe or over bounds --> integrity_error + disabled -- Safe --> publishable dlp --> dlp_state{DLP state} dlp_state -- passed --> publishable[Complete publishable projection] dlp_state -- private-sanitized --> publishable dlp_state -- publication-filtered --> partial[Safe partial output; analysis stays complete
only when native coverage proves it] publishable --> mode{Execution profile} partial --> mode - mode -- Local --> local_result[Validated receipt-less local result;
revalidate and label carried incremental findings] + mode -- Local --> local_result[Validated receipt-less local result;
revalidate carried findings before delivery;
record fallback for federated incremental requests] local_result --> local_output{Explicit local provider?} local_output -- Yes --> local_file[Shared summary and findings to private Markdown and console;
optional Analysis text in private Markdown] local_file --> local_delivery{Artifact and console delivery succeed?} @@ -192,7 +200,7 @@ flowchart TD integrity_error -- Explicit local --> local_failure local_output -- No --> local_handoff[Private JSON handoff only] mode -. Explicit post --include-analysis .-> analysis_summary[Receipt-bound Analysis in collapsed MR section] - mode -- GitLab MR --> receipt[Attach exact v13 ordinary or v14 partial receipt:
diff, target T, policy P and CI job] + mode -- GitLab MR --> receipt[Attach validated ordinary or partial receipt:
diff, full selection, target T, policy P and CI job] receipt --> post{Posting input valid at readback?} post -- No --> posting_error[Job-local publication-policy error;
findings transaction not started] post -- Yes --> diagram_post[Revalidate the same source bounds and DLP;
render flowchart with deterministic LR/TB or sequence;
fault omits diagram, findings continue] @@ -217,8 +225,8 @@ flowchart TD class local auxiliary; class preflight_error,terminal_strict_error,preview_error,gitlink,preview_unclassified,no_handoff,runtime_error,integrity_error,posting_error error; class no_work warning; - class start,api,native_auth,terminal_route,target_policy,unprotected_rules,separate_policy,acquire,diagram_setup,registry,gitlink_projection,preview,review,diagram_snapshot,finalize,diagram_admit,diag,dlp,disabled,publishable,partial,receipt,diagram_post,transaction auxiliary; - class auth,local_auth,input,profile,detached,initial_state,terminal_gate,current_diff,protected,selector,limited,default_policy,acquire_ok,gitlink_check,gitlink_scope,preview_ok,selected,exit,core,dlp_mode,dlp_state,mode,post,live_state,transaction_ok,published decision; + class start,api,native_auth,terminal_route,target_policy,unprotected_rules,separate_policy,acquire,diagram_setup,registry,gitlink_projection,ordinary_projection,preview,incremental_federation_fallback,review,diagram_snapshot,finalize,diagram_admit,diag,dlp,disabled,publishable,partial,receipt,diagram_post,transaction auxiliary; + class auth,local_auth,input,profile,detached,initial_state,terminal_gate,current_diff,protected,selector,limited,default_policy,acquire_ok,gitlink_check,gitlink_scope,preview_ok,selected,federated_incremental,exit,core,dlp_mode,dlp_state,mode,post,live_state,transaction_ok,published decision; ``` Recognized stops record an identity-bound `ocr.pre-execution-status/v5` or @@ -240,7 +248,7 @@ an advisory v6 status. Note-capable setup and preview statuses carry the complet B/H/T/P identity for live revalidation before each write; setup also requires the exact captured P. Unclassified preview diagnostics retain only a bounded count, never raw stderr. Generic OCR, parse, schema and provider failures -without a posting-eligible full identity remain in the job. A v13 result whose +without a posting-eligible full identity remain in the job. A current result whose MR becomes terminal before posting does not publish a new normal review; the pre-execution terminal-status note is a separate path. @@ -259,7 +267,7 @@ publication text and unproved code retain the ordinary HTML restriction; all code still crosses the remaining secret, PII, forbidden-value and control checks. Publication `ocr.publication/v2` separates public omitted fields and reasons from private-only sanitized fields and reasons. The v4 summary signal -and receipt v13 expose those closed counts without converting OCR coverage or +and ordinary receipt expose those closed counts without converting OCR coverage or provider posting counts. Finding source requests are planned together and coalesced by immutable Git @@ -278,8 +286,7 @@ filters the result, the producer first validates that native manifest and passes only a path-free selection proof; posting checks the proof, original coverage counts and remaining findings against Git. This route blocks automatic approval, old finding-thread deletion, and requested discussion -resolution even when the native manifest is complete. v13 retains its exact -ordinary-review meaning. +resolution even when the native manifest is complete. The core integrity boundary deliberately precedes additive diagnostics. A malformed result, contradictory manifest, stale identity, failed cleanup, or missing/mismatched toolkit action @@ -334,7 +341,7 @@ flowchart TD Valid detail records are bounded, credential-redacted, and control-safe before they reach the local stderr or CI job log. Dynamic detail text, paths, and per-tool failure maps never enter the finalized result, receipt, merge-request comments, publication-DLP telemetry, or later-action -inputs. Receipt v13 stores only `absent|verified|invalid|conflicting` and a bounded aggregate +inputs. The ordinary receipt stores only `absent|verified|invalid|conflicting` and a bounded aggregate `failed` integer for `verified`; the toolkit action receipt v3 remains authoritative for evidence attempts and completions. @@ -359,13 +366,15 @@ flowchart TD receipt -- No --> ci_context{GitLab CI MR context?} ci_context -- Yes --> schema_error ci_context -- No --> direct[Standalone compatible receipt-less posting path] - receipt -- Yes --> exact{Exact current v13 or v14 receipt valid?} + receipt -- Yes --> exact{Valid current ordinary or partial receipt?} exact -- No --> schema_error[Job-local publication-policy error] exact -- Yes --> partial_check{v14 partial gitlink receipt?} partial_check -- Yes --> source_proof{Original Git trees, counts and
native selected work match?} source_proof -- No --> schema_error source_proof -- Yes --> fresh{Current CI job, diff, target
and policy authority valid?} - partial_check -- No --> fresh + partial_check -- No --> ordinary_proof{Immutable Git diff matches native selection
or the validated private selection proof?} + ordinary_proof -- No --> schema_error + ordinary_proof -- Yes --> fresh fresh -- No --> stale_error[Stale or unavailable;
preserve prior review] fresh -- Yes --> projection{Publication projection} direct --> publish[Publish findings and summary] @@ -384,7 +393,7 @@ flowchart TD action_ok --> cleanup{Old-review cleanup
before each mutation} action_warn --> cleanup cleanup -- Before first mutation, stale --> action_stale - cleanup -- All confirmed --> complete[Replacement complete;
v14 preserves prior finding threads] + cleanup -- All confirmed --> complete[Replacement complete;
partial gitlink, excluded or reused work preserves prior finding threads] cleanup -- After cleanup starts, drift or unconfirmed write --> cleanup_partial[Stop nonzero; old cleanup partial;
retain current-run comments] classDef success fill:#d1fae5,stroke:#15803d,color:#14532d,stroke-width:2px; @@ -415,11 +424,11 @@ base, H its source head, and `B != T` is valid. The code tuple and authority are checked before each current-result write and again before an eligible approval. A policy-only fast-forward of the same still-protected default branch may finish against captured P when ancestry is proved; a changed default, lost protection, rewrite, -unverifiable ancestry, or moved code tuple stops. Exact v9-v12 receipts remain +unverifiable ancestry, or moved code tuple stops. Exact v9-v13 receipts remain historically readable under their frozen invariants but cannot authorize a new current publication. Pre-execution v5/v6 retain embedded v11/v12 review tuples; v7 retains the embedded v11 tuple for hard evidence-budget diagnostics. -All of those tuples still receive freshness checks. A detached GitLab CI job without v13/v14 cannot use the +All of those tuples still receive freshness checks. A detached GitLab CI job without the applicable receipt cannot use the standalone direct-posting path; local review stays receipt-less and does not post to GitLab. Pre-write checks leave a provider-side race; neither the diagram nor a comment-only outcome implies that an earlier bot approval was revoked. diff --git a/docs/security.md b/docs/security.md index e2f422ae..21fcf930 100644 --- a/docs/security.md +++ b/docs/security.md @@ -6,8 +6,7 @@ No input becomes safe merely because a trusted pipeline acquired it. One runner-owned immutable B/H range is proved before range-dependent evidence and independently matched to native requested/resolved/exact-range fields at -admission. Complete coverage does not prove range identity. Current result -receipts v13/v14 bind that claim; frozen v9-v12 remain historical readback and +admission. Complete coverage does not prove range identity. Current ordinary and partial result receipts bind that claim; frozen v9-v13 remain historical readback and pre-execution v5/v6 keep their unchanged embedded review tuples. The v7 hard-evidence budget status uses the existing v11 review tuple and carries only closed numeric resource facts, without a review result or approval authority. @@ -37,11 +36,12 @@ qualification issues and existing qualification evidence or changelog fragments. A contributor can control repository content, merge-request metadata and discussion text, including tool-like instructions and crafted references. Public issue authors can copy qualification markers; their text cannot authorize a -privileged workflow to edit or reopen their issue. An MCP -upstream controls its descriptions, schemas and responses. An operator controls -the reviewed registry, credentials and selected protected policy. A compromised -runner or same-user process remains a host-level threat outside the toolkit's -process-isolation guarantees. +privileged workflow to edit or reopen their issue. An MCP upstream controls its +live descriptions, schemas and responses, but its description and input schema +are not authority: the operator-owned registry supplies the model-facing interface. +An operator controls the reviewed registry, credentials and selected protected +policy. A compromised runner or same-user process remains a host-level threat +outside the toolkit's process-isolation guarantees. The main trust transitions are: @@ -51,7 +51,7 @@ The main trust transitions are: merge commit cannot stand in for either. 2. Optional metadata and protected-policy discussions/remediation/CI outcomes cross normalization, stage-specific DLP and owner-only storage. -3. Repository evidence enters the mandatory internal MCP. Operator registry v2 +3. Repository evidence enters the mandatory internal MCP. Operator registry cannot remove, replace, rename or shadow that server. 4. Optional external tools cross the toolkit-owned federation gateway. OCR sees only frozen `server__tool` aliases through a fixed private relay; upstream @@ -77,6 +77,30 @@ The main trust transitions are: authority. Generated promotion outputs reject conflicting existing content before any pin is changed; exclusive creation protects new destinations. +### Runtime trust boundaries + +The following checks also apply when changing a parser, transport, renderer or +approval adapter. Each row describes a property to preserve across upgrades. + +| Untrusted input or decision | Required protection | +| --- | --- | +| Git tree and diff size | Bound bytes and records while consuming the stream. Stop and reap the child on overflow or timeout. | +| Review selection and exclusions | Compare selected and excluded entries to the immutable diff. Excluded or unaccounted changes prevent automatic approval. Recheck the reviewed identity at posting. | +| MCP tool discovery | Bind the exposed description and argument contract to operator policy. Live server metadata cannot add a model-facing capability. | +| Results from multiple MCP servers | Track the origin of delivered material, including cached replies. Check arguments before dispatch to a different destination. | +| Structured results and tool metadata | Apply publication checks to external keys, values and exposed metadata, including material absent from the visible prose. | +| Destination hostnames | Use one unambiguous host identity for registry admission and transport authorization. Reject names whose interpretation can change between the two. | +| External context sent to the model | Check bounded decoded representations at acquisition, store readback and delivery. A harmless display transformation cannot confer disclosure authority. | +| Rendering with semantic DLP disabled | Keep destination validation, inert Markdown and presentation bounds active. Retain the disabled-mode warning and block automatic approval. | + +### External contributions and the software supply chain + +A fork author controls the proposed tests, build backend, workflow steps and scripts they invoke. Read-only token permissions limit GitHub API operations. The job can still read its checkout, accessible base caches and inherited data, write logs and artifacts, and contact the network. Keep base caches free of private packages and credentials. Review the exact revision before approving hosted fork CI. Privileged jobs build from reviewed source and bind downloads to their own authorized run. Release authorization, registry environments and the site dispatch credential have separate owners. + +Merging a contributor's change into a branch in the main repository changes its trust context. Before introducing a protected intake branch, restrict each publishing environment explicitly to `main` and isolate cross-repository dispatch credentials. A deployment rule permitting every protected branch would also permit a newly protected `dev`. Check the ruleset, required checks and actual token permissions on a fork PR and on promotion to `main`. + +The GitLab example pins the official Python image from Docker Hub by its multi-platform manifest digest. The runner starts that image before verifying the OCR binary or toolkit package, so protected job credentials still depend on the trusted image publisher and runner. The example uses an OCR binary for `linux/amd64` and requires a runner with that image platform. The maintainer checks the digest monthly and when a security fix is available, verifies the official `linux/amd64` manifest, and exercises the installed toolkit before changing the pin. The configured Dependabot ecosystems do not update this GitLab YAML pin. [Docker image pinning](https://docs.docker.com/build/building/best-practices/#pin-base-image-versions). + ### Local GitLab telemetry The operator chooses a trusted local `glab` installation, authenticated context and private state directory. A person who can write an MR, note, reaction or project setting can influence observations. Those inputs cannot grant collection access, publish a finding or approve an MR. @@ -161,6 +185,20 @@ requires fresh identity, contains no paths or source text, and preserves old findings without approval or thread cleanup. Corruption and unknown failures do not become budget diagnoses. +Ordinary GitLab review coverage is independently bound to the same immutable range. +The toolkit derives every changed path from Git, freezes repository selection +inputs, and requires native preview-selected and preview-excluded records to form +an exact disjoint partition with closed reasons. Native manifest identities and +reasons must reproduce that partition. If a qualified native version omits a +previewed gitignore exclusion, posting requires a separate selection proof and +counts the excluded path. The ordinary receipt carries only path-free counts, +reason totals, and a digest; posting rebuilds them before writing. Any exclusion, +including committed ignore rules, unsupported files, binaries, deletions, size +limits, secrets, provider directories, defaults, or user exclusions, blocks +automatic approval while preserving publication of the safely reviewed subset. +Any reused native work blocks a new automatic GitLab approval and preserves +prior finding threads. + Changed Git submodule pointers are a separate repository-coverage boundary. For an exact capability-qualified OCR version, the toolkit compares complete before/after Git trees, the explicit unfiltered diff, and the ordinary-file projection before @@ -188,8 +226,12 @@ If publication DLP removes a finding or warning, the filtered handoff omits the native manifest. Only after validating that manifest, the toolkit carries a path-free selection proof made of item digests and the source-artifact digest; `post` checks it against immutable Git changes and the original complete -coverage before publishing any retained finding. A missing or altered proof -stops publication. Git diff output is also bounded while the child runs, so +coverage before publishing any retained finding. A missing proof or a mismatch +with independently checked Git data stops publication. The producer owns the +claim about what OCR observed. The selection digest provides consistency within +the job’s private handoff; the digest cannot authenticate a replacement from a +compromised runner. Filtered results cannot grant approval or remove prior +finding threads. Git diff output is also bounded while the child runs, so an oversized patch cannot fill temporary storage before the limit is checked. The `auto` fallback is sensitive to wrong-project source substitution, @@ -197,7 +239,7 @@ retargeting, default-branch or protection changes, stale diff versions, cross-job handoff replacement, and policy object replacement. It requires authenticated same-project IDs and bounded provider/Git reads; a locally available SHA or CI declaration alone is -not authority. A forged persisted receipt cannot fill missing v13 authority +not authority. A forged persisted receipt cannot fill missing review authority fields from older versions. Configured federation still carries confused-deputy and object/tenant authorization risk: DLP and origin checks do not repair an overprivileged upstream service. These controls do not secure an @@ -237,22 +279,36 @@ comparisons remain diagnostic evidence rather than review receipts. ## Governed federation boundary -`OCR_MCP_SERVERS_JSON` accepts only a closed version-2 registry. Unknown fields, -legacy passthrough shapes, ambiguous aliases, missing environment-backed secrets, -unsupported schemas, missing allowlisted tools and collisions fail before model -execution. GitLab permits HTTPS upstreams only. Local review may also use an -absolute operator-selected stdio executable with bounded arguments and an -allowlisted environment; there is no shell or setup hook. - -The gateway discovers and freezes the inventory before OCR, validates the -admitted JSON Schema profile, URL-shaped argument origins, arguments, response -kinds, and all byte/item/depth/time/call/run bounds. Outbound arguments and -inbound descriptions, schemas and results cross DLP when enabled. HTTPS disables +`OCR_MCP_SERVERS_JSON` accepts only a closed operator registry. Every tool requires +an operator-authored description and closed input schema; undeclared object fields, +open nested objects, untyped array items and argument combinators are rejected. +Unknown fields, legacy passthrough shapes, ambiguous aliases, missing +environment-backed secrets, unsupported schemas, missing allowlisted tools and +collisions fail before model execution. GitLab permits HTTPS upstreams only. +Local review may also use an absolute operator-selected stdio executable with +bounded arguments and an allowlisted environment; there is no shell or setup hook. + +The gateway validates all operator descriptions and input schemas before opening +any upstream connection. It discovers and freezes the inventory before OCR and +exports only the operator interfaces. Live upstream definitions cannot add fields, +solicit repository data or alter model-facing instructions. The gateway validates +arguments, their URL-shaped origins, response kinds, and all +byte/item/depth/time/call/run bounds. Outbound arguments and +inbound output schemas and results cross DLP when enabled; operator interface text +crosses DLP before export. HTTPS disables redirects, cookies and ambient proxy trust; stdio uses toolkit-owned bounded framing and child-process cleanup. Returned links remain inert. Sampling, roots, elicitation, OAuth, server-directed headers, generic link retrieval, writes and resource/media projection are unsupported. +Delivered result strings, including structured keys and values, retain their +source-server provenance. Raw and normalized exact matches and bounded long +excerpts cannot be sent as model-selected values to a different configured server. +The operator schema authorizes the keys in destination arguments. Same-server reuse +remains available. This isolation also applies when generic DLP is explicitly +disabled and follows cache hits and shared-flight delivery. Publication DLP checks +short external structural keys at token boundaries. + The official Python MCP SDK v2 is the primary integration boundary, while the wire protocol is negotiated independently for OCR and each upstream. Explicitly qualified SDK v1/v2 peers are supported; SDK major is not a protocol revision. @@ -267,7 +323,7 @@ and OCR-session retention. The content-free `ocr.federation/v2` receipt records closed per-alias counts, argument/result DLP gate and reason counts, and cleanup state. Legacy v1 receipts remain readable but do not identify the rejection boundary or reason. -Receipt v13 reconciles OCR attempts independently with gateway +The ordinary receipt reconciles OCR attempts independently with gateway attempts and terminal outcomes. Used advisory tools, known denied/failed calls, or accounting mismatch make the run comment-only. Missing, malformed, unfinalized or cleanup-uncertain federation evidence blocks normal publication. @@ -318,6 +374,15 @@ is resolved once before acquisition and is shared by local and GitLab execution. With DLP enabled, context and federation ingress/egress plus publication sinks cross the shared detector. Private retention is checked separately. +Context model egress uses bounded HTML-decoded, nested decoded-markup, +display/source, compatibility and renderer-derived security views. Markup and +bare HTTP(S) or `mailto` destinations share one bounded sweep across original, +HTML-decoded and compatibility-normalized text. The sweep reads text only and +preserves the original presentation. Provider and broker admission, +hostile store readback and the final complete `context_get` projection each +enforce those views, so a reversible entity spelling cannot defer disclosure to +the model boundary. + Publication classifies sensitive material independently of diagnostic redaction: a redactor changing formatting alone does not prove that text contains a secret. Literal source can preserve operators only when exact full-source proof establishes @@ -332,8 +397,9 @@ Unicode, configured secret values, credential literals, contacts and forbidden source text. Configured values are checked before whitespace/NFC normalization as well as afterwards. An exact code match does not exempt sensitive material. -Admitted publication prose has a separate safe presentation step. HTTP/HTTPS, -relative and anchor Markdown links remain links after destination validation; +Publication prose has a separate safe presentation step that remains mandatory when +semantic DLP is disabled. HTTP/HTTPS, relative and anchor Markdown links remain links +after destination validation; unsafe schemes, user information, controls, malformed authorities and excessive decoding are rejected without network access. Leading whitespace cannot hide an encoded scheme-relative authority. Images become ordinary links. @@ -467,7 +533,24 @@ Unicode matches fail closed as `limit`. Source text and applicable normalized/decoded views are checked independently. A formatting boundary cannot silently join a contact into a bare identifier. Unproved formatted numbers retain conservative phone checks; arithmetic syntax alone -does not establish an executable-source role. Literal code +does not establish an executable-source role. Publication recognizes a range +when both ISO dates are calendar-valid and the entire phone candidate falls +inside the range. The range must have a clear token boundary on each side. +A colon immediately after the final date still prevents recognition. +The separator can be two or three periods, an ellipsis, or +an en dash, with up to 16 spaces or tabs on either side. A parsed link to a +fragment in the current document or a local `.md` or `.markdown` file can retain +Unicode letters in its heading. This requires a letter-based slug followed by a +literal ISO date and a destination without a query. An optional one- to +three-digit ordinal can precede the slug. +A standalone assignment such as `size = 16 * 1024 * 1024`, or that exact text +inside a supported inline code span, preserves its multiplication operators +during phone checks. This form accepts two to four power-of-two operands of up +to five decimal digits without leading zeros. At least two must be 1024 or +greater. Each `*` or `**` takes one to eight spaces or tabs on each side. +Text that also requires Mermaid entity decoding can still be withheld during +the independent check of the decoded representation. +Explicit contact context, adjacent phone numbers and credential checks still apply. Literal code does not activate its markup, while its obfuscated sensitive material remains subject to checks. Diagnostic substitutions never establish credential material; complete empty/masked query values stay empty/masked in surrounding syntax. @@ -537,8 +620,11 @@ six-digit layouts retain their previous conservative classification. Explicit contact labels/plus prefixes remain conservative. Underscores inside numeric identifiers do not activate Markdown emphasis. -A parsed false value bypasses those DLP checks for one run, emits a prominent warning in -private logs and bounded Technical details, and always blocks automatic approval. +A parsed false value bypasses semantic material checks for one run, emits a prominent +warning in private logs and bounded Technical details, and always blocks automatic +approval. Bounded inert Markdown projection remains mandatory: images become links, +HTML stays literal, fences use the neutral text renderer, and an unsafe destination or +presentation limit rejects result admission. Schema, byte/item/time/origin, identity, evidence, cleanup and posting-transaction gates remain active. Disabling DLP can expose sensitive data to an upstream MCP, the model, local Markdown, or GitLab. Re-enabling it cannot retract prior egress @@ -556,7 +642,7 @@ rejection: `forge_discussions`, `remediation_threads`, `ci_outcomes`, `external_context`, `operator_secret`, or `other`. Each rejected item counts each matching class once. Counts may overlap and need not sum to total omitted items. Rejected text is not retained or reprocessed later to infer attribution. -`ocr.publication-dlp-signal/v4`, Technical details and receipt v13 expose only +`ocr.publication-dlp-signal/v4`, Technical details and the ordinary receipt expose only bounded states and counts. Publication `ocr.publication/v2` separates omitted public fields and reasons from private-only sanitized fields and reasons; OCR coverage and provider posting counts remain independent. @@ -621,14 +707,14 @@ projects supply neither executable code nor exclusion policy to the audit. Definition provenance does not assert provider wire observation. See the [debug containment contract](local.md#private-debug-bundle). - Automatic approval binds exact source, actual target/diff, policy authority, - protection and author identity, skips self-approval, and accepts only exact - receipt v13 with enabled DLP and every existing eligibility gate satisfied. + protection and author identity, skips self-approval, and requires a current ordinary + receipt with enabled DLP and every existing eligibility gate satisfied. The toolkit never removes an existing approval; a prior bot approval may remain after retargeting under GitLab's approval-reset policy. - Provider identity, diff, authority and lifecycle are revalidated before normal publication and again before an eligible approval. Code-tuple movement and changed or unverifiable authority stop the write. Only a proven same protected - default-policy branch fast-forward may finish against captured P. A v13 result + default-policy branch fast-forward may finish against captured P. A current result whose MR became terminal is not newly published; the prior review remains. - Ambiguous inline creates use one author-bound readback without retry. Rollback deletes only recorded IDs absent from the baseline; marker text cannot claim ownership of another note. diff --git a/examples/gitlab/README.md b/examples/gitlab/README.md index 826d3e07..99501892 100644 --- a/examples/gitlab/README.md +++ b/examples/gitlab/README.md @@ -42,11 +42,13 @@ pipeline timing and merge-policy implications. It does not replace manual readin | Metadata | [`modes/metadata.gitlab-ci.yml`](modes/metadata.gitlab-ci.yml) | Bounded title, description, labels, and source branch | None | May remain enabled when all receipt gates pass | | Explicit limited unprotected target | [`modes/unprotected-target.gitlab-ci.yml`](modes/unprotected-target.gitlab-ci.yml) | Bounded metadata plus exact-target Rules as untrusted guidance | No protected policy or external federation | Structurally comment-only when the actual target is unprotected | | Enriched discussions | [`modes/enriched-discussions.gitlab-ci.yml`](modes/enriched-discussions.gitlab-ci.yml) | Metadata plus protected-policy GitLab discussions and remediation threads | GitLab reads before OCR | Explicitly disabled in the recipe | -| Governed MCP federation | [`modes/direct-mcp.gitlab-ci.yml`](modes/direct-mcp.gitlab-ci.yml) | Metadata plus model-selected, gateway-admitted tool results | Registry-v2 HTTPS upstream through the bounded gateway | Used advisory tools are comment-only; unused services and successful `review_read` use are not independent blockers | +| Governed MCP federation | [`modes/direct-mcp.gitlab-ci.yml`](modes/direct-mcp.gitlab-ci.yml) | Metadata plus model-selected, gateway-admitted tool results | Authorized HTTPS upstream through the bounded gateway | Used advisory tools are comment-only; unused services and successful `review_read` use are not independent blockers | -The default `auto` profile can use `off`, `metadata`, `enriched`, and configured registry-v2 federation for a single MR targeting an unprotected branch; its Rules and context policy come from the protected default branch P, while the actual diff and target stay separate. It never adds an approval for that unprotected target. The explicit `unprotected` recipe retains the earlier limited profile: only `off` or `metadata`, Rules at the exact captured target SHA as untrusted guidance, no accepted decisions or structured guidance, and no enriched context or external federation. Its limitation line does not make a complete result incomplete. A protected target keeps normal behavior in either profile. +Use the mode files from the same Git tag as the checksum-pinned wheel. The governed MCP recipe requires a wheel that accepts the operator-authored registry interface. -The enriched-discussions mode uses [`context/policy-discussions.json`](context/policy-discussions.json). Copy the selected policy to `.opencodereview/review-context-policy.json` on the protected policy branch. Governed federation is operator configuration: upstream descriptions, schemas, model-chosen arguments, and admitted results enter the OCR session only through the bounded gateway. Do not combine mode files until the resulting union has been reviewed deliberately. +The default `auto` profile can use `off`, `metadata`, `enriched`, and configured federation for a single MR targeting an unprotected branch; its Rules and context policy come from the protected default branch P, while the actual diff and target stay separate. It never adds an approval for that unprotected target. The explicit `unprotected` recipe retains the earlier limited profile: only `off` or `metadata`, Rules at the exact captured target SHA as untrusted guidance, no accepted decisions or structured guidance, and no enriched context or external federation. Its limitation line does not make a complete result incomplete. A protected target keeps normal behavior in either profile. + +The enriched-discussions mode uses [`context/policy-discussions.json`](context/policy-discussions.json). Copy the selected policy to `.opencodereview/review-context-policy.json` on the protected policy branch. Governed federation is operator configuration: the gateway exposes operator-authored tool definitions and admits model-selected arguments and upstream results. Do not combine mode files until the resulting union has been reviewed deliberately. For first setup, merge Rules and any protected review configuration into the selected policy branch before enabling the review job in a later merge request. If both are introduced together, the integration MR may stop before OCR with a setup-pending note; retrying it cannot promote source Rules, and later MRs work after the policy change merges. Explicit `unprotected` with missing target Rules, or a missing/mismatched immutable status identity, fails closed. A green advisory pipeline/job is not evidence that OCR or the model executed. GitLab Code Owners and approval rules remain separate merge policy, not OCR prerequisites. diff --git a/examples/gitlab/context/README.md b/examples/gitlab/context/README.md index acf2d662..e092cc47 100644 --- a/examples/gitlab/context/README.md +++ b/examples/gitlab/context/README.md @@ -15,7 +15,7 @@ limited comment-only mode and does not acquire enriched policy context: Current policy v4 does not accept `references`. Legacy v1-v3 references are parsed but never executed: optional references are skipped, and required references make the run comment-only. Configure any reviewed external tools separately through -the governed registry-v2 example in +the governed registry example in [`modes/direct-mcp.gitlab-ci.yml`](../modes/direct-mcp.gitlab-ci.yml). Do not copy old adapter commands or endpoints into a policy. See [Bounded review context](../../../docs/review-context.md) for migration behavior. diff --git a/examples/gitlab/modes/direct-mcp.gitlab-ci.yml b/examples/gitlab/modes/direct-mcp.gitlab-ci.yml index 878a6ab5..f6fa203b 100644 --- a/examples/gitlab/modes/direct-mcp.gitlab-ci.yml +++ b/examples/gitlab/modes/direct-mcp.gitlab-ci.yml @@ -1,5 +1,7 @@ variables: + # Use with a checksum-pinned toolkit release that supports registry v3. + # With an earlier release, use its matching example from the same Git tag. OCR_REVIEW_CONTEXT_MODE: "metadata" OCR_AUTO_APPROVE: "false" OCR_MCP_SERVERS_JSON: >- - {"version":2,"servers":{"review_evidence":{"transport":{"type":"https","url":"https://review-evidence.example.invalid/v1/mcp"},"auth":{"scheme":"Bearer","token_from":"REVIEW_EVIDENCE_MCP_TOKEN"},"tools":{"read_review_evidence":{"assurance":"advisory","resource_origins":["https://review-evidence.example.invalid"]}}}}} + {"version":3,"servers":{"review_evidence":{"transport":{"type":"https","url":"https://review-evidence.example.invalid/v1/mcp"},"auth":{"scheme":"Bearer","token_from":"REVIEW_EVIDENCE_MCP_TOKEN"},"tools":{"read_review_evidence":{"assurance":"advisory","description":"Read one operator-authorized review-evidence record by exact identifier.","input_schema":{"type":"object","properties":{"id":{"type":"string","maxLength":128}},"required":["id"],"additionalProperties":false},"resource_origins":["https://review-evidence.example.invalid"]}}}}} diff --git a/examples/gitlab/modes/enriched-discussions.gitlab-ci.yml b/examples/gitlab/modes/enriched-discussions.gitlab-ci.yml index 091ee024..5a5daeab 100644 --- a/examples/gitlab/modes/enriched-discussions.gitlab-ci.yml +++ b/examples/gitlab/modes/enriched-discussions.gitlab-ci.yml @@ -2,4 +2,4 @@ variables: # Pair with context/policy-discussions.json on the protected policy branch. OCR_REVIEW_CONTEXT_MODE: "enriched" OCR_AUTO_APPROVE: "false" - OCR_MCP_SERVERS_JSON: "{}" + OCR_MCP_SERVERS_JSON: "" diff --git a/examples/gitlab/modes/identity-only.gitlab-ci.yml b/examples/gitlab/modes/identity-only.gitlab-ci.yml index 5286da78..0f52d5ed 100644 --- a/examples/gitlab/modes/identity-only.gitlab-ci.yml +++ b/examples/gitlab/modes/identity-only.gitlab-ci.yml @@ -1,4 +1,4 @@ variables: OCR_REVIEW_CONTEXT_MODE: "off" OCR_AUTO_APPROVE: "true" - OCR_MCP_SERVERS_JSON: "{}" + OCR_MCP_SERVERS_JSON: "" diff --git a/examples/gitlab/modes/metadata.gitlab-ci.yml b/examples/gitlab/modes/metadata.gitlab-ci.yml index 4ef7add1..8418f9ec 100644 --- a/examples/gitlab/modes/metadata.gitlab-ci.yml +++ b/examples/gitlab/modes/metadata.gitlab-ci.yml @@ -1,4 +1,4 @@ variables: OCR_REVIEW_CONTEXT_MODE: "metadata" OCR_AUTO_APPROVE: "true" - OCR_MCP_SERVERS_JSON: "{}" + OCR_MCP_SERVERS_JSON: "" diff --git a/examples/gitlab/ocr-review.gitlab-ci.yml b/examples/gitlab/ocr-review.gitlab-ci.yml index 2acd6621..b0d4ff09 100644 --- a/examples/gitlab/ocr-review.gitlab-ci.yml +++ b/examples/gitlab/ocr-review.gitlab-ci.yml @@ -3,7 +3,7 @@ stages: - ai_review default: - image: python:3.12-slim + image: docker.io/library/python:3.12-slim@sha256:5b5fe805d367f8f5a359ded6ab2652b7f9a206453ee6ee789c0045ba6ec15016 variables: OCR_VERSION: "v1.14.5" diff --git a/pyproject.toml b/pyproject.toml index 8ff15290..3414b4fb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -186,3 +186,8 @@ showcontent = true directory = "removal" name = "Removals" showcontent = true + +[[tool.towncrier.type]] +directory = "contributor" +name = "Contributors" +showcontent = true diff --git a/scripts/dependency-audit.sh b/scripts/dependency-audit.sh index d333c834..67209289 100755 --- a/scripts/dependency-audit.sh +++ b/scripts/dependency-audit.sh @@ -9,7 +9,7 @@ mkdir -p .quality-logs UV_PROJECT_ENVIRONMENT=.quality-logs/dependency-audit-venv export UV_PROJECT_ENVIRONMENT -UV_VERSION=0.13.8 +UV_VERSION=0.13.10 installed_uv_version=$(uv --version 2>/dev/null || true) case "$installed_uv_version" in "uv $UV_VERSION"|"uv $UV_VERSION "*) use_uvx=0 ;; diff --git a/scripts/gitleaks.sh b/scripts/gitleaks.sh index 5ba98126..1a617a4d 100755 --- a/scripts/gitleaks.sh +++ b/scripts/gitleaks.sh @@ -31,7 +31,12 @@ if [ "${1:-}" = --staged ] || [ "${1:-}" = --tree ]; then exec python3 "$script_dir/public_content.py" fi -repository_root=$(git rev-parse --show-toplevel) +export GIT_NO_REPLACE_OBJECTS=1 +git_dir=$(git rev-parse --absolute-git-dir) +if [ "$(git rev-parse --is-shallow-repository)" != false ]; then + echo "gitleaks history scan requires a complete Git history" >&2 + exit 2 +fi head_ref=${2:-HEAD} if [ "$#" -ge 1 ]; then @@ -39,7 +44,7 @@ if [ "$#" -ge 1 ]; then else base_ref= for candidate in origin/main main; do - if git rev-parse --verify --quiet "${candidate}^{commit}" >/dev/null; then + if git rev-parse --verify --quiet --end-of-options "${candidate}^{commit}" >/dev/null; then base_ref=$candidate break fi @@ -50,8 +55,8 @@ else fi fi -base_commit=$(git rev-parse --verify "${base_ref}^{commit}") -head_commit=$(git rev-parse --verify "${head_ref}^{commit}") +base_commit=$(git rev-parse --verify --end-of-options "${base_ref}^{commit}") +head_commit=$(git rev-parse --verify --end-of-options "${head_ref}^{commit}") if ! git merge-base --is-ancestor "$base_commit" "$head_commit"; then echo "gitleaks base ref must be an ancestor of the head ref" >&2 @@ -69,15 +74,25 @@ if [ "$installed_version" != "$GITLEAKS_VERSION" ]; then exit 2 fi -# Match the pinned GitHub Action's pull-request scan: first-parent, no-merge -# patches beginning with the first feature commit. The Action receives that -# first commit as baseRef and expands it to baseRef^..headRef. -first_commit=$(git rev-list --first-parent --no-merges --reverse "${base_commit}..${head_commit}" | sed -n '1p') -if [ -n "$first_commit" ]; then - log_opts="--no-merges --first-parent ${first_commit}^..${head_commit}" -else - log_opts="--no-merges --first-parent -1 ${head_commit}" -fi +# Gitleaks reads both config and ignore files from its source directory. +# Present only the base's policy while reading candidate history as Git objects. +policy_dir=$(mktemp -d "${TMPDIR:-/tmp}/ocr-gitleaks.XXXXXXXX") +trap 'rm -r -- "$policy_dir"' EXIT +trap 'exit 1' HUP INT TERM +for policy_file in .gitleaks.toml .gitleaksignore; do + policy_entry=$(git ls-tree "$base_commit" -- "$policy_file") + case "$policy_entry" in + '') ;; + '100644 blob '*|'100755 blob '*) + git cat-file blob "${base_commit}:${policy_file}" >"$policy_dir/$policy_file" + ;; + *) echo "gitleaks base policy must be a regular file: $policy_file" >&2; exit 2 ;; + esac +done -cd "$repository_root" -exec gitleaks detect --redact --exit-code=1 --log-level=warn --log-opts="$log_opts" +unset GITLEAKS_CONFIG GITLEAKS_CONFIG_TOML +log_opts="--no-ext-diff --no-textconv --diff-merges=first-parent ${base_commit}..${head_commit}" +cd "$policy_dir" +GIT_DIR="$git_dir" GIT_WORK_TREE="$policy_dir" \ + gitleaks git --redact=100 --exit-code=1 --log-level=warn --ignore-gitleaks-allow \ + --log-opts="$log_opts" . diff --git a/scripts/installed_runtime_smoke.py b/scripts/installed_runtime_smoke.py index 41ff038e..69f7ca27 100644 --- a/scripts/installed_runtime_smoke.py +++ b/scripts/installed_runtime_smoke.py @@ -15,6 +15,9 @@ from ocr_toolkit.federation import admission, parse_registry, start_gateway, transport from ocr_toolkit.federation import gateway as gateway_module +from ocr_toolkit.federation.contracts import REGISTRY_VERSION + +_OPERATOR_DESCRIPTION = "Check the installed runtime with one controlled value." peer = MCPServer("installed-runtime-smoke-peer") @@ -31,7 +34,7 @@ def _registry() -> str: return json.dumps( { - "version": 2, + "version": REGISTRY_VERSION, "servers": { "synthetic": { "transport": { @@ -39,7 +42,18 @@ def _registry() -> str: "command": sys.executable, "args": ["-I", str(Path(__file__).resolve()), "--peer"], }, - "tools": {"schema_probe": {"assurance": "review_read"}}, + "tools": { + "schema_probe": { + "assurance": "review_read", + "description": _OPERATOR_DESCRIPTION, + "input_schema": { + "type": "object", + "properties": {"value": {"type": "string"}}, + "required": ["value"], + "additionalProperties": False, + }, + } + }, } }, } @@ -65,11 +79,12 @@ async def _exercise(running: Any) -> None: listing = await client.list_tools() if len(listing.tools) != 1 or listing.tools[0].name != "synthetic__schema_probe": raise RuntimeError("installed gateway exported an unexpected tool inventory") - schema = listing.tools[0].input_schema + expected = json.loads(_registry())["servers"]["synthetic"]["tools"]["schema_probe"] + exported_schema = json.dumps(listing.tools[0].input_schema, sort_keys=True) + expected_schema = json.dumps(expected["input_schema"], sort_keys=True) if ( - schema.get("type") != "object" - or schema.get("required") != ["value"] - or schema.get("properties", {}).get("value", {}).get("type") != "string" + listing.tools[0].description != expected["description"] + or exported_schema != expected_schema ): raise RuntimeError("installed gateway exported an unexpected tool schema") result = await client.call_tool("synthetic__schema_probe", {"value": "controlled"}) diff --git a/scripts/ocr_qualification/delivery.py b/scripts/ocr_qualification/delivery.py index 8853f449..e9feb44b 100644 --- a/scripts/ocr_qualification/delivery.py +++ b/scripts/ocr_qualification/delivery.py @@ -359,8 +359,19 @@ def render_workflow_issue(evidence: dict[str, Any], run_url: str) -> str: body += f"\n### Workflow evidence\n\n- run: {run_url}\n- classification: `{classification}`\n" if classification == "automatic-safe": body += ( - "- the aggregation job prepares one exact patch only if the complete observed chain is automatic-safe\n" - "- opening a real PR requires the optional OCR update bot credential so protected checks run\n" + "- Check `ocr-chain-assessment.json` in the `ocr-compatibility-chain` artifact. " + "The `assess-complete-chain` job summary records the aggregate classification, " + "qualification mode, and patch generation and artifact upload outcomes. " + "The aggregation job prepares `ocr-chain-update.patch` only after all " + "candidate jobs succeed, the complete observed chain is automatic-safe, " + "and `qualification_only` is off. " + "A maintainer reviews the patch and opens the PR.\n" + "- If the patch is missing or expired, confirm the chain was eligible and its " + "final release is still unseen above the current `monitoring_floor`. " + "Then dispatch **OCR compatibility** from `main`. " + "Leave `tag` and `after_tag` empty and `qualification_only` off. " + "Set `through_tag` to the final release of the desired chain. " + "Check the new chain assessment and artifact before applying the patch.\n" ) return body diff --git a/scripts/release_authorization.py b/scripts/release_authorization.py index d44073c2..c79594b6 100644 --- a/scripts/release_authorization.py +++ b/scripts/release_authorization.py @@ -239,7 +239,7 @@ def authorize_release( commit = _full_commit(commit, "release merge commit") base_sha = _full_commit(base.get("sha"), "release base commit") head_sha = _full_commit(head.get("sha"), "reviewed release head") - if not isinstance(number, int) or number < 1: + if type(number) is not int or number < 1: raise AuthorizationError("release pull request number is invalid") if requested_version and requested_version != version: raise AuthorizationError("requested version does not match the release pull request") diff --git a/src/ocr_toolkit/_qualified_handoffs.json b/src/ocr_toolkit/_qualified_handoffs.json index 9c25064d..54531c4f 100644 --- a/src/ocr_toolkit/_qualified_handoffs.json +++ b/src/ocr_toolkit/_qualified_handoffs.json @@ -58,5 +58,35 @@ "size": 62431394 } ] + }, + "1.14.6": { + "capabilities": [ + "analysis", + "chatgpt_auth", + "diagram_output", + "gitlink_projection", + "local_review_continuation", + "local_review_incremental" + ], + "local_review_assets": [ + { + "capabilities": [ + "local_review_continuation", + "local_review_incremental" + ], + "name": "opencodereview-darwin-arm64", + "sha256": "24d043eefd63dadfbf64b1dcc49eb3430bf63c518d6b4d7627985a4e5f0c87a8", + "size": 61029138 + }, + { + "capabilities": [ + "local_review_continuation", + "local_review_incremental" + ], + "name": "opencodereview-linux-amd64", + "sha256": "a91fea039d7070f8155e8bdaac3b8324e97104fb510ac0fa97de40e622ee3fff", + "size": 62451874 + } + ] } } diff --git a/src/ocr_toolkit/common/redaction.py b/src/ocr_toolkit/common/redaction.py index 9f992dcb..cd598864 100644 --- a/src/ocr_toolkit/common/redaction.py +++ b/src/ocr_toolkit/common/redaction.py @@ -413,8 +413,9 @@ def has_sensitive_material( *, credential_view: str | None = None, values: tuple[str, ...] | None = None, + known_only: bool = False, ) -> bool: - """Classify publication material using shared rules, not diagnostic rewrites.""" + """Check configured values and, by default, structural credential patterns.""" values = environment_secret_values() if values is None else values # A decoded passphrase may itself contain words rewritten by token-name @@ -422,6 +423,10 @@ def has_sensitive_material( if redact_env_secret_values(text, values=values) != text: return True prepared = normalize_redaction_tokens(strip_redaction_bypass_controls(text)) + if redact_env_secret_values(prepared, values=values) != prepared: + return True + if known_only: + return False view = text if credential_view is None else credential_view credential = ( prepared @@ -429,8 +434,7 @@ def has_sensitive_material( else normalize_redaction_tokens(strip_redaction_bypass_controls(view)) ) return bool( - redact_env_secret_values(prepared, values=values) != prepared - or redact_url_userinfo_only(prepared) != prepared + redact_url_userinfo_only(prepared) != prepared or _query_has_material(credential) or _BEARER_RE.search(prepared) or _JWT_RE.search(prepared) @@ -469,13 +473,18 @@ def redact_sensitive(text: str) -> str: return _JWT_RE.sub("***", redacted) +class RedactedKeyCollision(ValueError): + """Two different object keys normalize to the same sanitized key.""" + + def sanitize_ocr_value(value: Any) -> Any: """Recursively redact OCR-controlled strings before MR publication. OCR JSON is model/provider-controlled output. Treat every string as publishable until proven otherwise: comments, warnings, tool metadata, and future fields all pass through this sanitizer before any formatting, - fingerprinting, or GitLab posting logic consumes them. + fingerprinting, or GitLab posting logic consumes them. Reject ambiguous + keys so the sanitized result preserves each member's source identity. """ if isinstance(value, str): @@ -485,7 +494,9 @@ def sanitize_ocr_value(value: Any) -> Any: if isinstance(value, dict): sanitized: dict[Any, Any] = {} for key, item in value.items(): - sanitized_key = sanitize_ocr_value(key) if isinstance(key, str) else key + sanitized_key = redact_sensitive(key) if isinstance(key, str) else key + if sanitized_key in sanitized: + raise RedactedKeyCollision("OCR result keys collide during redaction") sanitized[sanitized_key] = sanitize_ocr_value(item) return sanitized return value diff --git a/src/ocr_toolkit/context/broker.py b/src/ocr_toolkit/context/broker.py index 72029a67..2e942664 100644 --- a/src/ocr_toolkit/context/broker.py +++ b/src/ocr_toolkit/context/broker.py @@ -100,8 +100,11 @@ def _publish_projection( publication=True, forbidden=forbidden, ) - if not checked.admitted or checked.text != text: + if not checked.admitted or checked.text is None: return None + if checked.text != text and checked.reason != "disabled": + return None + projected["text"] = checked.text return projected @@ -119,7 +122,12 @@ def _normalized_record( continue value = record[field] if field == "text": - checked = check_text(value, budgets=budgets, forbidden=forbidden) + checked = check_text( + value, + budgets=budgets, + model_egress=True, + forbidden=forbidden, + ) if not checked.admitted or checked.text is None: return None result[field] = checked.text @@ -130,6 +138,7 @@ def _normalized_record( checked = check_text( normalized, budgets=TextBudgets(max_chars=512, max_bytes=2_048, max_lines=1), + model_egress=True, forbidden=forbidden, ) if not checked.admitted: @@ -166,6 +175,7 @@ def _normalized_record( checked = check_text( path, budgets=TextBudgets(max_chars=512, max_bytes=2_048, max_lines=1), + model_egress=True, forbidden=forbidden, ) if not checked.admitted: @@ -269,7 +279,12 @@ def prepare_remediation_records( pending: list[PendingContextRecord] = [] for record in records: - root = check_text(record.root_body, budgets=policy.budgets, forbidden=forbidden) + root = check_text( + record.root_body, + budgets=policy.budgets, + model_egress=True, + forbidden=forbidden, + ) if ( not root.admitted or root.text != record.root_body @@ -293,7 +308,12 @@ def prepare_remediation_records( replies: list[dict[str, object]] = [] valid = True for expected_order, reply in enumerate(record.replies): - checked = check_text(reply.body, budgets=policy.budgets, forbidden=forbidden) + checked = check_text( + reply.body, + budgets=policy.budgets, + model_egress=True, + forbidden=forbidden, + ) if ( reply.order != expected_order or reply.author_class not in policy.account_classes diff --git a/src/ocr_toolkit/context/ci_outcomes.py b/src/ocr_toolkit/context/ci_outcomes.py index 006f0fc2..bf97ff90 100644 --- a/src/ocr_toolkit/context/ci_outcomes.py +++ b/src/ocr_toolkit/context/ci_outcomes.py @@ -96,7 +96,13 @@ def prepare_ci_outcome_records( continue values = (record.check, *record.path_prefixes) checked = [ - check_text(value, budgets=CI_IDENTITY_BUDGETS, forbidden=forbidden) for value in values + check_text( + value, + budgets=CI_IDENTITY_BUDGETS, + model_egress=True, + forbidden=forbidden, + ) + for value in values ] if any( not value.admitted or value.text != original for value, original in zip(checked, values) diff --git a/src/ocr_toolkit/context/dlp/admission.py b/src/ocr_toolkit/context/dlp/admission.py index 9701cf4d..117f41dd 100644 --- a/src/ocr_toolkit/context/dlp/admission.py +++ b/src/ocr_toolkit/context/dlp/admission.py @@ -7,7 +7,7 @@ from collections.abc import Callable, Iterator, Mapping from contextlib import contextmanager from contextvars import ContextVar -from dataclasses import dataclass +from dataclasses import dataclass, field from functools import wraps from typing import ParamSpec @@ -20,7 +20,9 @@ ) from ocr_toolkit.context.code_text import CodeTextContext, TextSink from ocr_toolkit.context.contracts import TextBudgets +from ocr_toolkit.context.dlp.arithmetic import binary_size_phone_view from ocr_toolkit.context.dlp.credentials import credential_reference_view +from ocr_toolkit.context.dlp.datetimes import dated_anchor_phone_view from ocr_toolkit.context.dlp.decoding import _html_decode, _mermaid_decode, bounded_nfkc from ocr_toolkit.context.dlp.email import contains_email from ocr_toolkit.context.dlp.markup import ( @@ -52,7 +54,8 @@ MARKDOWN_FORMAT_RE = re.compile(r"[`*_~]") DISPLAY_WHITESPACE_RE = re.compile(r"\s+") MIN_EXACT_EXCERPT_CHARS = 24 -MAX_EXCERPT_SEARCH_COST = 50_000_000 +MAX_FORBIDDEN_MATCH_WORK = 50_000_000 +EXCERPT_INDEX_WINDOWS = 128 * 1024 DLP_ENV_NAME = "OCR_DLP_ENABLED" TRUE_VALUES = frozenset({"1", "true", "yes", "on"}) FALSE_VALUES = frozenset({"0", "false", "no", "off"}) @@ -128,6 +131,7 @@ class ForbiddenValue: value: str source_class: str + structural_key: bool = False def __post_init__(self) -> None: if self.source_class not in FORBIDDEN_SOURCE_CLASSES: @@ -138,34 +142,75 @@ def __post_init__(self) -> None: class ForbiddenMatcher: """Compile protected values and their closed provenance once.""" - exact: tuple[str, ...] - sources: tuple[frozenset[str], ...] = () limited: bool = False + short: dict[tuple[int, bool], dict[str, frozenset[str]]] = field(default_factory=dict) + long: tuple[tuple[str, frozenset[str]], ...] = () + long_windows: int = 0 @classmethod def compile(cls, values: tuple[str | ForbiddenValue, ...]) -> ForbiddenMatcher: - registered: dict[str, set[str]] = {} + registered: dict[tuple[str, bool], set[str]] = {} for item in values: value = item.value if isinstance(item, ForbiddenValue) else item source = item.source_class if isinstance(item, ForbiddenValue) else "other" + structural_key = isinstance(item, ForbiddenValue) and item.structural_key candidate = normalize_text(value, allow_horizontal_tabs=True) if not candidate: continue try: representations = (_display_normalize(candidate), _source_normalize(candidate)) except (RepresentationLimit, TimeoutError): - return cls((), (), limited=True) + return cls(limited=True) for representation in representations: if representation: - registered.setdefault(representation, set()).add(source) - return cls(tuple(registered), tuple(frozenset(v) for v in registered.values())) + short_key = structural_key and len(representation) < MIN_EXACT_EXCERPT_CHARS + registered.setdefault((representation, short_key), set()).add(source) + short: dict[tuple[int, bool], dict[str, frozenset[str]]] = {} + long: list[tuple[str, frozenset[str]]] = [] + long_windows = 0 + for (text, short_key), classes in registered.items(): + if len(text) < MIN_EXACT_EXCERPT_CHARS: + short.setdefault((len(text), short_key), {})[text] = frozenset(classes) + else: + long.append((text, frozenset(classes))) + long_windows += len(text) - MIN_EXACT_EXCERPT_CHARS + 1 + return cls(short=short, long=tuple(long), long_windows=long_windows) + + def _match_short(self, value: str, matched: set[str]) -> None: + for (width, tokens), rules in self.short.items(): + if len(rules) <= 4: + for candidate, classes in rules.items(): + found = candidate in value + if found and tokens: + found = ( + re.search(rf"(? None: + width = MIN_EXACT_EXCERPT_CHARS + for start in range(0, windows, EXCERPT_INDEX_WINDOWS): + end = min(windows, start + EXCERPT_INDEX_WINDOWS) + excerpts = {value[i : i + width] for i in range(start, end)} + for candidate, classes in self.long: + if not classes <= matched and any( + candidate[i : i + width] in excerpts for i in range(len(candidate) - width + 1) + ): + matched.update(classes) def match_details(self, value: str) -> tuple[str | None, tuple[str, ...]]: """Return rejection and aggregate classes without retaining rejected content.""" if self.limited: return "limit", () - if not self.exact: + if not self.short and not self.long: return None, () matched: set[str] = set() try: @@ -173,28 +218,18 @@ def match_details(self, value: str) -> tuple[str | None, tuple[str, ...]]: except (RepresentationLimit, TimeoutError): return "limit", () for normalized in representations: - comparison_cost = max(1, len(normalized)) * sum( - max(1, len(candidate)) for candidate in self.exact + windows = max(0, len(normalized) - MIN_EXACT_EXCERPT_CHARS + 1) if self.long else 0 + chunks = (windows + EXCERPT_INDEX_WINDOWS - 1) // EXCERPT_INDEX_WINDOWS + work = ( + windows + + chunks * self.long_windows + + len(normalized) + * sum(len(rules) if len(rules) <= 4 else 1 for rules in self.short.values()) ) - if comparison_cost > MAX_EXCERPT_SEARCH_COST: + if work > MAX_FORBIDDEN_MATCH_WORK: return "limit", () - long_indices = tuple( - i - for i, candidate in enumerate(self.exact) - if len(candidate) >= MIN_EXACT_EXCERPT_CHARS - ) - windows = max(0, len(normalized) - MIN_EXACT_EXCERPT_CHARS + 1) - if windows * sum(len(self.exact[i]) for i in long_indices) > MAX_EXCERPT_SEARCH_COST: - return "limit", () - for i, candidate in enumerate(self.exact): - found = candidate == normalized or candidate in normalized - if not found and windows and len(candidate) >= MIN_EXACT_EXCERPT_CHARS: - found = normalized in candidate or any( - normalized[j : j + MIN_EXACT_EXCERPT_CHARS] in candidate - for j in range(windows) - ) - if found: - matched.update(self.sources[i] if self.sources else {"other"}) + self._match_short(normalized, matched) + self._match_long(normalized, windows, matched) return ("forbidden", tuple(sorted(matched))) if matched else (None, ()) def match_reason(self, value: str) -> str | None: @@ -204,6 +239,12 @@ def matches(self, value: str) -> bool: return self.match_reason(value) is not None +def _token_boundaries(value: str, start: int, end: int) -> bool: + before = value[start - 1] if start else "" + after = value[end] if end < len(value) else "" + return not (before == "_" or before.isalnum() or after == "_" or after.isalnum()) + + def normalize_text(value: object, *, allow_horizontal_tabs: bool = False) -> str | None: """Normalize NFC/newlines and reject unsupported controls.""" @@ -239,14 +280,22 @@ def _literal_contact_view(value: str, *, visible: bool, formatting: bool = True) return _source_normalize(normalized) -def _markup_phone(value: str, *, literal: bool) -> bool: +def _markup_phone(value: str, *, literal: bool, publication: bool) -> bool: markup = interpret_markdown(phone_markup_view(value, formatting=False)) # Visible formatting is interpreted by the parser. Hidden HTML material # needs an independent sweep; stripping it or joining its digits would # silently make an obfuscated contact look like an opaque identifier. - return (not literal and _contains_phone(_literal_normalize(markup.contacts))) or any( - _contains_phone(phone_markup_view(_literal_normalize(fragment))) - for fragment in markup.hidden + hidden = ( + (*markup.hidden_nonlinks, *(dated_anchor_phone_view(link) for link in markup.links)) + if publication and not literal + else markup.hidden + ) + return ( + not literal + and _contains_phone(_literal_normalize(markup.contacts), publication=publication) + ) or any( + _contains_phone(phone_markup_view(_literal_normalize(fragment)), publication=publication) + for fragment in hidden ) @@ -270,6 +319,7 @@ def _check_material( *, budgets: TextBudgets, publication: bool = False, + model_egress: bool = False, forbidden: tuple[str | ForbiddenValue, ...] = (), forbidden_matcher: ForbiddenMatcher | None = None, allow_horizontal_tabs: bool = False, @@ -321,17 +371,22 @@ def _check_material( literal = sink != TextSink.PROSE or allow_opaque_code display_transform = _literal_normalize if literal else _display_normalize source_transform = _literal_normalize if literal else _source_normalize - decoded = _html_decode(normalized) if publication else normalized - decoded_semantic = _semantic_secret_text(_html_decode(semantic)) if publication else semantic + interpret_security_views = publication or model_egress + decoded = _html_decode(normalized) if interpret_security_views else normalized + decoded_semantic = ( + _semantic_secret_text(_html_decode(semantic)) if interpret_security_views else semantic + ) if ( decoded.replace("\r\n", "\n").replace("\r", "\n").strip().count("\n") + 1 > budgets.max_lines ): return DLPResult(False, None, "limit", "lines") - displayed = display_transform(normalized) if publication else normalized - source = source_transform(normalized) if publication else normalized + displayed = display_transform(normalized) if interpret_security_views else normalized + source = source_transform(normalized) if interpret_security_views else normalized views = [] - if publication: + markup_material: tuple[str, ...] = () + joined_destinations: tuple[str, ...] = () + if interpret_security_views: views.extend( ( ("decoded", decoded, decoded_semantic), @@ -339,7 +394,8 @@ def _check_material( ("source", source, source_transform(decoded_semantic)), ) ) - for text in decoded_markup_material(normalized): + markup_material, joined_destinations = decoded_markup_material(normalized, decoded) + for text in markup_material: views.append(("decoded_markup", text, _semantic_secret_text(text))) compatible_markup = bounded_nfkc(text) if compatible_markup != text: @@ -363,11 +419,11 @@ def _check_material( return DLPResult(False, None, "limit", "lines") if redact_env_secret_values(mermaid_original, values=secrets) != mermaid_original: return DLPResult(False, None, "secret", "mermaid") - if publication and has_unsafe_controls(mermaid, display=True): + if interpret_security_views and has_unsafe_controls(mermaid, display=True): return DLPResult(False, None, "laundering", "display_control") mermaid_semantic = _semantic_secret_text(_html_decode(_mermaid_decode(decoded_semantic))) views.append(("mermaid", mermaid, mermaid_semantic)) - if publication: + if interpret_security_views: views.extend( ( ( @@ -383,7 +439,7 @@ def _check_material( ) ) security_views = [] - if publication and literal: + if interpret_security_views and literal: literal_views = [("literal", normalized, semantic)] if has_mermaid: literal_views.append(("literal_mermaid", mermaid, mermaid_semantic)) @@ -409,6 +465,21 @@ def _check_material( seen_secrets.add((candidate, secret_view)) if has_sensitive_material(candidate, credential_view=secret_view, values=secrets): return DLPResult(False, None, "secret", representation) + if secrets: + # A registered value can span the original separators between URLs. + for candidate in joined_destinations: + if has_sensitive_material(candidate, values=secrets, known_only=True): + return DLPResult(False, None, "secret", "decoded_markup") + compatible_destination = bounded_nfkc(candidate) + if compatible_destination != candidate and has_sensitive_material( + compatible_destination, values=secrets, known_only=True + ): + return DLPResult(False, None, "secret", "compatible_markup") + arithmetic_phone = ( + binary_size_phone_view(normalized, prose=sink == TextSink.PROSE and not literal) + if publication and sink != TextSink.DIAGRAM_LABEL + else normalized + ) seen_pii: set[str] = set() for representation, candidate in ( ("normalized", normalized), @@ -432,7 +503,12 @@ def _check_material( transform=email_transform, ): return DLPResult(False, None, "pii", f"email:{representation}") - if _contains_phone(candidate) or _markup_phone(candidate, literal=literal): + phone_candidate = candidate + if representation == "source" and not literal and arithmetic_phone != normalized: + phone_candidate = _source_normalize(arithmetic_phone) + if _contains_phone(phone_candidate, publication=publication) or _markup_phone( + phone_candidate, literal=literal, publication=publication + ): return DLPResult(False, None, "pii", f"phone:{representation}") # Secret/email deobfuscation remains independent of literal rendering. # Strong contact signals also retain the stricter arbitrary-format sweep. @@ -444,6 +520,8 @@ def _check_material( if publication and literal: context = code_context if allow_opaque_code and sink != TextSink.DIAGRAM_LABEL else None phone_original = context.phone_view(normalized) if context is not None else normalized + if phone_original == normalized: + phone_original = arithmetic_phone phone_views = ( (phone_original, _html_decode(_mermaid_decode(_html_decode(phone_original)))) if has_mermaid @@ -456,16 +534,16 @@ def _check_material( candidate, visible=visible, formatting=not (allow_opaque_code and sink == TextSink.LITERAL_CODE), - ) + ), + publication=True, ): return DLPResult(False, None, "pii", "phone:literal_markup") matcher = forbidden_matcher or ForbiddenMatcher.compile(forbidden) matcher_reason, source_classes = matcher.match_details(normalized) - for name, candidate, _secret in views: - if name == "decoded_markup": - reason, classes = matcher.match_details(candidate) - matcher_reason = matcher_reason or reason - source_classes = tuple(sorted(set(source_classes) | set(classes))) + for candidate in (*markup_material, *joined_destinations): + reason, classes = matcher.match_details(candidate) + matcher_reason = matcher_reason or reason + source_classes = tuple(sorted(set(source_classes) | set(classes))) if has_mermaid: mermaid_reason, mermaid_sources = matcher.match_details(mermaid) matcher_reason = matcher_reason or mermaid_reason @@ -473,7 +551,7 @@ def _check_material( if matcher_reason: return DLPResult(False, None, matcher_reason, "forbidden_matcher", source_classes) if ( - publication + interpret_security_views and not (allow_opaque_code and sink == TextSink.LITERAL_CODE) and has_unsafe_controls(decoded, display=True) ): @@ -504,6 +582,7 @@ def check_text( *, budgets: TextBudgets, publication: bool = False, + model_egress: bool = False, forbidden: tuple[str | ForbiddenValue, ...] = (), forbidden_matcher: ForbiddenMatcher | None = None, allow_horizontal_tabs: bool = False, @@ -512,12 +591,13 @@ def check_text( sink: TextSink = TextSink.PROSE, enabled: bool | None = None, ) -> DLPResult: - """Admit all material, prepare prose, and independently admit the prepared text.""" + """Admit semantic material when enabled and always prepare publication prose.""" checked = _check_material( value, budgets=budgets, publication=publication, + model_egress=model_egress, forbidden=forbidden, forbidden_matcher=forbidden_matcher, allow_horizontal_tabs=allow_horizontal_tabs, @@ -526,12 +606,7 @@ def check_text( sink=sink, enabled=enabled, ) - if ( - not checked.admitted - or checked.reason == "disabled" - or not publication - or sink != TextSink.PROSE - ): + if not checked.admitted or not publication or sink != TextSink.PROSE: return checked assert checked.text is not None try: @@ -543,6 +618,7 @@ def check_text( prepared, budgets=budgets, publication=True, + model_egress=model_egress, forbidden=forbidden, forbidden_matcher=forbidden_matcher, allow_horizontal_tabs=allow_horizontal_tabs, diff --git a/src/ocr_toolkit/context/dlp/arithmetic.py b/src/ocr_toolkit/context/dlp/arithmetic.py new file mode 100644 index 00000000..4bdf3dd8 --- /dev/null +++ b/src/ocr_toolkit/context/dlp/arithmetic.py @@ -0,0 +1,59 @@ +"""Recognize complete literal binary-size assignments for phone interpretation.""" + +from __future__ import annotations + +import re + +from ocr_toolkit.context.dlp.contact_labels import _explicit_context +from ocr_toolkit.context.dlp.decoding import _technical_decode, bounded_nfkc +from ocr_toolkit.context.dlp.markup import interpret_markdown, strip_format_markers + +_INTEGER = r"[1-9][0-9]{0,4}" +_OPERATOR = r"[ \t]{1,8}\*\*?[ \t]{1,8}" +_ASSIGNMENT = re.compile( + rf"[A-Za-z_][A-Za-z0-9_]{{0,63}}[ \t]{{0,8}}=[ \t]{{0,8}}" + rf"(?P{_INTEGER}(?:{_OPERATOR}{_INTEGER}){{1,3}})" +) +_OPERATORS = re.compile(_OPERATOR) + + +def _assignment_phone_view(value: str) -> str: + assignment = _ASSIGNMENT.fullmatch(value) + if assignment is None or _explicit_context(value, assignment.start("expression")): + return value + expression = assignment["expression"] + operands = [int(token) for token in _OPERATORS.split(expression)] + # Require two four-digit-or-larger scale factors so short telephone groups + # cannot gain authority merely from ASCII stars in an assignment. + if sum(operand >= 1024 for operand in operands) < 2 or any( + operand & (operand - 1) for operand in operands + ): + return value + return value[: assignment.start("expression")] + expression.replace("*", "\u00d7") + + +def binary_size_phone_view(value: str, *, prose: bool) -> str: + """Keep operators in complete standalone or exact inline code assignments.""" + whole = _assignment_phone_view(value) + if whole != value or not prose or "`" not in value or "*" not in value: + return whole + parts = [] + cursor = 0 + for opening, start, end in interpret_markdown(value).exact_code_bodies: + if start < cursor or _explicit_context(value, opening): + continue + # Decode and normalize only the adjacent label window. Exact original + # delimiters and assignment bytes still supply the arithmetic proof. + prefix = value[max(0, opening - 256) : opening] + canonical = strip_format_markers(bounded_nfkc(_technical_decode(prefix), original=prefix)) + if _explicit_context(canonical, len(canonical)): + continue + fragment = value[start:end] + candidate = _assignment_phone_view(fragment) + if candidate != fragment: + parts.extend((value[cursor:start], candidate)) + cursor = end + if not parts: + return value + parts.append(value[cursor:]) + return "".join(parts) diff --git a/src/ocr_toolkit/context/dlp/datetimes.py b/src/ocr_toolkit/context/dlp/datetimes.py index b9ae12dc..27b56e07 100644 --- a/src/ocr_toolkit/context/dlp/datetimes.py +++ b/src/ocr_toolkit/context/dlp/datetimes.py @@ -5,8 +5,20 @@ import re import unicodedata from datetime import date, datetime +from urllib.parse import unquote -CALENDAR_DAY_PATTERN = r"(?:\d{4}-\d{2}-\d{2}|\d{2}\.\d{2}\.\d{4})" +_ISO_DAY = r"\d{4}-\d{2}-\d{2}" +CALENDAR_DAY_PATTERN = rf"(?:{_ISO_DAY}|\d{{2}}\.\d{{2}}\.\d{{4}})" +_DATE_RANGE = re.compile( + rf"(?P{_ISO_DAY})[ \t]{{0,16}}(?:\.\.\.?|\u2026|\u2013)[ \t]{{0,16}}" + rf"(?P{_ISO_DAY})" +) +_LOCAL_MARKDOWN_PATH = re.compile( + r"/?(?:(?:\.{1,2}|[A-Za-z0-9_-][A-Za-z0-9._-]{0,127})/)*" + r"[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}\.(?:md|markdown)\Z", + re.IGNORECASE | re.ASCII, +) +_HIGH_PERCENT_BYTE = re.compile(r"%(?:[89a-fA-F][0-9a-fA-F])") _DATETIME = re.compile( rf"(?P{CALENDAR_DAY_PATTERN})(?:T|[ \t]+)" r"(?P\d{2}:\d{2}(?::\d{2}(?:[.,]\d{1,9})?)?)" @@ -31,6 +43,69 @@ def _word_part(char: str) -> bool: return char.isalnum() or unicodedata.category(char).startswith("M") +def complete_date_range(value: str, start: int, end: int) -> bool: + """Prove both ISO days within one closed range around the phone candidate.""" + + for block in _DATE_RANGE.finditer( + value, max(0, start - _WINDOW), min(len(value), end + _WINDOW) + ): + if not block.start() <= start < end <= block.end(): + continue + left = value[block.start() - 1] if block.start() else "" + tail = value[block.end() : block.end() + 2] + right = tail[:1] + if left and (_word_part(left) or left in "_.:+/-"): + continue + if right and (_word_part(right) or right in "_:+/-\u2026\u2013"): + continue + if right == "." and len(tail) == 2 and (_word_part(tail[1]) or tail[1] in "_.:+/-"): + continue + try: + calendar_day(block["first"]) + calendar_day(block["last"]) + except ValueError: + continue + return True + return False + + +def dated_anchor_phone_view(value: str) -> str: + """Undo UTF-8 letter escaping in a parsed local Markdown date anchor only.""" + + if len(value) > 1024 or "%" not in value: + return value + path, separator, fragment = value.partition("#") + if not separator or (path and not _LOCAL_MARKDOWN_PATH.fullmatch(path)): + return value + # The date and any heading ordinal must be present in their literal form. + # Only the preceding word slug can contribute percent-encoded material. + raw_date = fragment[-10:] + if fragment[-11:-10] != "-" or not re.fullmatch(_ISO_DAY, raw_date): + return value + raw_slug = fragment[:-11] + if "%" in _HIGH_PERCENT_BYTE.sub("", raw_slug): + return value + try: + slug = unquote(raw_slug, errors="strict") + calendar_day(raw_date) + except ValueError: + return value + words = slug.split("-") + if re.fullmatch(r"[0-9]{1,3}", words[0]): + words = words[1:] + if not words or any( + not word + or not word[0].isalpha() + or any( + not char.isalpha() and not unicodedata.category(char).startswith("M") for char in word + ) + or word.casefold() in {"contact", "phone", "telephone", "tel", "call"} + for word in words + ): + return value + return f"{path}#{slug}-{raw_date}" + + def complete_datetime(value: str, start: int, end: int) -> bool: """Recognize a whole parsed timestamp containing this entire numeric candidate.""" diff --git a/src/ocr_toolkit/context/dlp/markup.py b/src/ocr_toolkit/context/dlp/markup.py index 08d1b2ce..99e64507 100644 --- a/src/ocr_toolkit/context/dlp/markup.py +++ b/src/ocr_toolkit/context/dlp/markup.py @@ -186,10 +186,12 @@ def finalize_tokens(self, tokens: list[dict[str, Any]], depth: int) -> list[dict def parse_codespan(self, match: re.Match[str], state: InlineState) -> int: end = super().parse_codespan(match, state) if state.tokens and state.tokens[-1]["type"] == "codespan" and "dlp_start" in state.env: + offset = state.env["dlp_start"] state.tokens[-1]["dlp_opening"] = ( - state.env["dlp_start"] + match.start(), + offset + match.start(), len(match[0]), ) + state.tokens[-1]["dlp_body"] = (offset + match.end(), offset + end - len(match[0])) return end @@ -238,6 +240,8 @@ class MarkupText: code_openings: tuple[tuple[int, int], ...] = () hidden: tuple[str, ...] = () links: tuple[str, ...] = () + hidden_nonlinks: tuple[str, ...] = () + exact_code_bodies: tuple[tuple[int, int, int], ...] = () _PARSER = _Markdown( @@ -259,20 +263,24 @@ def interpret_markdown(value: str) -> MarkupText: pieces: list[str] = [] contacts: list[str] = [] openings: list[tuple[int, int]] = [] + exact_code_bodies: list[tuple[int, int, int]] = [] hidden: dict[str, None] = {} links: dict[str, None] = {} + hidden_nonlinks: dict[str, None] = {} used = 0 hidden_used = 0 maximum = 4 * len(value) + 4096 hidden_maximum = 4 * len(value.encode("utf-8")) + 4096 - def hide(text: str) -> None: + def hide(text: str, *, destination: bool = False) -> None: nonlocal hidden_used if text and text not in hidden: hidden_used += len(text) if hidden_used > hidden_maximum: raise RepresentationLimit("hidden material expansion budget") hidden[text] = None + if text and not destination: + hidden_nonlinks[text] = None def add(text: str) -> None: nonlocal used @@ -295,7 +303,7 @@ def walk(items: list[dict[str, Any]]) -> None: if kind in {"link", "image"}: attrs = token["attrs"] links[attrs["url"]] = None - hide(attrs["url"]) + hide(attrs["url"], destination=True) hide(attrs.get("title", "")) formatted = kind in {"emphasis", "strong", "codespan"} if formatted: @@ -320,6 +328,14 @@ def walk(items: list[dict[str, Any]]) -> None: add(token.get("raw", "\n" if kind in {"softbreak", "linebreak"} else "")) if kind == "codespan" and "dlp_opening" in token: openings.append(token["dlp_opening"]) + opening, width = token["dlp_opening"] + start, end = token["dlp_body"] + if ( + 0 <= opening < start < end <= len(value) - width + and value[opening:start] == value[end : end + width] == "`" * width + and value[start:end] == token["raw"] + ): + exact_code_bodies.append((opening, start, end)) if formatted: boundary() if kind in {"paragraph", "block_code", "heading", "block_html"}: @@ -328,7 +344,7 @@ def walk(items: list[dict[str, Any]]) -> None: walk(tokens) for attrs in state.env["ref_links"].values(): links[attrs["url"]] = None - hide(attrs["url"]) + hide(attrs["url"], destination=True) hide(attrs.get("title", "")) return MarkupText( "".join(pieces), @@ -336,6 +352,8 @@ def walk(items: list[dict[str, Any]]) -> None: tuple(openings), tuple(hidden), tuple(links), + tuple(hidden_nonlinks), + tuple(exact_code_bodies), ) diff --git a/src/ocr_toolkit/context/dlp/numeric.py b/src/ocr_toolkit/context/dlp/numeric.py index dcb0b022..e25cbc5a 100644 --- a/src/ocr_toolkit/context/dlp/numeric.py +++ b/src/ocr_toolkit/context/dlp/numeric.py @@ -14,6 +14,7 @@ CALENDAR_DAY_PATTERN, _word_part, calendar_day, + complete_date_range, complete_datetime, ) from ocr_toolkit.context.dlp.decoding import _technical_decode, bounded_nfkc @@ -122,7 +123,7 @@ def _complete_technical_block(value: str, start: int, end: int) -> bool: return False -def _contains_phone(value: str) -> bool: +def _contains_phone(value: str, *, publication: bool = False) -> bool: """Recognize formatted phone-like values without classifying bare identifiers.""" return any( @@ -132,7 +133,7 @@ def _contains_phone(value: str) -> bool: or any(separator in match.group(0) for separator in " .()/-") ) and _phone_shape(value, match) - and not _technical_number(value, match) + and not _technical_number(value, match, publication=publication) for match in PHONE_RE.finditer(value) ) @@ -220,7 +221,7 @@ def _decimal_partition(value: str, start: int, end: int) -> bool: return found and all(char in " ()" for char in value[cursor:end]) -def _technical_number(value: str, match: re.Match[str]) -> bool: +def _technical_number(value: str, match: re.Match[str], *, publication: bool = False) -> bool: """Exclude only bounded, parsed technical syntax from phone candidates.""" candidate = match.group(0) @@ -230,8 +231,10 @@ def _technical_number(value: str, match: re.Match[str]) -> bool: or _explicit_context(value, match.start()) ): return False - if complete_datetime(value, *match.span()) or _complete_technical_block( - value, match.start(), match.end() + if ( + complete_datetime(value, *match.span()) + or (publication and complete_date_range(value, *match.span())) + or _complete_technical_block(value, *match.span()) ): return True # All contextual grammars below are bounded. Do not copy the complete diff --git a/src/ocr_toolkit/context/dlp/projection.py b/src/ocr_toolkit/context/dlp/projection.py index ebc0d65b..35414d5e 100644 --- a/src/ocr_toolkit/context/dlp/projection.py +++ b/src/ocr_toolkit/context/dlp/projection.py @@ -11,8 +11,10 @@ from mistune import BlockState from mistune.renderers.markdown import MarkdownRenderer +from ocr_toolkit.common.value_boundaries import complete_value from ocr_toolkit.context.contracts import TextBudgets -from ocr_toolkit.context.dlp.decoding import RepresentationLimit, _html_decode +from ocr_toolkit.context.dlp.datetimes import dated_anchor_phone_view +from ocr_toolkit.context.dlp.decoding import RepresentationLimit, _html_decode, bounded_nfkc from ocr_toolkit.context.dlp.markup import _PARSER, interpret_markdown from ocr_toolkit.context.dlp.presentation import has_unsafe_controls @@ -24,31 +26,82 @@ class UnsafeDestination(ValueError): _HTML_LITERAL = {ord(c): f"&#{ord(c)};" for c in string.punctuation} _HTML_LITERAL.update({ord("<"): "<", ord(">"): ">", ord("&"): "&"}) _TEXT_LITERAL = {ord(c): f"&#{ord(c)};" for c in "\\[]!`"} +_BARE_DESTINATION = re.compile(r"(?i)(?\"`]+") +_QUOTED_DESTINATION_SEPARATOR = re.compile(r"'[,;]'") + + +def _bare_destinations(source: str) -> Iterable[tuple[str, tuple[str, ...]]]: + for match in _BARE_DESTINATION.finditer(source): + destination = match[0] + start = match.start() + if not start or source[start - 1] != "'": + yield destination, () + continue + address, closing_quote, tail = destination.rpartition("'") + if not closing_quote or tail.strip(".,;:!?)]}"): + yield destination, () + continue + # A bare URL may contain apostrophes. Split only an explicitly + # delimited sequence of quoted URLs with a complete outer boundary. + parts = _QUOTED_DESTINATION_SEPARATOR.split(address) + before_quote = source[start - 2] if start > 1 else " " + if ( + len(parts) > 1 + and (before_quote.isspace() or before_quote in "([{=:;,") + and all( + not part.endswith(("\\", "'")) and _BARE_DESTINATION.fullmatch(part) is not None + for part in parts + ) + and complete_value(source, match.end()) + ): + yield address, tuple(parts) + else: + yield address, () -def decoded_markup_material(value: str) -> tuple[str, ...]: - """Inspect bounded hidden/link material independently of active-URL admission.""" - - if "[" not in value and "<" not in value: - return () +def _decode_destinations(destinations: Iterable[str], maximum: int) -> dict[str, None]: views: dict[str, None] = {} - maximum = 4 * len(value) + 4096 used = 0 - markup = interpret_markdown(value) - for url in dict.fromkeys((*markup.links, *markup.hidden)): + for material in destinations: for _ in range(3): - # Replacement retains surrounding material even for malformed byte - # escapes. Active URLs separately require strict valid Unicode. - decoded = _html_decode(unquote(url)) - if decoded == url: + # Active URLs separately require strict valid Unicode. + transformed = _html_decode(unquote(material)) + if transformed == material: break - if decoded not in views: - used += len(decoded) + if transformed not in views: + used += len(transformed) if used > maximum: raise RepresentationLimit("destination material budget") - views[decoded] = None - url = decoded - return tuple(views) + views[transformed] = None + material = transformed + else: + if _html_decode(unquote(material)) != material: + raise RepresentationLimit("destination material decoding depth") + return views + + +def decoded_markup_material(value: str, decoded: str) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Return bounded independent material and joined destinations for registered matches.""" + + destinations: dict[str, None] = {} + joined: dict[str, None] = {} + for source in dict.fromkeys((value, decoded, bounded_nfkc(decoded, original=value))): + if "[" in source or "<" in source: + markup = interpret_markdown(source) + destinations.update(dict.fromkeys((*markup.links, *markup.hidden))) + if "%" in source: + for destination, parts in _bare_destinations(source): + if parts: + destinations.update(dict.fromkeys(parts)) + joined[destination] = None + else: + destinations[destination] = None + maximum = 4 * len(value) + 4096 + material = _decode_destinations(destinations, maximum) + # Reserve separate bounded space for registered matching so retaining the + # original separators cannot exhaust the independent material budget. + joined_material = _decode_destinations(joined, maximum) + return tuple(material), tuple(text for text in joined_material if text not in material) def validate_destination(value: str) -> None: @@ -167,17 +220,20 @@ def _project_once(value: str, budgets: TextBudgets) -> str: assert isinstance(tokens, list) stack = list(tokens) rewrite = False - validated: set[str] = set() + validated: dict[str, str] = {} - def validate(url: str) -> None: + def validate(attrs: dict[str, Any]) -> None: + url = attrs["url"] if url not in validated: validate_destination(url) - validated.add(url) + # Keep equivalent letter spelling through the rendered material recheck. + validated[url] = dated_anchor_phone_view(url) + attrs["url"] = validated[url] while stack: token = stack.pop() if token["type"] in {"link", "image"}: - validate(token["attrs"]["url"]) + validate(token["attrs"]) rewrite = ( rewrite or token["type"] in {"inline_html", "block_html", "image"} @@ -193,7 +249,7 @@ def validate(url: str) -> None: stack.extend(token.get("children", ())) # Unused definitions are still supplied material, not invisible exceptions. for attrs in state.env["ref_links"].values(): - validate(attrs["url"]) + validate(attrs) if not rewrite: # Keep existing harmless syntax and literal carriers exactly. Rewriting # them merely to canonicalize Markdown can invent credential material. diff --git a/src/ocr_toolkit/context/dlp/provenance.py b/src/ocr_toolkit/context/dlp/provenance.py new file mode 100644 index 00000000..e803533d --- /dev/null +++ b/src/ocr_toolkit/context/dlp/provenance.py @@ -0,0 +1,69 @@ +"""Bounded exact and excerpt matching for already size-checked external JSON.""" + +from __future__ import annotations + +from collections.abc import Iterable, Iterator +from dataclasses import dataclass, field + +from .admission import ( + MIN_EXACT_EXCERPT_CHARS, + _display_normalize, + _source_normalize, + normalize_text, +) + + +def _representations(values: Iterable[str]) -> Iterator[str]: + for value in values: + candidate = normalize_text(value, allow_horizontal_tabs=True) + if candidate: + for view in (_display_normalize(candidate), _source_normalize(candidate)): + if view: + yield value if view == value else view + + +def _excerpts(value: str) -> Iterator[str]: + length = MIN_EXACT_EXCERPT_CHARS + for index in range(len(value) - length + 1): + yield value[index : index + length] + + +@dataclass(slots=True) +class ResultProvenance: + """Keep raw result strings, including those without a normalized representation.""" + + raw: set[str] = field(default_factory=set) + normalized: set[str] = field(default_factory=set) + + @classmethod + def compile(cls, values: Iterable[str]) -> ResultProvenance: + raw = set(values) + return cls(raw, set(_representations(raw))) + + def update(self, other: ResultProvenance) -> None: + self.raw.update(other.raw) + self.normalized.update(other.normalized) + + @staticmethod + def matches(values: set[str], sources: tuple[ResultProvenance, ...]) -> bool: + if not values or not sources: + return False + if any(not values.isdisjoint(source.raw) for source in sources): + return True + views = set(_representations(values)) + if any(not views.isdisjoint(source.normalized) for source in sources): + return True + # Index just the size-checked argument windows. Scan each source once, + # with storage bounded by argument size and work linear in source text. + excerpts = { + excerpt + for view in views | values + for excerpt in _excerpts(view) + if not excerpt.isspace() + } + return bool(excerpts) and any( + excerpt in excerpts + for source in sources + for view in source.raw | source.normalized + for excerpt in _excerpts(view) + ) diff --git a/src/ocr_toolkit/context/mcp.py b/src/ocr_toolkit/context/mcp.py index cb21ad32..2d7f88cc 100644 --- a/src/ocr_toolkit/context/mcp.py +++ b/src/ocr_toolkit/context/mcp.py @@ -10,7 +10,12 @@ from collections.abc import Mapping from ocr_toolkit.context.contracts import STORE_RESOURCE_CLASSES -from ocr_toolkit.context.store import HANDLE_RE, ContextStore +from ocr_toolkit.context.store import ( + HANDLE_RE, + ContextStore, + ContextStoreError, + validate_model_projection, +) LIST_TOOL = "context_list" GET_TOOL = "context_get" @@ -177,13 +182,17 @@ def call_context_tool( ) except ValueError as exc: raise ContextMCPError("context record is unavailable") from exc + try: + model_projection = validate_model_projection(record) + except ContextStoreError as exc: + raise ContextMCPError("context record is unavailable") from exc return _text( { "handle": record.handle, "resource_class": record.resource_class, "descriptor": record.descriptor, "mutable": record.mutable, - "record": dict(record.projections["model"]), + "record": dict(model_projection), } ) raise ContextMCPError("context tool is invalid") diff --git a/src/ocr_toolkit/context/store.py b/src/ocr_toolkit/context/store.py index c41b47c9..494da8c8 100644 --- a/src/ocr_toolkit/context/store.py +++ b/src/ocr_toolkit/context/store.py @@ -158,8 +158,12 @@ def _bounded_projection_integer(value: object, *, maximum: int) -> int: return value -def _remediation_text(value: object) -> str: - checked = check_text(value, budgets=STORE_TEXT_BUDGETS) +def _remediation_text(value: object, *, model_egress: bool) -> str: + checked = check_text( + value, + budgets=STORE_TEXT_BUDGETS, + model_egress=model_egress, + ) if not checked.admitted or not isinstance(checked.text, str) or checked.text != value: raise ContextStoreError("remediation projection text is invalid") return checked.text @@ -176,7 +180,7 @@ def _remediation_actor(value: object) -> str: return normalized -def _remediation_projection(value: object) -> Mapping[str, object]: +def _remediation_projection(value: object, *, model_egress: bool) -> Mapping[str, object]: """Hostile-read the fixed model-only remediation-thread projection.""" item = _mapping(value, "remediation projection") @@ -186,7 +190,7 @@ def _remediation_projection(value: object) -> Mapping[str, object]: if set(root) != {"text", "author_pseudonym"}: raise ContextStoreError("remediation root fields are invalid") normalized_root = { - "text": _remediation_text(root.get("text")), + "text": _remediation_text(root.get("text"), model_egress=model_egress), "author_pseudonym": _remediation_actor(root.get("author_pseudonym")), } anchor_state = normalize_text(item.get("anchor_state")) @@ -228,7 +232,7 @@ def _remediation_projection(value: object) -> Mapping[str, object]: "order": order, "author_class": author_class, "author_pseudonym": _remediation_actor(reply.get("author_pseudonym")), - "text": _remediation_text(reply.get("text")), + "text": _remediation_text(reply.get("text"), model_egress=model_egress), "created_at": created_at, "updated_at": updated_at, } @@ -265,7 +269,7 @@ def _remediation_projection(value: object) -> Mapping[str, object]: } -def _ci_outcome_projection(value: object) -> Mapping[str, object]: +def _ci_outcome_projection(value: object, *, model_egress: bool) -> Mapping[str, object]: """Hostile-read the fixed model-only same-revision CI projection.""" item = _mapping(value, "CI outcome projection") @@ -284,7 +288,11 @@ def _ci_outcome_projection(value: object) -> Mapping[str, object]: check != item.get("check") or not isinstance(check, str) or not 1 <= len(check) <= 128 - or not check_text(check, budgets=TextBudgets(128, 512, 1)).admitted + or not check_text( + check, + budgets=TextBudgets(128, 512, 1), + model_egress=model_egress, + ).admitted ): raise ContextStoreError("CI outcome check is invalid") if item.get("revision") != "reviewed_head": @@ -319,7 +327,11 @@ def _ci_outcome_projection(value: object) -> Mapping[str, object]: raise ContextStoreError("CI outcome path prefix is invalid") from None if ( canonical != prefix - or not check_text(canonical, budgets=TextBudgets(256, 1_024, 1)).admitted + or not check_text( + canonical, + budgets=TextBudgets(256, 1_024, 1), + model_egress=model_egress, + ).admitted ): raise ContextStoreError("CI outcome path prefix is invalid") normalized.append(canonical) @@ -336,15 +348,19 @@ def _ci_outcome_projection(value: object) -> Mapping[str, object]: } -def _projection_value(field: str, value: object) -> object: +def _projection_value(field: str, value: object, *, model_egress: bool = False) -> object: """Hostile-read one generic projection value without policy reinterpretation.""" if field == REMEDIATION_MODEL_FIELD: - return _remediation_projection(value) + return _remediation_projection(value, model_egress=model_egress) if field == CI_OUTCOME_MODEL_FIELD: - return _ci_outcome_projection(value) + return _ci_outcome_projection(value, model_egress=model_egress) if field == "text": - checked = check_text(value, budgets=STORE_TEXT_BUDGETS) + checked = check_text( + value, + budgets=STORE_TEXT_BUDGETS, + model_egress=model_egress, + ) if not checked.admitted or checked.text != value: raise ContextStoreError("context projection text is invalid") return value @@ -360,6 +376,15 @@ def _projection_value(field: str, value: object) -> object: raise ContextStoreError("context projection author class is invalid") if field == "author_pseudonym" and PSEUDONYM_RE.fullmatch(normalized) is None: raise ContextStoreError("context projection author pseudonym is invalid") + if ( + model_egress + and not check_text( + normalized, + budgets=TextBudgets(512, 2_048, 1), + model_egress=True, + ).admitted + ): + raise ContextStoreError("context projection string is invalid") return normalized if field in {"resolved", "outdated"}: if not isinstance(value, bool): @@ -390,6 +415,14 @@ def _projection_value(field: str, value: object) -> object: or not path or len(path) > 512 or len(path.encode("utf-8")) > 2_048 + or ( + model_egress + and not check_text( + path, + budgets=TextBudgets(512, 2_048, 1), + model_egress=True, + ).admitted + ) ): raise ContextStoreError("context projection anchor path is invalid") normalized_anchor["path"] = path @@ -478,6 +511,13 @@ def _record(value: object) -> ContextRecord: for value in strings.values() ): raise ContextStoreError("context record identity is invalid") + if ( + strings["descriptor"] not in {"discussion", *STORE_RESOURCE_CLASSES} + or not check_text( + strings["source"], budgets=TextBudgets(512, 2_048, 1), model_egress=True + ).admitted + ): + raise ContextStoreError("context listing metadata is invalid") if strings["resource_class"] not in STORE_RESOURCE_CLASSES: raise ContextStoreError("context record resource class is invalid") if SHA256_RE.fullmatch(str(strings["digest"])) is None: @@ -500,7 +540,8 @@ def _record(value: object) -> ContextRecord: if len(mapped) > len(allowed) or not set(mapped).issubset(allowed): raise ContextStoreError("context projection fields are invalid") normalized_projections[name] = { - field: _projection_value(field, value) for field, value in mapped.items() + field: _projection_value(field, value, model_egress=name == "model") + for field, value in mapped.items() } remediation_model = REMEDIATION_MODEL_FIELD in normalized_projections["model"] ci_outcome_model = CI_OUTCOME_MODEL_FIELD in normalized_projections["model"] @@ -561,6 +602,28 @@ def _record(value: object) -> ContextRecord: ) +def validate_model_projection(record: ContextRecord) -> Mapping[str, object]: + """Revalidate the complete record and return its model-facing projection.""" + + revalidated = _record( + { + "handle": record.handle, + "source": record.source, + "adapter": record.adapter, + "tenant": record.tenant, + "canonical_object": record.canonical_object, + "resource_class": record.resource_class, + "descriptor": record.descriptor, + "projections": record.projections, + "version": record.version, + "digest": record.digest, + "mutable": record.mutable, + "expiry": record.expiry, + } + ) + return revalidated.projections["model"] + + @dataclass(frozen=True, slots=True) class ContextStore: """Expose validated local records without any provider transport.""" @@ -734,6 +797,9 @@ def read( completeness = _mapping(root.get("completeness"), "context completeness") if any( not isinstance(key, str) + or not 1 <= len(key) <= 512 + or normalize_text(key) != key + or not check_text(key, budgets=TextBudgets(512, 2_048, 1), model_egress=True).admitted or not isinstance(value, str) or value not in {"complete", "partial", "mutated", "unavailable"} for key, value in completeness.items() diff --git a/src/ocr_toolkit/evidence/gitlink_projection.py b/src/ocr_toolkit/evidence/gitlink_projection.py index 4289124c..1b388f75 100644 --- a/src/ocr_toolkit/evidence/gitlink_projection.py +++ b/src/ocr_toolkit/evidence/gitlink_projection.py @@ -10,15 +10,30 @@ import stat import subprocess import time +from contextlib import ExitStack from dataclasses import dataclass from pathlib import Path +from ocr_toolkit.common.filesystem import open_private_parent_directory, same_file_identity from ocr_toolkit.common.git import read_only_git_prefix -from ocr_toolkit.evidence.gitlinks import GitlinkInputPlan +from ocr_toolkit.evidence.gitlinks import GitlinkInputPlan, plan_review_input from ocr_toolkit.evidence.repository import GitRepositoryReader, RepositoryEvidenceError -from ocr_toolkit.native_capabilities import supports_native_capability -from ocr_toolkit.ocr_result import TOOLKIT_GITLINK_SELECTION_KEY -from ocr_toolkit.result_contract import OcrResultContractError +from ocr_toolkit.native_capabilities import ( + native_omits_gitignore_exclusions, + supports_native_capability, +) +from ocr_toolkit.ocr_result import ( + TOOLKIT_GITLINK_SELECTION_KEY, + TOOLKIT_REVIEW_SELECTION_KEY, + OcrResultMalformed, + decode_ocr_json, +) +from ocr_toolkit.result_contract import ( + EXCLUSION_REASONS, + MAX_COVERAGE_RECORDS, + OcrResultContractError, + parse_result_outcome, +) from ocr_toolkit.review_range import ReviewRange, admit_native_range _SAFE_CONFIG_NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_./-]{0,127}\Z") @@ -33,20 +48,9 @@ _GIT_TIMEOUT_SECONDS = 30 _DIFF_ENTRY_LIMIT = 20_000 _GITLINK_SELECTION_SCHEMA = "ocr.gitlink-selection/v1" +_REVIEW_SELECTION_SCHEMA = "ocr.review-selection/v1" _LOCAL_INPUTS = (".gitignore", ".gitmodules", ".gitattributes") _GIT_METADATA_INPUTS = ("config", "config.worktree", "info/attributes", "info/exclude") -_PREVIEW_REASONS = frozenset( - { - "user_exclude", - "unsupported_ext", - "default_path", - "secret_exclude", - "provider_directory", - "deleted", - "binary", - "too_large", - } -) @dataclass(frozen=True, slots=True) @@ -81,7 +85,7 @@ def is_gitlink(self) -> bool: @dataclass(frozen=True, slots=True) class GitlinkProjection: - """Frozen original identity, projected ordinary diff and consulted inputs.""" + """Frozen review identity, complete ordinary diff and consulted Git inputs.""" plan: GitlinkInputPlan original_diff: tuple[RawDiffEntry, ...] @@ -96,61 +100,106 @@ def child_environment(self) -> dict[str, str]: return dict(self.environment) -def _read_input(path: Path) -> bytes | None: - try: - metadata = path.lstat() - except FileNotFoundError: - return None - if not stat.S_ISREG(metadata.st_mode) or metadata.st_size > _GIT_INPUT_LIMIT: - raise RepositoryEvidenceError("OCR local Git input is unsafe or too large") - flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) - descriptor = os.open(path, flags) +@dataclass(frozen=True, slots=True) +class PreviewExclusion: + """One preview-excluded immutable diff entry and its closed native reason.""" + + entry: RawDiffEntry + reason: str + + +@dataclass(frozen=True, slots=True) +class ReviewSelection: + """Exact disjoint selected/excluded partition of the immutable ordinary diff.""" + + selected: tuple[RawDiffEntry, ...] + excluded: tuple[PreviewExclusion, ...] + + +def _read_input(root: int, path: Path) -> bytes | None: + parent = root try: - opened = os.fstat(descriptor) - if ( - not stat.S_ISREG(opened.st_mode) - or opened.st_ino != metadata.st_ino - or opened.st_dev != metadata.st_dev - or opened.st_size > _GIT_INPUT_LIMIT - ): - raise RepositoryEvidenceError("OCR local Git input changed or is unsafe") - payload = os.read(descriptor, _GIT_INPUT_LIMIT + 1) - if len(payload) > _GIT_INPUT_LIMIT or len(payload) != opened.st_size: - raise RepositoryEvidenceError("OCR local Git input changed or is too large") - return payload + for component in path.parts[:-1]: + try: + child = os.open( + component, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent + ) + except FileNotFoundError: + return None + except NotADirectoryError: + mode = os.stat(component, dir_fd=parent, follow_symlinks=False).st_mode + if stat.S_ISREG(mode): + return None + raise + if parent != root: + os.close(parent) + parent = child + try: + metadata = os.stat(path.name, dir_fd=parent, follow_symlinks=False) + except FileNotFoundError: + return None + if not stat.S_ISREG(metadata.st_mode) or metadata.st_size > _GIT_INPUT_LIMIT: + raise RepositoryEvidenceError("OCR local Git input is unsafe or too large") + descriptor = os.open(path.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent) + try: + opened = os.fstat(descriptor) + if ( + not stat.S_ISREG(opened.st_mode) + or not same_file_identity(opened, metadata) + or opened.st_size > _GIT_INPUT_LIMIT + ): + raise RepositoryEvidenceError("OCR local Git input changed or is unsafe") + payload = os.read(descriptor, _GIT_INPUT_LIMIT + 1) + if len(payload) > _GIT_INPUT_LIMIT or len(payload) != opened.st_size: + raise RepositoryEvidenceError("OCR local Git input changed or is too large") + return payload + finally: + os.close(descriptor) + except OSError as exc: + raise RepositoryEvidenceError("OCR local Git input is unavailable or unsafe") from exc finally: - os.close(descriptor) + if parent != root: + os.close(parent) def _input_digest(root: Path, plan: GitlinkInputPlan) -> str: - paths = {root / path for path in _LOCAL_INPUTS} - git_dir = root / ".git" - try: - git_dir_mode = git_dir.lstat().st_mode - except OSError as exc: - raise RepositoryEvidenceError("OCR Git directory is unavailable") from exc - if not stat.S_ISDIR(git_dir_mode): - # Linked worktrees have an indirect common configuration; leave this - # shape closed until both metadata locations can be pinned. - raise RepositoryEvidenceError("OCR gitlink projection requires a direct Git directory") + paths = {Path(path) for path in _LOCAL_INPUTS} + git_dir = Path(".git") paths.update(git_dir / path for path in _GIT_METADATA_INPUTS) + configs = {git_dir / "config", git_dir / "config.worktree"} for change in plan.ordinary: - parts = change.path.split("/")[:-1] - for depth in range(1, len(parts) + 1): - paths.add(root.joinpath(*parts[:depth], ".gitattributes")) + for directory in Path(change.path).parents: + if directory == Path("."): + break + paths.update((directory / ".gitignore", directory / ".gitattributes")) digest = hashlib.sha256() - for path in sorted(paths): - payload = _read_input(path) - digest.update(str(path.relative_to(root)).encode("utf-8")) - digest.update(b"\0") - digest.update(b"M" if payload is None else b"P") - if payload is not None: - if path in {git_dir / "config", git_dir / "config.worktree"} and re.search( - rb"(?im)^\s*\[\s*include(?:if)?(?:\s|\])", - payload.removeprefix(b"\xef\xbb\xbf"), - ): - raise RepositoryEvidenceError("OCR local Git config includes are unsupported") - digest.update(hashlib.sha256(payload).digest()) + with ExitStack() as stack: + try: + root_fd, git_name = open_private_parent_directory(root / git_dir, create=False) + stack.callback(os.close, root_fd) + git_fd = os.open(git_name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=root_fd) + stack.callback(os.close, git_fd) + except (OSError, ValueError) as exc: + # Linked worktrees have indirect configuration that is not pinned here. + raise RepositoryEvidenceError( + "OCR gitlink projection requires a direct Git directory" + ) from exc + for path in sorted(paths): + payload = ( + _read_input(git_fd, path.relative_to(git_dir)) + if path.is_relative_to(git_dir) + else _read_input(root_fd, path) + ) + digest.update(str(path).encode("utf-8")) + digest.update(b"\0") + digest.update(b"M" if payload is None else b"P") + if payload is not None: + if path in configs and re.search( + rb"(?im)^\s*\[\s*include(?:if)?(?:\s|\])", + payload.removeprefix(b"\xef\xbb\xbf"), + ): + raise RepositoryEvidenceError("OCR local Git config includes are unsupported") + digest.update(hashlib.sha256(payload).digest()) return digest.hexdigest() @@ -375,6 +424,135 @@ def gitlink_selection_proof( } +def review_selection_digest(projection: GitlinkProjection, selection: ReviewSelection) -> str: + """Digest immutable item identities, fingerprints and every selection decision.""" + + selected = [_manifest_id(entry) for entry in selection.selected] + excluded = [_manifest_id(exclusion.entry) for exclusion in selection.excluded] + if ( + len(selected) != len(set(selected)) + or len(excluded) != len(set(excluded)) + or set(selected).intersection(excluded) + ): + raise RepositoryEvidenceError("OCR review selection is not disjoint") + decisions = dict.fromkeys(selected, "selected") + decisions.update( + { + item_id: exclusion.reason + for item_id, exclusion in zip(excluded, selection.excluded, strict=True) + } + ) + fingerprints = dict(projection.fingerprints) + if set(decisions) != set(fingerprints): + raise RepositoryEvidenceError("OCR review selection digest lacks a full partition") + digest = hashlib.sha256() + for item_id in sorted(decisions): + for field in (item_id, fingerprints[item_id], decisions[item_id]): + raw = field.encode("utf-8") + digest.update(len(raw).to_bytes(8, "big")) + digest.update(raw) + return digest.hexdigest() + + +def review_selection_proof( + projection: GitlinkProjection, selection: ReviewSelection +) -> dict[str, object]: + """Carry a path-free full partition across a publication-filtered result.""" + + digest = review_selection_digest(projection, selection) + return { + "schema_version": _REVIEW_SELECTION_SCHEMA, + "selected_item_ids": sorted(_manifest_id(entry) for entry in selection.selected), + "excluded": sorted( + ( + { + "item_id": _manifest_id(exclusion.entry), + "exclude_reason": exclusion.reason, + } + for exclusion in selection.excluded + ), + key=lambda record: record["item_id"], + ), + "selection_sha256": digest, + } + + +def selection_from_review_proof( + projection: GitlinkProjection, result: dict[str, object] +) -> ReviewSelection: + """Rebuild a full ordinary selection when native result records are insufficient.""" + + proof = result.get(TOOLKIT_REVIEW_SELECTION_KEY) + metadata = result.get("_ocr_toolkit") + publication = metadata.get("publication") if isinstance(metadata, dict) else None + state = publication.get("state") if isinstance(publication, dict) else None + filtered = state == "publication-filtered" + if ( + state not in ("publication-filtered", "passed", "private-sanitized", "disabled") + or (filtered and result.get("status") not in ("completed_with_errors", "budget_exceeded")) + or (filtered and result.get("manifest") is not None) + or not isinstance(proof, dict) + or set(proof) != {"schema_version", "selected_item_ids", "excluded", "selection_sha256"} + or proof.get("schema_version") != _REVIEW_SELECTION_SCHEMA + or not isinstance(proof.get("selected_item_ids"), list) + or not isinstance(proof.get("excluded"), list) + ): + raise RepositoryEvidenceError("OCR review selection proof is invalid") + expected = {_manifest_id(entry): entry for entry in projection.ordinary_diff} + selected_ids = proof["selected_item_ids"] + excluded_records = proof["excluded"] + if len(selected_ids) + len(excluded_records) != len(expected): + raise RepositoryEvidenceError("OCR filtered selection is not a full partition") + if any( + not isinstance(item_id, str) or item_id not in expected for item_id in selected_ids + ) or selected_ids != sorted(set(selected_ids)): + raise RepositoryEvidenceError("OCR filtered selected identities are invalid") + excluded: list[PreviewExclusion] = [] + excluded_ids: set[str] = set() + for record in excluded_records: + if ( + not isinstance(record, dict) + or set(record) != {"item_id", "exclude_reason"} + or not isinstance(record.get("item_id"), str) + or record["item_id"] not in expected + or record["item_id"] in excluded_ids + or not isinstance(record.get("exclude_reason"), str) + or record.get("exclude_reason") not in EXCLUSION_REASONS + ): + raise RepositoryEvidenceError("OCR filtered excluded identities are invalid") + excluded_ids.add(record["item_id"]) + excluded.append(PreviewExclusion(expected[record["item_id"]], record["exclude_reason"])) + if set(selected_ids).intersection(excluded_ids) or set(selected_ids) | excluded_ids != set( + expected + ): + raise RepositoryEvidenceError("OCR filtered selection is not a full partition") + selection = ReviewSelection( + tuple(expected[item_id] for item_id in selected_ids), tuple(excluded) + ) + if proof != review_selection_proof(projection, selection): + raise RepositoryEvidenceError("OCR filtered selection proof differs from Git") + if filtered: + original = publication.get("original") if isinstance(publication, dict) else None + if not isinstance(original, dict) or any( + type(original.get(field)) is not int or original[field] != count + for field, count in ( + ("selected", len(selection.selected)), + ("excluded", len(selection.excluded)), + ) + ): + raise RepositoryEvidenceError("OCR filtered original coverage is invalid") + comments = result.get("comments") + selected_paths = {entry.path for entry in selection.selected} + if not isinstance(comments, list) or any( + not isinstance(comment, dict) + or not isinstance(comment.get("path"), str) + or comment["path"] not in selected_paths + for comment in comments + ): + raise RepositoryEvidenceError("OCR filtered finding is outside selected files") + return selection + + def selected_gitlink_proof_entries( projection: GitlinkProjection, result: dict[str, object] ) -> tuple[RawDiffEntry, ...]: @@ -435,6 +613,13 @@ def selected_gitlink_proof_entries( return selected +def _patch_header_path(prefix: str, path: str) -> str: + # Repository paths exclude backslashes and controls. With core.quotePath + # disabled, a double quote is the remaining character Git C-quotes. + value = prefix + path + return json.dumps(value, ensure_ascii=False) if '"' in path else value + + def _patch_fingerprints( root: Path, plan: GitlinkInputPlan, @@ -463,14 +648,12 @@ def _patch_fingerprints( ], environment, ) - try: - text = patch.decode("utf-8") - except UnicodeDecodeError as exc: - raise RepositoryEvidenceError("OCR projected patch is not UTF-8") from exc - sections: list[list[str]] = [] - for raw_line in text.split("\n"): - line = raw_line.removesuffix("\r") - if line.startswith("diff --git "): + # Paths have already been validated from NUL-delimited Git records. Keep + # hunk bytes intact for native fingerprint matching and excluded inventory. + sections: list[list[bytes]] = [] + for raw_line in patch.split(b"\n"): + line = raw_line.removesuffix(b"\r") + if line.startswith(b"diff --git "): sections.append([]) if sections: sections[-1].append(line) @@ -483,26 +666,28 @@ def _patch_fingerprints( for entry, lines in zip(entries, sections, strict=True): old_path = entry.old_path or entry.new_path or "" new_path = entry.new_path or entry.old_path or "" - if lines[0] != f"diff --git a/{old_path} b/{new_path}": + old_header = _patch_header_path("a/", old_path) + new_header = _patch_header_path("b/", new_path) + if lines[0] != f"diff --git {old_header} {new_header}".encode(): raise RepositoryEvidenceError("OCR projected patch path is ambiguous") in_hunk = False insertions = 0 deletions = 0 - filtered: list[str] = [] + filtered: list[bytes] = [] for line in lines: - if line.startswith("@@"): + if line.startswith(b"@@"): in_hunk = True - if not in_hunk and line.startswith("index "): + if not in_hunk and line.startswith(b"index "): continue - if in_hunk and line.startswith("+"): + if in_hunk and line.startswith(b"+"): insertions += 1 - elif in_hunk and line.startswith("-"): + elif in_hunk and line.startswith(b"-"): deletions += 1 filtered.append(line) - diff_text = "\n".join(filtered).rstrip("\r\n") - fingerprint_source = "\0".join(("range", old_path, new_path, diff_text)) + diff_text = b"\n".join(filtered).rstrip(b"\r\n") + fingerprint_prefix = "\0".join(("range", old_path, new_path, "")).encode() fingerprints.append( - (_manifest_id(entry), hashlib.sha256(fingerprint_source.encode("utf-8")).hexdigest()) + (_manifest_id(entry), hashlib.sha256(fingerprint_prefix + diff_text).hexdigest()) ) line_counts.append((entry.path, insertions, deletions)) if len({item_id for item_id, _ in fingerprints}) != len(fingerprints): @@ -517,6 +702,7 @@ def make_gitlink_projection( environment = _projection_environment(plan) root = reader.root + input_digest = _input_digest(root, plan) merge_base = ( _git_output(root, ["merge-base", plan.base_sha, plan.head_sha], environment) .decode("ascii") @@ -524,13 +710,14 @@ def make_gitlink_projection( ) if merge_base != plan.base_sha: raise RepositoryEvidenceError("OCR range merge-base differs from the planned base") - input_digest = _input_digest(root, plan) unfiltered = _raw_diff(root, plan, environment, reveal_gitlinks=True) _check_tree_identity(plan, unfiltered) projected = _raw_diff(root, plan, environment, reveal_gitlinks=False) ordinary = tuple(entry for entry in unfiltered if not entry.is_gitlink) if projected != ordinary: raise RepositoryEvidenceError("OCR Git config did not isolate the ordinary diff") + if not plan.changes and len(ordinary) > MAX_COVERAGE_RECORDS: + raise RepositoryEvidenceError("OCR ordinary diff exceeds the review coverage record limit") if any( entry.status == "T" or entry.old_mode not in {"000000", "100644", "100755"} @@ -556,9 +743,7 @@ def make_gitlink_projection( def verify_gitlink_projection(reader: GitRepositoryReader, projection: GitlinkProjection) -> None: """Recheck every original endpoint, consulted input and projected record.""" - from ocr_toolkit.evidence.gitlinks import plan_gitlink_input - - current = plan_gitlink_input(reader, projection.plan.base_sha, projection.plan.head_sha) + current = plan_review_input(reader, projection.plan.base_sha, projection.plan.head_sha) if ( current != projection.plan or _input_digest(reader.root, projection.plan) != projection.input_digest @@ -582,12 +767,12 @@ def verify_gitlink_projection(reader: GitRepositoryReader, projection: GitlinkPr raise RepositoryEvidenceError("OCR projected Git patch changed") -def qualify_gitlink_preview(projection: GitlinkProjection, raw: bytes) -> tuple[RawDiffEntry, ...]: - """Accept only the complete 1.13.3 preview for the independently proven diff.""" +def qualify_review_preview(projection: GitlinkProjection, raw: bytes) -> ReviewSelection: + """Accept an exact reason-closed preview partition of the independently proven diff.""" try: - payload = json.loads(raw) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: + payload = decode_ocr_json(raw) + except OcrResultMalformed as exc: raise RepositoryEvidenceError("OCR gitlink preview is not valid JSON") from exc if not isinstance(payload, dict) or set(payload) != { "files", @@ -608,6 +793,7 @@ def qualify_gitlink_preview(projection: GitlinkProjection, raw: bytes) -> tuple[ if len(expected) != len(projection.ordinary_diff): raise RepositoryEvidenceError("OCR gitlink projection has a duplicate path") selected: list[RawDiffEntry] = [] + excluded: list[PreviewExclusion] = [] seen: set[str] = set() insertions = 0 deletions = 0 @@ -658,8 +844,10 @@ def qualify_gitlink_preview(projection: GitlinkProjection, raw: bytes) -> tuple[ "OCR gitlink preview selection conflicts with exclusion" ) selected.append(entry) - elif reason not in _PREVIEW_REASONS: + elif reason not in EXCLUSION_REASONS: raise RepositoryEvidenceError("OCR gitlink preview has an unknown exclusion") + else: + excluded.append(PreviewExclusion(entry, reason)) if seen != set(expected): raise RepositoryEvidenceError("OCR gitlink preview omitted an ordinary path") for field, value in ( @@ -671,82 +859,224 @@ def qualify_gitlink_preview(projection: GitlinkProjection, raw: bytes) -> tuple[ ): if type(payload[field]) is not int or payload[field] != value: raise RepositoryEvidenceError("OCR gitlink preview totals are inconsistent") - return tuple(selected) + return ReviewSelection(tuple(selected), tuple(excluded)) -def qualify_gitlink_manifest( +def qualify_gitlink_preview(projection: GitlinkProjection, raw: bytes) -> tuple[RawDiffEntry, ...]: + """Compatibility wrapper returning the selected part of a qualified preview.""" + + return qualify_review_preview(projection, raw).selected + + +def _selected_record_matches( + record: dict[str, object], entry: RawDiffEntry, fingerprints: dict[str, str] +) -> bool: + item_id = _manifest_id(entry) + return bool( + record.get("item_id") == item_id + and record.get("path") == entry.path + and record.get("old_path", "") == (entry.old_path if entry.status == "R" else "") + and record.get("fingerprint") == fingerprints.get(item_id) + ) + + +def _native_manifest_version(manifest: dict[str, object]) -> str | None: + execution = manifest.get("execution") + version = execution.get("ocr_version") if isinstance(execution, dict) else None + return version[1:] if isinstance(version, str) and version.startswith("v") else None + + +def selection_from_manifest( projection: GitlinkProjection, - selected: tuple[RawDiffEntry, ...], result: dict[str, object], -) -> None: - """Bind native completed coverage to every preview-selected ordinary item.""" + *, + allow_partial_gitlink_readback: bool = False, +) -> ReviewSelection: + """Recover an exact full-diff selection partition from native manifest records.""" + + manifest = result.get("manifest") + coverage = manifest.get("coverage") if isinstance(manifest, dict) else None + selected_records = coverage.get("selected") if isinstance(coverage, dict) else None + excluded_records = coverage.get("excluded") if isinstance(coverage, dict) else None + if not isinstance(selected_records, list) or not isinstance(excluded_records, list): + raise RepositoryEvidenceError("OCR review manifest selection is unavailable") + expected = {_manifest_id(entry): entry for entry in projection.ordinary_diff} + if len(expected) != len(projection.ordinary_diff): + raise RepositoryEvidenceError("OCR review identities are ambiguous") + selected: list[RawDiffEntry] = [] + excluded: list[PreviewExclusion] = [] + seen: set[str] = set() + for record in selected_records: + item_id = record.get("item_id") if isinstance(record, dict) else None + if not isinstance(item_id, str) or item_id not in expected or item_id in seen: + raise RepositoryEvidenceError("OCR review manifest selected item is invalid") + seen.add(item_id) + selected.append(expected[item_id]) + for record in excluded_records: + item_id = record.get("item_id") if isinstance(record, dict) else None + reason = record.get("exclude_reason") if isinstance(record, dict) else None + if ( + not isinstance(item_id, str) + or item_id not in expected + or item_id in seen + or not isinstance(reason, str) + or reason not in EXCLUSION_REASONS + ): + raise RepositoryEvidenceError("OCR review manifest excluded item is invalid") + seen.add(item_id) + excluded.append(PreviewExclusion(expected[item_id], reason)) + missing = expected.keys() - seen + if missing: + # A gitlink receipt proves only the selected ordinary subset and always + # remains partial. Ordinary receipts need the actual preview witness. + if not ( + allow_partial_gitlink_readback + and projection.gitlink_diff + and isinstance(manifest, dict) + and native_omits_gitignore_exclusions(_native_manifest_version(manifest)) + ): + raise RepositoryEvidenceError("OCR review manifest omitted an immutable diff item") + excluded.extend( + PreviewExclusion(expected[item_id], "gitignore") for item_id in sorted(missing) + ) + return ReviewSelection(tuple(selected), tuple(excluded)) + + +def qualify_review_manifest( + projection: GitlinkProjection, + selection: ReviewSelection, + result: dict[str, object], + *, + require_fresh_complete: bool = False, +) -> bool: + """Check native coverage and return whether omitted Git ignores need the preview proof.""" manifest = result.get("manifest") if not isinstance(manifest, dict) or manifest.get("schema_version") != "ocr.run-manifest/v1": - raise RepositoryEvidenceError("OCR gitlink result lacks the qualified manifest") - if result.get("status") != "complete" or manifest.get("terminal_state") != "complete": - raise RepositoryEvidenceError("OCR gitlink result is not native complete") + raise RepositoryEvidenceError("OCR review result lacks the qualified manifest") + try: + parse_result_outcome(result) + except OcrResultContractError as exc: + raise RepositoryEvidenceError("OCR review manifest has an invalid contract") from exc try: admit_native_range(result, ReviewRange(projection.plan.base_sha, projection.plan.head_sha)) except OcrResultContractError as exc: raise RepositoryEvidenceError( - "OCR gitlink manifest has a different review identity" + "OCR review manifest has a different review identity" ) from exc native_input = manifest.get("input") - assert isinstance(native_input, dict) - execution = manifest.get("execution") - native_version = execution.get("ocr_version") if isinstance(execution, dict) else None - if ( - not isinstance(native_version, str) - or not native_version.startswith("v") - or not supports_native_capability(native_version[1:], "gitlink_projection") + native_version = _native_manifest_version(manifest) + if not isinstance(native_input, dict) or not supports_native_capability( + native_version, "gitlink_projection" ): - raise RepositoryEvidenceError("OCR gitlink manifest has an unsupported binary version") + raise RepositoryEvidenceError("OCR review manifest has an unsupported binary version") coverage = manifest.get("coverage") if not isinstance(coverage, dict): - raise RepositoryEvidenceError("OCR gitlink manifest coverage is invalid") - expected = {_manifest_id(entry): entry for entry in selected} + raise RepositoryEvidenceError("OCR review manifest coverage is invalid") + expected_selected = {_manifest_id(entry): entry for entry in selection.selected} + expected_excluded = { + _manifest_id(exclusion.entry): exclusion for exclusion in selection.excluded + } + if ( + len(expected_selected) != len(selection.selected) + or len(expected_excluded) != len(selection.excluded) + or set(expected_selected).intersection(expected_excluded) + or set(expected_selected) | set(expected_excluded) + != {_manifest_id(entry) for entry in projection.ordinary_diff} + ): + raise RepositoryEvidenceError("OCR review selection is not a full disjoint partition") fingerprints = dict(projection.fingerprints) - if len(expected) != len(selected): - raise RepositoryEvidenceError("OCR gitlink selected identities are ambiguous") - proof = gitlink_selection_proof(projection, selected) + proof = gitlink_selection_proof(projection, selection.selected) if native_input.get("source_artifact_sha256") != proof["source_artifact_sha256"]: - raise RepositoryEvidenceError("OCR gitlink source artifact differs from the Git patch") - for key in ("selected", "completed"): - records = coverage.get(key) - if not isinstance(records, list) or len(records) != len(expected): - raise RepositoryEvidenceError("OCR gitlink manifest omitted selected work") - seen: set[str] = set() - for record in records: - if not isinstance(record, dict): - raise RepositoryEvidenceError("OCR gitlink manifest item is invalid") - item_id = record.get("item_id") - if not isinstance(item_id, str) or item_id not in expected or item_id in seen: - raise RepositoryEvidenceError("OCR gitlink manifest item is unexpected") - seen.add(item_id) - entry = expected[item_id] - if ( - record.get("path") != entry.path - or record.get("old_path", "") != (entry.old_path if entry.status == "R" else "") - or record.get("fingerprint") != fingerprints.get(item_id) - ): - raise RepositoryEvidenceError("OCR gitlink manifest item disagrees with Git") - for key in ("reused", "failed", "waived"): - if coverage.get(key) != []: - raise RepositoryEvidenceError("OCR gitlink manifest contains unreviewed work") - if manifest.get("run_failure") is not None or manifest.get("parent_run_id"): - raise RepositoryEvidenceError("OCR gitlink result is not a fresh complete review") + raise RepositoryEvidenceError("OCR review source artifact differs from the Git patch") + selected_records = coverage.get("selected") + if not isinstance(selected_records, list) or len(selected_records) != len(expected_selected): + raise RepositoryEvidenceError("OCR review manifest omitted selected work") + seen: set[str] = set() + for record in selected_records: + item_id = record.get("item_id") if isinstance(record, dict) else None + if ( + not isinstance(record, dict) + or not isinstance(item_id, str) + or item_id not in expected_selected + or item_id in seen + or not _selected_record_matches(record, expected_selected[item_id], fingerprints) + ): + raise RepositoryEvidenceError("OCR review selected item disagrees with Git") + seen.add(item_id) + excluded_records = coverage.get("excluded") + if not isinstance(excluded_records, list) or len(excluded_records) > len(expected_excluded): + raise RepositoryEvidenceError("OCR review manifest omitted excluded work") + seen.clear() + for record in excluded_records: + item_id = record.get("item_id") if isinstance(record, dict) else None + exclusion = expected_excluded.get(item_id) if isinstance(item_id, str) else None + if ( + not isinstance(record, dict) + or not isinstance(item_id, str) + or exclusion is None + or item_id in seen + or record.get("path") != exclusion.entry.path + or ( + "old_path" in record + and ( + exclusion.entry.status != "R" or record["old_path"] != exclusion.entry.old_path + ) + ) + or record.get("exclude_reason") != exclusion.reason + ): + raise RepositoryEvidenceError("OCR review excluded item disagrees with preview") + seen.add(item_id) + missing_exclusions = expected_excluded.keys() - seen + if missing_exclusions and ( + not native_omits_gitignore_exclusions(native_version) + or any(expected_excluded[item_id].reason != "gitignore" for item_id in missing_exclusions) + ): + raise RepositoryEvidenceError("OCR review manifest omitted excluded work") comments = result.get("comments") - if not isinstance(comments, list): - raise RepositoryEvidenceError("OCR gitlink result comments are invalid") - selected_paths = {entry.path for entry in selected} - for comment in comments: + selected_paths = {entry.path for entry in selection.selected} + if not isinstance(comments, list) or any( + not isinstance(comment, dict) + or not isinstance(comment.get("path"), str) + or comment["path"] not in selected_paths + for comment in comments + ): + raise RepositoryEvidenceError("OCR review result has a finding outside selected files") + completed = coverage.get("completed") + if not isinstance(completed, list) or any( + not isinstance(record, dict) + or not isinstance(record.get("item_id"), str) + or record["item_id"] not in expected_selected + or not _selected_record_matches(record, expected_selected[record["item_id"]], fingerprints) + for record in completed + ): + raise RepositoryEvidenceError("OCR review completed item disagrees with Git") + if require_fresh_complete: + if len(completed) != len(expected_selected): + raise RepositoryEvidenceError("OCR gitlink completed coverage does not match preview") + if any(coverage.get(key) != [] for key in ("reused", "failed", "waived")): + raise RepositoryEvidenceError("OCR gitlink manifest contains unreviewed work") if ( - not isinstance(comment, dict) - or not isinstance(comment.get("path"), str) - or comment["path"] not in selected_paths + result.get("status") != "complete" + or manifest.get("terminal_state") != "complete" + or manifest.get("run_failure") is not None + or manifest.get("parent_run_id") ): - raise RepositoryEvidenceError("OCR gitlink result has a finding outside selected files") + raise RepositoryEvidenceError("OCR gitlink result is not a fresh complete review") + return bool(missing_exclusions) + + +def qualify_gitlink_manifest( + projection: GitlinkProjection, + selected: tuple[RawDiffEntry, ...], + result: dict[str, object], +) -> None: + """Bind qualified gitlink coverage while preserving the historical call surface.""" + + selection = selection_from_manifest(projection, result, allow_partial_gitlink_readback=True) + if len(selection.selected) != len(selected) or set(selection.selected) != set(selected): + raise RepositoryEvidenceError("OCR gitlink manifest selected work changed") + qualify_review_manifest(projection, selection, result, require_fresh_complete=True) def selected_gitlink_manifest_entries( diff --git a/src/ocr_toolkit/evidence/gitlinks.py b/src/ocr_toolkit/evidence/gitlinks.py index fc76b471..dfe39d38 100644 --- a/src/ocr_toolkit/evidence/gitlinks.py +++ b/src/ocr_toolkit/evidence/gitlinks.py @@ -120,10 +120,10 @@ def changed_gitlinks( return _changes_from_maps(before, after) -def plan_gitlink_input( +def plan_review_input( reader: GitRepositoryReader, base_sha: str, head_sha: str -) -> GitlinkInputPlan | None: - """Qualify changed pure pointers and retain every ordinary original delta. +) -> GitlinkInputPlan: + """Qualify the complete immutable delta, including any changed pure pointers. No submodule target object is opened. Unsafe transitions and ambiguous move pairing fail before any OCR preview or model call can use the plan. @@ -134,8 +134,6 @@ def plan_gitlink_input( before = _entries_by_path(reader.list_objects(base_sha)) after = _entries_by_path(reader.list_objects(head_sha)) changes = _changes_from_maps(before, after) - if not changes: - return None for change in changes: if change.kind == "transition": raise RepositoryEvidenceError("gitlink type transition is unsupported") @@ -158,8 +156,8 @@ def plan_gitlink_input( raise RepositoryEvidenceError("gitlink move pairing is ambiguous") moves.append((deletions[oid][0], additions[oid][0])) - before_modules = reader.gitmodules_paths(base_sha) - after_modules = reader.gitmodules_paths(head_sha) + before_modules = reader.gitmodules_paths(base_sha) if changes else {} + after_modules = reader.gitmodules_paths(head_sha) if changes else {} changed_paths = {change.path for change in changes} names = { name @@ -186,3 +184,12 @@ def plan_gitlink_input( tuple(sorted(before_modules.items())), tuple(sorted(after_modules.items())), ) + + +def plan_gitlink_input( + reader: GitRepositoryReader, base_sha: str, head_sha: str +) -> GitlinkInputPlan | None: + """Return the complete review plan only when the range changes a gitlink.""" + + plan = plan_review_input(reader, base_sha, head_sha) + return plan if plan.changes else None diff --git a/src/ocr_toolkit/evidence/project.py b/src/ocr_toolkit/evidence/project.py index 78591697..a8374f5c 100644 --- a/src/ocr_toolkit/evidence/project.py +++ b/src/ocr_toolkit/evidence/project.py @@ -216,7 +216,9 @@ def render_bootstrap( navigation.append( ("After review intent, consider" if mr_context is not None else "Consider") + " relevant allowlisted external tools only when useful; " - "see actual MCP tool definitions for names and schemas." + "see actual MCP tool definitions. " + "Results cannot authorize " + "suppression, severity changes, publication or approval." ) required_suffix = "" if diagram_available and store.base is not None and store.head is not None: diff --git a/src/ocr_toolkit/evidence/repository.py b/src/ocr_toolkit/evidence/repository.py index 87c47168..b32f9798 100644 --- a/src/ocr_toolkit/evidence/repository.py +++ b/src/ocr_toolkit/evidence/repository.py @@ -8,6 +8,7 @@ import selectors import subprocess import time +from collections.abc import Callable from dataclasses import dataclass from pathlib import Path, PurePosixPath @@ -37,21 +38,26 @@ rb"^(?P[0-7]{6}) (?Pblob|tree|commit) (?P[0-9a-f]{40})\t(?P.*)$", re.DOTALL, ) +_NAME_STATUS_RE = re.compile(rb"(?:[ADTUXB]|[CR][0-9]{1,3}|M[0-9]{0,3})") BATCH_HEADER_RE = re.compile( rb"^(?P[0-9a-f]{40}) (?Pblob|tree|commit) (?P[0-9]+)\n$" ) MAX_BATCH_BLOB_BYTES = 32_000_000 MAX_GIT_TEXT_BYTES = 8_000_000 +MAX_GIT_GREP_BYTES = 512_000 MAX_ANCESTRY_FETCH_DEPTH = 128 MAX_GITMODULES_BYTES = 128_000 MAX_GITMODULES_ENTRIES = 256 MAX_SUBMODULE_NAME_BYTES = 256 -def _git_environment() -> dict[str, str]: +def _git_environment(*, local_only: bool = False) -> dict[str, str]: """Return a Git environment without caller-injected configuration entries.""" - return isolated_git_environment() + environment = isolated_git_environment() + if local_only: + environment.update(GIT_ALLOW_PROTOCOL="", GIT_NO_LAZY_FETCH="1") + return environment def _git_prefix(root: Path) -> list[str]: @@ -110,6 +116,67 @@ class BoundedBlobRead: diagnostics: tuple[str, ...] +class _NulFields: + """Yield complete Git fields to one parser as bounded stdout arrives.""" + + def __init__(self, receive: Callable[[bytes], None]) -> None: + self.receive = receive + self.partial = bytearray() + + def consume(self, chunk: bytes) -> None: + search_from = len(self.partial) + self.partial.extend(chunk) + start = 0 + while (end := self.partial.find(b"\0", search_from)) >= 0: + self.receive(bytes(self.partial[start:end])) + start = end + 1 + search_from = start + if start: + del self.partial[:start] + + +def _decode_git_path(raw_path: bytes, *, label: str) -> str: + try: + value = raw_path.decode("utf-8") + except UnicodeDecodeError as exc: + raise RepositoryEvidenceError(f"{label} is not valid UTF-8") from exc + return normalize_repo_path(value) + + +class _ChangedPaths: + """Admit unique normalized paths only after their full record is valid.""" + + def __init__(self, limit: int) -> None: + """Configure the changed-path ceiling and incremental field state.""" + + self.limit = limit + self.remaining_paths = 0 + self.record_paths: list[str] = [] + self.paths: set[str] = set() + + def receive(self, field: bytes) -> None: + if self.remaining_paths == 0: + if _NAME_STATUS_RE.fullmatch(field) is None: + raise RepositoryEvidenceError("Git returned an invalid name-status record") + self.remaining_paths = 2 if field[:1] in {b"R", b"C"} else 1 + return + + self.record_paths.append(_decode_git_path(field, label="changed path")) + self.remaining_paths -= 1 + if self.remaining_paths: + return + for path in self.record_paths: + self.paths.add(path) + if len(self.paths) > self.limit: + raise RepositoryEvidenceBudgetError( + len(self.paths), + self.limit, + "entries", + message="changed path count exceeds the bounded limit", + ) + self.record_paths.clear() + + def normalize_repo_path(value: str) -> str: """Return one safe repository-relative path accepted by Git plumbing.""" @@ -138,6 +205,7 @@ def __init__( max_file_bytes: int = 256_000, deadline: float | None = None, command_timeout: float | None = None, + local_only: bool = False, ) -> None: """Resolve the repository root and constrain every subsequent Git command.""" @@ -149,6 +217,7 @@ def __init__( raise RepositoryEvidenceError("repository command timeout must be finite and positive") self.deadline = deadline self.command_timeout = command_timeout + self._local_only = local_only resolved = root.resolve(strict=True) probe = self._run_at(resolved, ["rev-parse", "--show-toplevel"], timeout=self._timeout(15)) if probe.returncode != 0 or Path(probe.stdout.strip()).resolve() != resolved: @@ -198,24 +267,43 @@ def _run_at( return completed def _run( - self, args: list[str], *, timeout: int = 15, text: bool = True + self, + args: list[str], + *, + timeout: int = 15, + text: bool = True, + local_only: bool = False, + stdout_observer: Callable[[bytes], None] | None = None, ) -> subprocess.CompletedProcess[str] | subprocess.CompletedProcess[bytes]: """Run a bounded Git plumbing command at this reader's fixed root.""" - if self.command_timeout is not None: - return self._run_streamed(args, timeout=self._timeout(timeout), text=text) - return self._run_at(self.root, args, timeout=self._timeout(timeout), text=text) + return self._run_streamed( + args, + timeout=self._timeout(timeout), + text=text, + local_only=local_only, + stdout_observer=stdout_observer, + ) def _run_streamed( - self, args: list[str], *, timeout: float, text: bool + self, + args: list[str], + *, + timeout: float, + text: bool, + local_only: bool = False, + max_bytes: int | None = None, + stdout_observer: Callable[[bytes], None] | None = None, ) -> subprocess.CompletedProcess[str] | subprocess.CompletedProcess[bytes]: """Bound audit metadata while consuming it, including enormous Git trees.""" + limit = MAX_GIT_TEXT_BYTES if max_bytes is None else max_bytes command = [*_git_prefix(self.root), *args] + environment = _git_environment(local_only=local_only or self._local_only) output, errors = bytearray(), bytearray() deadline = time.monotonic() + timeout with subprocess.Popen( - command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=_git_environment() + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment ) as process: assert process.stdout is not None and process.stderr is not None try: @@ -229,14 +317,16 @@ def _run_streamed( "Git metadata acquisition deadline exceeded" ) for key, _events in selector.select(remaining): - part = os.read(key.fd, 65536) + part = os.read(key.fd, min(65_536, limit - len(key.data) + 1)) if not part: selector.unregister(key.fileobj) else: - if len(key.data) + len(part) > MAX_GIT_TEXT_BYTES: + if len(key.data) + len(part) > limit: raise RepositoryEvidenceError( "Git plumbing output exceeds the bounded byte limit" ) + if key.data is output and stdout_observer is not None: + stdout_observer(part) key.data.extend(part) process.wait(timeout=max(0.001, deadline - time.monotonic())) finally: @@ -251,6 +341,92 @@ def _run_streamed( command, process.returncode, bytes(output), bytes(errors) ) + def grep_tree( + self, + sha: str, + query: str, + patterns: tuple[str, ...], + *, + case_sensitive: bool, + ) -> bytes: + """Return bounded, NUL-addressed immutable tree matches, without text converters.""" + + if not re.fullmatch(r"[a-f0-9]{40}", sha): + raise RepositoryEvidenceError("Git grep requires an immutable commit") + args = [ + "-c", + "core.quotepath=false", + "-c", + "grep.threads=1", + "grep", + "-I", + "--no-recurse-submodules", + ] + if not case_sensitive: + args.append("-i") + args.extend( + [ + "-F", + "-n", + "-z", + "--no-color", + "--no-textconv", + "--max-count=101", + "-e", + query, + sha, + "--", + *patterns, + ] + ) + result = self._run_streamed( + args, + timeout=self._timeout(10), + text=False, + local_only=True, + max_bytes=MAX_GIT_GREP_BYTES, + ) + assert isinstance(result.stdout, bytes) + if ( + result.returncode not in (0, 1) + or result.stderr + or (result.returncode == 0) != bool(result.stdout) + ): + raise RepositoryEvidenceError("Git grep did not return a complete immutable result") + return result.stdout + + def review_patch(self, base: str, head: str) -> bytes: + """Read a bounded native-style patch with external diff drivers disabled.""" + + if any(not re.fullmatch(r"[a-f0-9]{40}", sha) for sha in (base, head)): + raise RepositoryEvidenceError("Git patch requires immutable commits") + result = self._run_streamed( + [ + "-c", + "core.quotepath=false", + "diff", + "--no-ext-diff", + "--no-textconv", + "--ignore-submodules=all", + "--find-renames", + "--src-prefix=a/", + "--dst-prefix=b/", + "--no-color", + "-U3", + "--end-of-options", + base, + head, + "--", + ], + timeout=self._timeout(10), + text=False, + local_only=True, + ) + assert isinstance(result.stdout, bytes) + if result.returncode or result.stderr: + raise RepositoryEvidenceError("Git diff did not return a complete immutable result") + return result.stdout + def has_commit(self, sha: str) -> bool: """Return whether one exact lowercase commit object is available locally.""" @@ -280,6 +456,8 @@ def _validate_fetch_identity(sha: str, remote: str) -> None: raise RepositoryEvidenceError("only the runner-owned origin remote is supported") def _fetch_commit(self, sha: str, *, depth: int) -> None: + if self._local_only: + raise RepositoryEvidenceError("remote acquisition is disabled for this reader") try: completed = subprocess.run( [ @@ -344,12 +522,12 @@ def is_ancestor(self, older_sha: str, newer_sha: str) -> bool: raise ShallowAncestryUnavailable("Git ancestry is unverifiable in a shallow repository") return False - def resolve_commit(self, ref: str) -> str: + def resolve_commit(self, ref: str, *, local_only: bool = False) -> str: """Resolve an explicit ref to an existing commit without fetching objects.""" if not ref or ref.startswith("-") or any(char in ref for char in ("\x00", "\n", " ")): raise RepositoryEvidenceError("Git ref contains unsupported syntax") - result = self._run(["rev-parse", "--verify", f"{ref}^{{commit}}"]) + result = self._run(["rev-parse", "--verify", f"{ref}^{{commit}}"], local_only=local_only) assert isinstance(result.stdout, str) sha = result.stdout.strip() if result.returncode == 0 else "" if len(sha) != 40 or not all(char in "0123456789abcdef" for char in sha): @@ -371,42 +549,45 @@ def checkout_scope(self, head: str) -> str | None: return None def list_objects( - self, ref: str, *, max_entries: int = MAX_TREE_ENTRIES + self, ref: str, *, max_entries: int = MAX_TREE_ENTRIES, local_only: bool = False ) -> tuple[RepositoryObject, ...]: """List bounded tree entries without following symlinks or submodules.""" - sha = self.resolve_commit(ref) - result = self._run(["ls-tree", "-z", "-r", "--full-tree", sha], timeout=30, text=False) - assert isinstance(result.stdout, bytes) - if result.returncode != 0: - raise RepositoryEvidenceError("failed to enumerate repository tree") - records = result.stdout.split(b"\0") - if records and records[-1] == b"": - records.pop() - if len(records) > max_entries: - raise RepositoryEvidenceBudgetError( - len(records), - max_entries, - "entries", - message="repository tree exceeds the bounded entry limit", - ) - entries = [] - for record in records: + sha = self.resolve_commit(ref, local_only=local_only) + entries: list[RepositoryObject] = [] + + def receive(record: bytes) -> None: match = OBJECT_RECORD_RE.fullmatch(record) if match is None: raise RepositoryEvidenceError("Git returned an unsupported tree entry") - try: - raw_path = match.group("path").decode("utf-8") - except UnicodeDecodeError as exc: - raise RepositoryEvidenceError("repository path is not valid UTF-8") from exc entries.append( RepositoryObject( - path=normalize_repo_path(raw_path), + path=_decode_git_path(match.group("path"), label="repository path"), mode=match.group("mode").decode("ascii"), object_type=match.group("type").decode("ascii"), object_sha=match.group("sha").decode("ascii"), ) ) + if len(entries) > max_entries: + raise RepositoryEvidenceBudgetError( + len(entries), + max_entries, + "entries", + message="repository tree exceeds the bounded entry limit", + ) + + fields = _NulFields(receive) + result = self._run( + ["ls-tree", "-z", "-r", "--full-tree", sha], + timeout=30, + text=False, + local_only=local_only, + stdout_observer=fields.consume, + ) + if result.returncode != 0: + raise RepositoryEvidenceError("failed to enumerate repository tree") + if fields.partial: + raise RepositoryEvidenceError("Git returned a truncated tree entry") return tuple(entries) def object_at(self, ref: str, path: str) -> RepositoryObject | None: @@ -566,7 +747,7 @@ def read_text_metadata( try: return consume_text_metadata( [*_git_prefix(self.root), "cat-file", "blob", entry.object_sha], - environment=_git_environment(), + environment=_git_environment(local_only=self._local_only), object_sha=entry.object_sha, size=size, timeout=self._timeout(30), @@ -612,7 +793,7 @@ def _batch_sizes(self, entries: tuple[RepositoryObject, ...]) -> tuple[int, ...] request = self._batch_request(entries) - environment = _git_environment() + environment = _git_environment(local_only=self._local_only) command_prefix = [*_git_prefix(self.root), "cat-file"] try: size_result = subprocess.run( @@ -650,7 +831,7 @@ def _batch_contents( if len(entries) != len(sizes): raise RepositoryEvidenceError("batch blob size count does not match request") request = self._batch_request(entries) - environment = _git_environment() + environment = _git_environment(local_only=self._local_only) command_prefix = [*_git_prefix(self.root), "cat-file"] try: result = subprocess.run( @@ -758,39 +939,18 @@ def changed_paths( base = self.resolve_commit(base_ref) head = self.resolve_commit(head_ref) + changed = _ChangedPaths(max_paths) + fields = _NulFields(changed.receive) result = self._run( ["diff", "--name-status", "-z", "--find-renames", "--no-ext-diff", base, head], text=False, + stdout_observer=fields.consume, ) - assert isinstance(result.stdout, bytes) if result.returncode != 0: raise RepositoryEvidenceError("failed to compare immutable repository refs") - paths: set[str] = set() - fields = result.stdout.split(b"\0") - if fields and fields[-1] == b"": - fields.pop() - index = 0 - while index < len(fields): - status = fields[index] - index += 1 - path_count = 2 if status[:1] in {b"R", b"C"} else 1 - if not status or index + path_count > len(fields): - raise RepositoryEvidenceError("Git returned an invalid name-status record") - for raw_path in fields[index : index + path_count]: - try: - decoded_path = raw_path.decode("utf-8") - except UnicodeDecodeError as exc: - raise RepositoryEvidenceError("changed path is not valid UTF-8") from exc - paths.add(normalize_repo_path(decoded_path)) - if len(paths) > max_paths: - raise RepositoryEvidenceBudgetError( - len(paths), - max_paths, - "entries", - message="changed path count exceeds the bounded limit", - ) - index += path_count - return tuple(sorted(paths)) + if fields.partial or changed.remaining_paths: + raise RepositoryEvidenceError("Git returned an invalid name-status record") + return tuple(sorted(changed.paths)) def build_file_snapshot( diff --git a/src/ocr_toolkit/evidence/source_reader.py b/src/ocr_toolkit/evidence/source_reader.py index f316b810..c296c1df 100644 --- a/src/ocr_toolkit/evidence/source_reader.py +++ b/src/ocr_toolkit/evidence/source_reader.py @@ -43,6 +43,7 @@ def __init__( max_total_bytes: int = MAX_TOTAL_SOURCE_BYTES, seconds: float = SOURCE_SECONDS, retain_syntax: bool = True, + local_only: bool = False, ) -> None: if not isinstance(head, str) or re.fullmatch(r"[0-9a-f]{40}", head) is None: raise ValueError("source head must be immutable") @@ -77,6 +78,7 @@ def __init__( seconds, ) self._retain_syntax = retain_syntax + self._local_only = local_only self._reader: GitRepositoryReader | None = None self._deadline: float | None = None self._paths: dict[str, RepositoryObject | SourceReadResult] = {} @@ -127,6 +129,7 @@ def _prepare(self) -> None: max_file_bytes=self._max_source, deadline=self._deadline, command_timeout=max(0.001, self._seconds), + local_only=self._local_only, ) for path, spans in self._requests.items(): entry = self._lookup(path) diff --git a/src/ocr_toolkit/federation/admission.py b/src/ocr_toolkit/federation/admission.py index 9995c84a..e43ae6df 100644 --- a/src/ocr_toolkit/federation/admission.py +++ b/src/ocr_toolkit/federation/admission.py @@ -6,6 +6,7 @@ import math import re from collections.abc import Iterator +from dataclasses import dataclass from typing import Any import mcp_types as types @@ -13,7 +14,9 @@ from referencing import Registry as SchemaRegistry from ocr_toolkit.context.contracts import TextBudgets -from ocr_toolkit.context.dlp import ForbiddenMatcher, check_text +from ocr_toolkit.context.dlp import ForbiddenMatcher, ForbiddenValue, check_text +from ocr_toolkit.context.dlp.decoding import RepresentationLimit +from ocr_toolkit.context.dlp.provenance import ResultProvenance from .contracts import ( ARGUMENT_BYTES, @@ -26,36 +29,42 @@ ) from .registry import origin -_KEYWORDS = { - "$schema", - "type", - "title", - "description", - "default", - "examples", - "properties", - "required", - "additionalProperties", - "items", - "prefixItems", - "minimum", - "maximum", - "exclusiveMinimum", - "exclusiveMaximum", - "minLength", - "maxLength", - "minItems", - "maxItems", - "minProperties", - "maxProperties", - "enum", - "const", - "allOf", - "anyOf", - "oneOf", -} +_KEYWORDS = frozenset( + { + "$schema", + "type", + "title", + "description", + "default", + "examples", + "properties", + "required", + "additionalProperties", + "items", + "prefixItems", + "minimum", + "maximum", + "exclusiveMinimum", + "exclusiveMaximum", + "minLength", + "maxLength", + "minItems", + "maxItems", + "minProperties", + "maxProperties", + "enum", + "const", + "allOf", + "anyOf", + "oneOf", + } +) +_SCHEMA_CHILDREN = frozenset({"items", "additionalProperties"}) +_SCHEMA_LIST_CHILDREN = frozenset({"prefixItems", "allOf", "anyOf", "oneOf"}) _URL = re.compile(r"(?:[A-Za-z][A-Za-z0-9+.-]*:)?//[^\s<>\"']+") _TEXT_BUDGETS = TextBudgets(RESPONSE_CHARS, RESPONSE_BYTES, RESPONSE_CHARS) +_COMBINATORS = frozenset({"allOf", "anyOf", "oneOf", "prefixItems"}) +_JSON_TYPES = frozenset({"array", "boolean", "integer", "null", "number", "object", "string"}) def encode(value: object) -> bytes: @@ -68,29 +77,57 @@ def encode(value: object) -> bytes: raise FederationError("protocol_invalid") from None -def strings(value: object, *, depth: int = 16, nodes: int = 1024) -> Iterator[str]: - """Walk a finite JSON tree with bounds before recursively visiting descendants.""" - pending = [(value, 0)] +def _string_material( + value: object, *, depth: int, nodes: int, schema_keywords_safe: bool +) -> Iterator[tuple[str, bool]]: + """Walk one bounded external JSON tree under the selected key-provenance policy.""" + pending = [(value, 0, "schema" if schema_keywords_safe else "data")] count = 0 while pending: - item, level = pending.pop() + item, level, context = pending.pop() count += 1 if count > nodes or level > depth: raise FederationError("oversized") if isinstance(item, str): - yield item + yield item, context == "property_name" elif isinstance(item, dict): if len(item) > nodes - count: raise FederationError("oversized") for key, child in item.items(): if not isinstance(key, str): raise FederationError("protocol_invalid") - yield key - pending.append((child, level + 1)) + child_context = "data" + if context == "schema": + # Keyword names are fixed only at schema nodes. Identical keys in + # property maps or example/default data remain upstream material. + if key not in _KEYWORDS: + yield key, True + if key == "type" and isinstance(child, str) and child in _JSON_TYPES: + # The validator fixes this vocabulary. The same word in a + # property name, example or result still has source provenance. + continue + if key == "properties": + child_context = "properties" + elif key == "required": + child_context = "required" + elif key in _SCHEMA_CHILDREN: + child_context = "schema" + elif key in _SCHEMA_LIST_CHILDREN: + child_context = "schema_list" + elif context == "properties": + yield key, True + child_context = "schema" + else: + yield key, True + pending.append((child, level + 1, child_context)) elif isinstance(item, list): if len(item) > nodes - count: raise FederationError("oversized") - pending.extend((child, level + 1) for child in item) + child_context = { + "schema_list": "schema", + "required": "property_name", + }.get(context, "data") + pending.extend((child, level + 1, child_context) for child in item) elif item is None or isinstance(item, bool): pass elif isinstance(item, int | float): @@ -100,6 +137,24 @@ def strings(value: object, *, depth: int = 16, nodes: int = 1024) -> Iterator[st raise FederationError("protocol_invalid") +def strings( + value: object, *, depth: int = 16, nodes: int = 1024, include_keys: bool = True +) -> Iterator[str]: + """Walk a finite JSON tree with bounds before recursively visiting descendants.""" + for text, key in _string_material(value, depth=depth, nodes=nodes, schema_keywords_safe=False): + if include_keys or not key: + yield text + + +def publication_values(value: object, *, schema: bool = False) -> Iterator[ForbiddenValue]: + """Project visible external keys and values, excluding fixed schema vocabulary.""" + depth, nodes = (12, 512) if schema else (16, 1024) + for text, structural_key in _string_material( + value, depth=depth, nodes=nodes, schema_keywords_safe=schema + ): + yield ForbiddenValue(text, "external_context", structural_key=structural_key) + + def check_dlp( value: object, matcher: ForbiddenMatcher, @@ -126,6 +181,17 @@ def check_dlp( ) +def check_provenance(value: object, sources: tuple[ResultProvenance, ...]) -> None: + """Check model-selected values after the closed argument schema has admitted the keys.""" + values = set(strings(value, include_keys=False)) + try: + matched = ResultProvenance.matches(values, sources) + except (RepresentationLimit, TimeoutError): + raise FederationError("oversized", boundary="arguments", detector="limit") from None + if matched: + raise FederationError("dlp_rejected", boundary="arguments", detector="forbidden") + + def compile_schema( schema: object, matcher: ForbiddenMatcher, *, dlp_enabled: bool = True ) -> Draft202012Validator: @@ -175,6 +241,44 @@ def compile_schema( raise FederationError("schema_invalid") from None +def compile_argument_schema( + schema: object, matcher: ForbiddenMatcher, *, dlp_enabled: bool = True +) -> Draft202012Validator: + """Compile an explicit closed operator-owned argument data contract.""" + validator = compile_schema(schema, matcher, dlp_enabled=dlp_enabled) + if not isinstance(schema, dict) or schema.get("type") != "object": + raise FederationError("schema_invalid") + pending = [schema] + while pending: + node = pending.pop() + if not isinstance(node, dict) or set(node) & _COMBINATORS: + raise FederationError("schema_invalid") + kind = node.get("type") + if not isinstance(kind, str) or kind not in _JSON_TYPES: + raise FederationError("schema_invalid") + if kind == "object": + properties = node.get("properties", {}) + if ( + not isinstance(properties, dict) + or node.get("additionalProperties") is not False + or "items" in node + ): + raise FederationError("schema_invalid") + pending.extend(properties.values()) + elif kind == "array": + if "properties" in node or "additionalProperties" in node: + raise FederationError("schema_invalid") + items = node.get("items") + if items is False: + continue + if not isinstance(items, dict): + raise FederationError("schema_invalid") + pending.append(items) + elif any(key in node for key in ("properties", "additionalProperties", "items")): + raise FederationError("schema_invalid") + return validator + + def arguments( value: object, policy: ToolPolicy, @@ -231,13 +335,24 @@ def result( return types.CallToolResult(content=content, structured_content=structured, is_error=False) -def string_values(value: object) -> Iterator[str]: - """Project already bounded external string values without inventing protected keys.""" - if isinstance(value, str): - yield value - elif isinstance(value, dict): - for child in value.values(): - yield from string_values(child) - elif isinstance(value, list): - for child in value: - yield from string_values(child) +@dataclass(frozen=True, slots=True) +class IndexedResult: + """Hold admitted result material until a caller consumes its delivery budget.""" + + response: types.CallToolResult + publication: frozenset[ForbiddenValue] + provenance: ResultProvenance + + +def index_result(value: types.CallToolResult) -> IndexedResult: + """Index text plus every structured key and value before caching an admitted result.""" + material = [ + *(block.text for block in value.content if isinstance(block, types.TextContent)), + value.structured_content, + ] + publication = frozenset(publication_values(material)) + try: + provenance = ResultProvenance.compile(item.value for item in publication) + except (RepresentationLimit, TimeoutError): + raise FederationError("oversized", boundary="result", detector="limit") from None + return IndexedResult(value, publication, provenance) diff --git a/src/ocr_toolkit/federation/contracts.py b/src/ocr_toolkit/federation/contracts.py index a0c914d4..ff34fd3a 100644 --- a/src/ocr_toolkit/federation/contracts.py +++ b/src/ocr_toolkit/federation/contracts.py @@ -5,6 +5,7 @@ from dataclasses import dataclass REGISTRY_BYTES = 64 * 1024 +REGISTRY_VERSION = 3 SCHEMA_BYTES = 16 * 1024 ARGUMENT_BYTES = 32 * 1024 RESPONSE_BYTES = 256 * 1024 @@ -74,12 +75,14 @@ def __init__( @dataclass(frozen=True, slots=True) class ToolPolicy: - """Bind a single selected upstream tool to operator-only authority.""" + """Bind one tool to an immutable operator-authored model interface.""" name: str alias: str assurance: str = "advisory" resource_origins: tuple[str, ...] = () + description: str = "" + input_schema: bytes = b"" @dataclass(frozen=True, slots=True) @@ -99,7 +102,7 @@ class ServerSpec: @dataclass(frozen=True, slots=True) class Registry: - """Represent one exact version-two operator registry.""" + """Represent the validated and versioned operator registry.""" servers: tuple[ServerSpec, ...] - version: int = 2 + version: int = REGISTRY_VERSION diff --git a/src/ocr_toolkit/federation/gateway.py b/src/ocr_toolkit/federation/gateway.py index 9b437413..8cee3bdb 100644 --- a/src/ocr_toolkit/federation/gateway.py +++ b/src/ocr_toolkit/federation/gateway.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import json import time from collections import OrderedDict from collections.abc import Mapping @@ -15,7 +16,8 @@ from mcp import Client from mcp.server.lowlevel import Server -from ocr_toolkit.context.dlp import ForbiddenMatcher +from ocr_toolkit.context.dlp import ForbiddenMatcher, ForbiddenValue +from ocr_toolkit.context.dlp.provenance import ResultProvenance from . import admission from .contracts import ( @@ -88,9 +90,10 @@ def __init__( } self.total_calls = 0 self.delivered_bytes = 0 - self.publication: set[str] = set() - self.dispatches: dict[bytes, asyncio.Task[types.CallToolResult]] = {} - self.cache: OrderedDict[bytes, tuple[types.CallToolResult, int]] = OrderedDict() + self.publication: set[ForbiddenValue] = set() + self._result_provenance = {spec.name: ResultProvenance() for spec in registry.servers} + self.dispatches: dict[bytes, asyncio.Task[admission.IndexedResult]] = {} + self.cache: OrderedDict[bytes, tuple[admission.IndexedResult, int]] = OrderedDict() self.cache_bytes = 0 self.semaphore = asyncio.Semaphore(CONCURRENCY) self.connections: set[asyncio.Task[Any]] = set() @@ -100,9 +103,37 @@ def __init__( "ocr-federation", on_list_tools=self.list_tools, on_call_tool=self.call_tool ) + def _compile_interfaces(self) -> dict[str, tuple[types.Tool, Draft202012Validator]]: + """Validate the complete operator surface before any authenticated upstream opens.""" + interfaces: dict[str, tuple[types.Tool, Draft202012Validator]] = {} + metadata_bytes = 0 + for spec in self.registry.servers: + for policy in spec.tools: + try: + input_schema = json.loads(policy.input_schema) + except (ValueError, TypeError, RecursionError, UnicodeError): + raise FederationError("schema_invalid") from None + validator = admission.compile_argument_schema( + input_schema, self.matcher, dlp_enabled=self.dlp_enabled + ) + description = policy.description + admission.check_dlp( + description, self.matcher, boundary="schema", dlp_enabled=self.dlp_enabled + ) + definition = types.Tool( + name=policy.alias, description=description, input_schema=input_schema + ) + metadata_bytes += len(definition.model_dump_json(by_alias=True).encode("utf-8")) + if metadata_bytes > METADATA_BYTES: + raise FederationError("oversized") + self.publication.update(admission.publication_values(description)) + self.publication.update(admission.publication_values(input_schema, schema=True)) + interfaces[policy.alias] = definition, validator + return interfaces + async def prepare(self, stack: AsyncExitStack) -> None: """Establish selected peers and reject incomplete discovery before OCR starts.""" - metadata_bytes = 0 + interfaces = self._compile_interfaces() for spec in self.registry.servers: if spec.transport == "stdio": env = {target: self.environment[source] for target, source in spec.env_from} @@ -145,9 +176,7 @@ async def prepare(self, stack: AsyncExitStack) -> None: tool = found.get(policy.name) if tool is None: raise FederationError("inventory_invalid") - validator = admission.compile_schema( - tool.input_schema, self.matcher, dlp_enabled=self.dlp_enabled - ) + definition, validator = interfaces[policy.alias] output_validator = ( admission.compile_schema( tool.output_schema, self.matcher, dlp_enabled=self.dlp_enabled @@ -155,16 +184,6 @@ async def prepare(self, stack: AsyncExitStack) -> None: if tool.output_schema is not None else None ) - description = tool.description or "" - admission.check_dlp( - description, self.matcher, boundary="schema", dlp_enabled=self.dlp_enabled - ) - definition = types.Tool( - name=policy.alias, description=description, input_schema=tool.input_schema - ) - metadata_bytes += len(definition.model_dump_json(by_alias=True).encode("utf-8")) - if metadata_bytes > METADATA_BYTES: - raise FederationError("oversized") self.tools[policy.alias] = ExportedTool( spec, policy, definition, validator, output_validator, client ) @@ -179,11 +198,13 @@ async def list_tools( async def _dispatch( self, key: bytes, tool: ExportedTool, arguments: dict[str, Any] - ) -> types.CallToolResult: + ) -> admission.IndexedResult: """Make exactly one upstream request and cache only completely admitted success.""" try: async with asyncio.timeout(CALL_SECONDS): async with self.semaphore: + # A queued dispatch can outlive the caller's initial provenance view. + self._authorize_result_egress(tool.server.name, arguments) value = await tool.client.session.send_request( types.CallToolRequest( params=types.CallToolRequestParams( @@ -193,10 +214,16 @@ async def _dispatch( types.CallToolResult, request_read_timeout_seconds=CALL_SECONDS, ) - admitted = admission.result( + response = admission.result( value, tool.output_validator, self.matcher, dlp_enabled=self.dlp_enabled ) - size = len(admitted.model_dump_json(by_alias=True).encode("utf-8")) + len(key) + admitted = admission.index_result(response) + size = len(response.model_dump_json(by_alias=True).encode("utf-8")) + len(key) + size += sum( + len(view.encode("utf-8")) + for view in admitted.provenance.normalized + if view not in admitted.provenance.raw + ) if size <= CACHE_BYTES and not self.closing: while self.cache and ( len(self.cache) >= CACHE_ENTRIES or self.cache_bytes + size > CACHE_BYTES @@ -239,6 +266,16 @@ def _terminal(self, alias: str, error: FederationError) -> None: if error.boundary in DLP_CALL_GATES and error.detector in DLP_GATE_REASONS: counts["dlp_gates"][error.boundary][error.detector] += 1 + def _authorize_result_egress(self, destination: str, arguments: object) -> None: + """Deny result material learned from every server except the destination.""" + sources = tuple( + provenance + for source, provenance in self._result_provenance.items() + if source != destination and provenance.raw + ) + if sources: + admission.check_provenance(arguments, sources) + async def call_tool( self, _context: Any, params: types.CallToolRequestParams ) -> types.CallToolResult: @@ -271,6 +308,8 @@ async def call_tool( self.matcher, dlp_enabled=self.dlp_enabled, ) + # Cross-server provenance remains active when generic DLP is disabled. + self._authorize_result_egress(tool.server.name, values) key = params.name.encode("ascii") + b"\0" + canonical if cached := self.cache.get(key): result = cached[0] @@ -288,17 +327,16 @@ async def call_tool( else: counts["single_flight"] += 1 result = await asyncio.shield(dispatch) - size = len(result.model_dump_json(by_alias=True).encode("utf-8")) + size = len(result.response.model_dump_json(by_alias=True).encode("utf-8")) if self.delivered_bytes + size > DELIVERY_BYTES: raise FederationError("budget_exceeded") self.delivered_bytes += size - self.publication.update( - admission.string_values( - [*[block.text for block in result.content], result.structured_content] - ) - ) + # There is no await between provenance registration and result delivery. + # Cache hits and shared-flight waiters therefore receive identical policy. + self._result_provenance[tool.server.name].update(result.provenance) + self.publication.update(result.publication) counts["completed"] += 1 - return result + return result.response except asyncio.CancelledError: self._terminal(params.name, FederationError("tool_failed")) raise @@ -342,6 +380,7 @@ async def stop(self) -> None: await asyncio.gather(*pending, return_exceptions=True) self.cache.clear() self.cache_bytes = 0 + self._result_provenance.clear() def receipt(self) -> dict[str, Any]: """Return only finalized, reconciliable accounting after verified cleanup.""" diff --git a/src/ocr_toolkit/federation/registry.py b/src/ocr_toolkit/federation/registry.py index 9002fe4a..c17e8bbc 100644 --- a/src/ocr_toolkit/federation/registry.py +++ b/src/ocr_toolkit/federation/registry.py @@ -6,7 +6,15 @@ import re from urllib.parse import urlsplit -from .contracts import REGISTRY_BYTES, FederationError, Registry, ServerSpec, ToolPolicy +from .contracts import ( + REGISTRY_BYTES, + REGISTRY_VERSION, + SCHEMA_BYTES, + FederationError, + Registry, + ServerSpec, + ToolPolicy, +) _NAME = re.compile(r"[A-Za-z][A-Za-z0-9_-]{0,63}\Z") _ENV = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,127}\Z") @@ -40,7 +48,7 @@ def _name(value: object) -> str: def origin(value: str, *, endpoint: bool = False) -> str: - """Canonicalize an explicit HTTPS origin without userinfo or ambiguous hosts.""" + """Canonicalize an explicit HTTPS origin with an ASCII hostname.""" try: parsed = urlsplit(value) if ( @@ -53,6 +61,9 @@ def origin(value: str, *, endpoint: bool = False) -> str: or "\\" in value or any(c.isspace() for c in value) or (not endpoint and (parsed.path not in {"", "/"} or parsed.query)) + # Require internationalized names as explicit A-labels so transitional + # IDNA mappings cannot collapse distinct domains at this trust boundary. + or not parsed.netloc.isascii() or parsed.hostname.endswith(".") or "%" in parsed.netloc ): @@ -99,8 +110,23 @@ def _unique(pairs: list[tuple[str, object]]) -> dict[str, object]: return result +def _schema_bytes(value: object) -> bytes: + """Freeze one operator-owned schema as canonical immutable JSON.""" + if not isinstance(value, dict): + raise FederationError("registry_invalid") + try: + encoded = json.dumps( + value, ensure_ascii=False, allow_nan=False, sort_keys=True, separators=(",", ":") + ).encode("utf-8") + except (ValueError, TypeError, RecursionError, UnicodeError): + raise FederationError("registry_invalid") from None + if len(encoded) > SCHEMA_BYTES: + raise FederationError("registry_invalid") + return encoded + + def parse_registry(raw: str, profile: str = "local") -> Registry: - """Parse only the closed v2 registry and the provider-permitted transports.""" + """Parse only the closed operator registry and the provider-permitted transports.""" try: if ( profile not in {"local", "gitlab_mr"} @@ -115,7 +141,7 @@ def parse_registry(raw: str, profile: str = "local") -> Registry: ) if ( type(data["version"]) is not int - or data["version"] != 2 + or data["version"] != REGISTRY_VERSION or not isinstance(data["servers"], dict) or len(data["servers"]) > 16 ): @@ -184,16 +210,24 @@ def parse_registry(raw: str, profile: str = "local") -> Registry: policies: list[ToolPolicy] = [] for tool_name, policy in selected.items(): _name(tool_name) - policy = _object(policy, {"assurance", "resource_origins"}, set()) + policy = _object( + policy, + {"assurance", "resource_origins", "description", "input_schema"}, + {"description", "input_schema"}, + ) assurance = policy.get("assurance", "advisory") origins = policy.get("resource_origins", []) + description = policy["description"] if ( assurance not in {"advisory", "review_read"} or not isinstance(origins, list) or len(origins) > 16 or any(not isinstance(o, str) for o in origins) + or not isinstance(description, str) + or len(description.encode("utf-8")) > SCHEMA_BYTES ): raise FederationError("registry_invalid") + input_schema = _schema_bytes(policy["input_schema"]) alias = f"{name}__{tool_name}" if len(alias) > 64 or alias in aliases: raise FederationError("registry_invalid") @@ -202,7 +236,14 @@ def parse_registry(raw: str, profile: str = "local") -> Registry: if url is not None: allowed_origins.add(origin(url, endpoint=True)) policies.append( - ToolPolicy(tool_name, alias, assurance, tuple(sorted(allowed_origins))) + ToolPolicy( + name=tool_name, + alias=alias, + assurance=assurance, + resource_origins=tuple(sorted(allowed_origins)), + description=description, + input_schema=input_schema, + ) ) servers.append( ServerSpec( diff --git a/src/ocr_toolkit/federation/runtime.py b/src/ocr_toolkit/federation/runtime.py index 9c57536a..53f670f1 100644 --- a/src/ocr_toolkit/federation/runtime.py +++ b/src/ocr_toolkit/federation/runtime.py @@ -16,7 +16,9 @@ from pathlib import Path from typing import Any -from .contracts import RUN_SECONDS, FederationError, Registry +from ocr_toolkit.context.dlp import ForbiddenValue + +from .contracts import REGISTRY_VERSION, RUN_SECONDS, FederationError, Registry from .gateway import Gateway @@ -33,7 +35,11 @@ def __init__( dlp_enabled: bool = True, ) -> None: self._dlp_enabled = dlp_enabled - if not isinstance(run_id, str) or re.fullmatch(r"[a-f0-9]{32}", run_id) is None: + if ( + registry.version != REGISTRY_VERSION + or not isinstance(run_id, str) + or re.fullmatch(r"[a-f0-9]{32}", run_id) is None + ): raise FederationError("registry_invalid") names = { source @@ -105,9 +111,13 @@ def secret_values(self) -> tuple[str, ...]: return self._secrets @property - def forbidden_publication(self) -> tuple[str, ...]: - """Return bounded admitted external strings only; never include them in receipts.""" - return tuple(sorted(self._gateway.publication)) if self._gateway is not None else () + def forbidden_publication(self) -> tuple[ForbiddenValue, ...]: + """Return private publication rules for bounded admitted external material.""" + if self._gateway is None: + return () + return tuple( + sorted(self._gateway.publication, key=lambda value: (value.value, value.structural_key)) + ) def _run( self, diff --git a/src/ocr_toolkit/local_incremental.py b/src/ocr_toolkit/local_incremental.py index 076db356..ed8603eb 100644 --- a/src/ocr_toolkit/local_incremental.py +++ b/src/ocr_toolkit/local_incremental.py @@ -5,14 +5,17 @@ import ast import hashlib import hmac +import posixpath import re import sys -from collections.abc import Collection, Sequence +from collections import Counter +from collections.abc import Mapping, Sequence from dataclasses import dataclass, field, replace from pathlib import Path, PurePosixPath from subprocess import TimeoutExpired from time import monotonic from typing import Any +from urllib.parse import unquote, urlsplit from ocr_toolkit import __version__ from ocr_toolkit.common.git import isolated_git_environment @@ -20,6 +23,7 @@ from ocr_toolkit.context.code_text import TextSink from ocr_toolkit.context.contracts import TextBudgets from ocr_toolkit.context.dlp import ForbiddenMatcher, ForbiddenValue, check_text +from ocr_toolkit.context.dlp.markup import RepresentationLimit, interpret_markdown from ocr_toolkit.diagrams.contracts import DIAGRAM_TOOL_NAME from ocr_toolkit.evidence.artifacts import EvidenceArtifacts from ocr_toolkit.evidence.model import CoverageRecord, EvidenceRecord @@ -29,16 +33,22 @@ from ocr_toolkit.evidence.source_reader import SourceReadSession from ocr_toolkit.evidence.store import EvidenceStore from ocr_toolkit.evidence.text_contracts import MAX_TOTAL_SOURCE_BYTES, SOURCE_SECONDS -from ocr_toolkit.local_incremental_dependencies import NativeDependencies, dependency_path +from ocr_toolkit.local_incremental_dependencies import ( + NativeDependencies, + dependency_path, + unqualified_groups, +) from ocr_toolkit.local_incremental_imports import ( StaticImport, import_dependencies, imports_dynamic_loader, ) +from ocr_toolkit.local_incremental_replay import ReplayVerifier from ocr_toolkit.local_incremental_state import ( MAX_FILES, MAX_FINDING_TEXT, MAX_FINDINGS, + MAX_REPLAY_ARGUMENT_BYTES, MAX_STATE_BYTES, RUN_ID, SHA_256, @@ -60,7 +70,12 @@ from ocr_toolkit.native_capabilities import supports_incremental_selection from ocr_toolkit.ocr_result import encode_ocr_result, max_result_bytes from ocr_toolkit.posting.suggestions import bounded_source_range -from ocr_toolkit.reporting.incremental import RESULT_KEY, IncrementalReport, ReusedFile +from ocr_toolkit.reporting.incremental import ( + RESULT_KEY, + BaselineGroups, + IncrementalReport, + ReusedFile, +) from ocr_toolkit.reporting.model import ReviewReport from ocr_toolkit.result_contract import parse_result_outcome from ocr_toolkit.review_range import ReviewRange, admit_native_range @@ -68,10 +83,17 @@ _MAX_ARGUMENT_BYTES = 32_000 _MAX_DEPENDENCY_BYTES = 64_000 _PATH_BUDGETS = TextBudgets(max_chars=512, max_bytes=2048, max_lines=1) +_REPLAY_BUDGETS = TextBudgets(MAX_REPLAY_ARGUMENT_BYTES, MAX_REPLAY_ARGUMENT_BYTES, 1) _FINDING_BUDGETS = TextBudgets(MAX_FINDING_TEXT, MAX_FINDING_TEXT * 4, 4000) _REGULAR = {"100644", "100755"} _IDENTIFIER = re.compile(r"[a-zA-Z_][a-zA-Z_0-9]*") +_PATH_REFERENCE = re.compile(r"[A-Za-z0-9._/-]+") _DYNAMIC_BINDINGS = {"__builtins__", "__import__", "exec", "eval"} +_PYTHON_SUFFIXES = {".py", ".pyw", ".pyi"} +_PYTHON_SHEBANG = re.compile(r"\bpython(?:[0-9.]*)\b") +_MARKDOWN_SUFFIXES = {".markdown", ".md"} +_DATA_SUFFIXES = _MARKDOWN_SUFFIXES | {".json"} +_EXTERNAL_LINK_SCHEMES = {"http", "https", "mailto", "tel"} _RULE_FILE_SUFFIXES = {"md", "txt", "markdown"} _ISOLATED_GIT_SETTINGS = frozenset( { @@ -91,6 +113,26 @@ } ) _SAFE_GIT_RESTRICTIONS = {"GIT_ALLOW_PROTOCOL": "", "GIT_NO_LAZY_FETCH": "1"} +_EDITOR_SELECTION_SETTINGS = frozenset({"GIT_EDITOR", "GIT_SEQUENCE_EDITOR"}) +# Names that may be echoed in the fallback diagnostic. Any other inherited key is +# reported generically, because environment keys can hold arbitrary text. +_NAMEABLE_GIT_SETTINGS = frozenset( + { + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_ASKPASS", + "GIT_CEILING_DIRECTORIES", + "GIT_DIR", + "GIT_DISCOVERY_ACROSS_FILESYSTEM", + "GIT_EXTERNAL_DIFF", + "GIT_INDEX_FILE", + "GIT_NAMESPACE", + "GIT_OBJECT_DIRECTORY", + "GIT_PROXY_COMMAND", + "GIT_SSH", + "GIT_SSH_COMMAND", + "GIT_WORK_TREE", + } +) _HTTP_ROUTING_SETTINGS = frozenset( { "http_proxy", @@ -242,22 +284,23 @@ def _file_review_runtime(config: dict[str, Any], run_id: str) -> dict[str, Any] } -def _bounded_incremental_result( +def bounded_incremental_result( native: dict[str, object], incremental: IncrementalReport ) -> dict[str, object]: + """Append local incremental metadata within the native result limit.""" + limit = max_result_bytes() full = {**native, RESULT_KEY: incremental.payload()} if len(encode_ocr_result(full)) <= limit: return full - if not incremental.files and not incremental.incomplete: - # This run reviewed the full selection; its optional baseline metadata - # can remain in the Markdown without replacing native result data. - return native compact = incremental.compact_payload() report_only: dict[str, object] = {RESULT_KEY: compact} candidate = {**native, **report_only} if len(encode_ocr_result(candidate)) <= limit: return candidate + if not incremental.files and not incremental.incomplete: + # A full native review can carry optional local metadata in Markdown. + return native # A native success shape is valid only with all its admitted findings. identity_and_findings: dict[str, object] = { name: native[name] @@ -284,21 +327,24 @@ def _bounded_incremental_result( def _preview_digest(preview: dict[str, PreviewFile]) -> str: return _digest( - { - path: (item.status, item.insertions, item.deletions, item.selected, item.reason) + [ + (path, item.status, item.insertions, item.deletions, item.selected, item.reason) for path, item in preview.items() - } + ] ) -def _scoped_candidates(prior: ReviewCache, candidates: set[str], changes: set[str]) -> set[str]: +def _scoped_candidates( + prior: ReviewCache, candidates: set[str], changes: set[str], verifier: ReplayVerifier +) -> set[str]: changed_paths = {dependency_path(path) for path in changes} return { path - for path in candidates + for path in sorted(candidates) if (scope := prior.files[path].scope) is not None and candidates.issuperset(scope.members) and changed_paths.isdisjoint(scope.head_paths) + and all(verifier.verifies(replay) for replay in scope.replays) } @@ -323,6 +369,13 @@ def _path_admitted(path: str, matcher: ForbiddenMatcher) -> bool: ).admitted +def _replay_text_admitted(value: str, matcher: ForbiddenMatcher) -> bool: + result = check_text( + value, budgets=_REPLAY_BUDGETS, publication=True, forbidden_matcher=matcher, enabled=True + ) + return result.admitted and result.text == value + + def _changed_paths( previous: dict[str, RepositoryObject], current: dict[str, RepositoryObject] ) -> set[str]: @@ -361,7 +414,30 @@ class _PythonModule: def _python_module(text: str) -> _PythonModule: """Describe Python module bindings without evaluating source or imports.""" - tree = ast.parse(text) + return _describe_module(ast.parse(text)) + + +def _candidate_module(path: str, text: str) -> _PythonModule | None: + line = text.partition("\n")[0] + if PurePosixPath(path).suffix.lower() in _PYTHON_SUFFIXES or ( + line.startswith("#!") and _PYTHON_SHEBANG.search(line) + ): + return _python_module(text) + try: + tree = ast.parse(text) + except SyntaxError: + return None + if any( + isinstance( + node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef, ast.Import, ast.ImportFrom) + ) + for node in ast.walk(tree) + ): + return _describe_module(tree) + return None + + +def _describe_module(tree: ast.Module) -> _PythonModule: imports, declared, referenced = [], set(), set() static_imports = [] dynamic_imports = False @@ -407,6 +483,94 @@ def _python_module(text: str) -> _PythonModule: ) +def _text_references(text: str, module: _PythonModule | None) -> frozenset[str]: + """Keep filename references across formats and Python's scoped identifiers.""" + + referenced = ( + set(module.referenced) + if module is not None + else {match.group().casefold() for match in _IDENTIFIER.finditer(text)} + ) + for match in _PATH_REFERENCE.finditer(text): + lexical = match.group() + if len(lexical) <= 512 and any(marker in lexical for marker in "./-"): + path = lexical.casefold().removeprefix("/") + while path.startswith(("./", "../")): + path = path.partition("/")[2] + referenced.update((path, path.rstrip("."), path.rsplit("/", 1)[-1].rstrip("."))) + return frozenset(referenced) + + +def _data_source(entry: RepositoryObject, text: str) -> bool: + """Data-only qualification requires content and Git mode to agree.""" + + return ( + entry.mode == "100644" + and PurePosixPath(entry.path).suffix.lower() in _DATA_SUFFIXES + and not text.removeprefix("\ufeff").startswith("#!") + ) + + +def _markdown_references(path: str, text: str, selected: set[str]) -> tuple[set[str], bool]: + """Resolve local CommonMark links and references without accessing their targets.""" + + try: + markup = interpret_markdown(text) + except (ValueError, RepresentationLimit, RecursionError): + return set(), True + uncertain = ( + "[[" in text or "{{" in text or any(item.lstrip().startswith("<") for item in markup.hidden) + ) + references = set() + for value in markup.links: + try: + destination = urlsplit(value) + if destination.scheme in _EXTERNAL_LINK_SCHEMES or ( + destination.netloc and not destination.scheme + ): + continue + if destination.scheme: + uncertain = True + continue + target = unquote(destination.path, errors="strict") + if not target: + continue + resolved = posixpath.normpath( + target[1:] + if target.startswith("/") + else posixpath.join(posixpath.dirname(path), target) + ) + if target.endswith("/") or not literal_path(resolved) or resolved not in selected: + uncertain = True + else: + references.update((resolved.casefold(), posixpath.basename(resolved).casefold())) + except ValueError: + uncertain = True + return references, uncertain + + +def _json_interface(value: object, names: set[str]) -> object: + if isinstance(value, dict): + for key in value: + names.update(_text_references(key, None)) + return {key: _json_interface(item, names) for key, item in value.items()} + if isinstance(value, list): + return [_json_interface(item, names) for item in value] + return type(value).__name__ + + +def _data_edit_bindings(path: str, previous: str, current: str) -> set[str]: + suffix = PurePosixPath(path).suffix.lower() + names: set[str] = set() + if suffix == ".json": + prior_json, current_json = (unique_json(text.encode()) for text in (previous, current)) + for value in (prior_json, current_json): + canonical_json(value) + if _json_interface(prior_json, names) != _json_interface(current_json, names): + raise IncrementalError("a changed JSON file has a new data interface") + return names + + def _independent_paths( reader: GitRepositoryReader, old_head: str, @@ -414,26 +578,68 @@ def _independent_paths( selected: set[str], changed: set[str], *, - tree_paths: Collection[str] | None = None, + current_tree: Mapping[str, RepositoryObject] | None = None, ) -> set[str]: """Keep direct path/identifier dependants and their transitive neighbours fresh.""" - modules = {path: _python_module(_read_text(reader, head, path)) for path in sorted(selected)} + if current_tree is None: + current_tree = {entry.path: entry for entry in reader.list_objects(head)} + modules = {} + references = {} + changed_texts = {} + data_paths = set() + uncertain = set() + for path in sorted(selected): + text = _read_text(reader, head, path) + if path in changed: + changed_texts[path] = text + module = _candidate_module(path, text) + if module is not None: + modules[path] = module + references[path] = _text_references(text, module) + if module is None and _data_source(current_tree[path], text): + data_paths.add(path) + if PurePosixPath(path).suffix.lower() in _MARKDOWN_SUFFIXES: + links, unresolved = _markdown_references(path, text, selected) + references[path] |= links + if unresolved: + uncertain.add(path) bindings = { - path: {name.casefold() for name in _binding_tokens(path) if _IDENTIFIER.fullmatch(name)} - | set(module.declared) - for path, module in modules.items() + path: {name.casefold() for name in _binding_tokens(path)} + | (set(modules[path].declared) if path in modules else set()) + for path in selected } previous_references = {} - for path in changed: - previous = _python_module(_read_text(reader, old_head, path)) - current = modules[path] - if not current.has_function or (previous.shared_shape, previous.imports) != ( - current.shared_shape, - current.imports, + json_changed = False + for path in sorted(changed): + previous_text = _read_text(reader, old_head, path) + previous = _candidate_module(path, previous_text) + current = modules.get(path) + previous_references[path] = _text_references(previous_text, previous) + if previous is None and current is None: + if path not in data_paths or not _data_source(current_tree[path], previous_text): + raise IncrementalError("a changed file has unsupported shared source semantics") + if path in uncertain: + raise IncrementalError("a changed Markdown file has ambiguous dependencies") + if PurePosixPath(path).suffix.lower() in _MARKDOWN_SUFFIXES: + links, unresolved = _markdown_references(path, previous_text, selected) + if unresolved: + raise IncrementalError("a changed Markdown file has ambiguous dependencies") + previous_references[path] |= links + bindings[path].update(_data_edit_bindings(path, previous_text, changed_texts[path])) + json_changed |= PurePosixPath(path).suffix.lower() == ".json" + continue + if ( + previous is None + or current is None + or not current.has_function + or (previous.shared_shape, previous.imports) + != ( + current.shared_shape, + current.imports, + ) ): raise IncrementalError("a changed module has new shared declarations") - previous_references[path] = previous.referenced dependency_inputs = { path: (module.static_imports, module.dynamic_imports) for path, module in modules.items() } @@ -453,31 +659,30 @@ def load_imports(path: str) -> tuple[tuple[StaticImport, ...], bool]: return module.static_imports, module.dynamic_imports dependencies = import_dependencies( - tree_paths - if tree_paths is not None - else {item.path for item in reader.list_objects(head)}, + current_tree.keys(), dependency_inputs, load_imports, ) unconfirmed = dependencies.dependants(dependencies.unknown) - changes = dependencies.dependants(changed) & selected + changes = (dependencies.dependants(changed) & selected) | changed else: dependencies = None unconfirmed = set() changes = set(changed) + if json_changed: + # A selected program may load JSON implicitly without naming the file. + changes.update(selected - data_paths) + changes.update(uncertain) active = set(changes) while active: identifiers = set().union(*(bindings[path] for path in active)) referenced = set().union( - *( - modules[path].referenced | previous_references.get(path, frozenset()) - for path in active - ) + *(references[path] | previous_references.get(path, frozenset()) for path in active) ) active = { path for path in selected - changes - if modules[path].referenced & identifiers or bindings[path] & referenced + if references[path] & identifiers or bindings[path] & referenced } if dependencies is not None: active = (dependencies.dependants(active) & selected) - changes @@ -563,7 +768,9 @@ class IncrementalSession: file_summary: dict[str, object] | None = None file_review_inputs_equivalent: bool = True fresh_scopes: dict[str, DependencyScope] = field(default_factory=dict) + fresh_groups: BaselineGroups | None = None pending: ReviewCache | None = None + store: EvidenceStore | None = field(default=None, repr=False) def select(self, preview_stdout: bytes) -> list[str] | None: """Qualify immutable selected paths, then propose literal native exclusions.""" @@ -575,6 +782,7 @@ def select(self, preview_stdout: bytes) -> list[str] | None: max_file_bytes=_MAX_DEPENDENCY_BYTES, command_timeout=5, deadline=monotonic() + 24, + local_only=True, ) self.current = {item.path: item for item in reader.list_objects(self.review_range.head)} selected = {path for path, item in self.full.items() if item.selected} @@ -636,12 +844,19 @@ def select(self, preview_stdout: bytes) -> list[str] | None: self.review_range.head, selected, changes, - tree_paths=self.current.keys(), + current_tree=self.current, ) if not candidates: self.reason = "No previously reviewed files are independent of the edits." return None - candidates = _scoped_candidates(self.prior, candidates, changes) + verifier = ReplayVerifier( + reader, + self.review_range, + self.store, + lambda value: _replay_text_admitted(value, self.matcher), + trees={self.review_range.head: tuple(self.current.values())}, + ) + candidates = _scoped_candidates(self.prior, candidates, changes, verifier) if not candidates: self.reason = "No prior group has verified dependencies unaffected by the edits." return None @@ -668,7 +883,7 @@ def confirm(self, preview_stdout: bytes) -> bool: for path, item in self.full.items() } if ( - _preview(preview_stdout) == expected + tuple(_preview(preview_stdout).items()) == tuple(expected.items()) and tuple(map(_rule_layer, self.rule_paths)) == self.rules ): self.carried = self.proposed @@ -689,7 +904,7 @@ def observe_rule_inputs(self) -> None: self.rule_inputs_stable = False def observe_native_dependencies(self, session_home: Path) -> None: - if self.full is not None and self.file_review_inputs_equivalent: + if self.full is not None and self.carried is None and self.file_review_inputs_equivalent: self.observed_dependencies = NativeDependencies.inspect( session_home, self.root, @@ -750,7 +965,7 @@ def verify_native(self, payload: dict[str, object], *, evidence_actions: object ) self.native_run, self.native_rules = run, rules self.complete = outcome.status == "complete" and completed == selected - if self.complete and self.observed_dependencies is not None: + if self.complete: diagram_owner = ( min( ( @@ -763,15 +978,26 @@ def verify_native(self, payload: dict[str, object], *, evidence_actions: object if self.diagram_observed else None ) - self.fresh_scopes = self.observed_dependencies.scopes( - self.root, - payload, - expected, - evidence_actions, - path_admitted=lambda path: _path_admitted(path, self.matcher), - diagram_owner=diagram_owner, - file_summary=self.file_summary, - ) + if self.observed_dependencies is None: + reason = "native_trace" + if self.carried is not None: + reason = "narrowed_context" + elif not self.file_review_inputs_equivalent: + reason = "diagram" + assessment = unqualified_groups(payload, expected, reason) + else: + assessment = self.observed_dependencies.scopes( + self.root, + payload, + expected, + evidence_actions, + path_admitted=lambda path: _path_admitted(path, self.matcher), + argument_admitted=lambda value: _replay_text_admitted(value, self.matcher), + diagram_owner=diagram_owner, + file_summary=self.file_summary, + store=self.store, + ) + self.fresh_scopes, self.fresh_groups = assessment.scopes, assessment.groups return self.complete except (ValueError, RecursionError) as exc: if self.carried is not None: @@ -813,8 +1039,12 @@ def admit( self._stage(report.comments, files, unconfirmed=unconfirmed) if self.pending is not None: qualified = sum(item.scope is not None for item in self.pending.files.values()) - incremental = replace(incremental, baseline_qualified_files=qualified) - result = _bounded_incremental_result(projected, incremental) + incremental = replace( + incremental, + baseline_qualified_files=qualified, + baseline_groups=self.pending.baseline_groups, + ) + result = bounded_incremental_result(projected, incremental) return result, replace(report, comments=combined, incremental=incremental) def _stage( @@ -851,8 +1081,25 @@ def _stage( if path in previous else self.fresh_scopes.get(path), ) + diagnostics = None + if self.fresh_groups is not None: + carried_groups = {item.scope.members for item in previous.values() if item.scope} + dropped = sum(not unconfirmed.isdisjoint(group) for group in carried_groups) + reasons = Counter(dict(self.fresh_groups.reasons)) + if dropped: + reasons["finding_admission"] += dropped + diagnostics = BaselineGroups( + self.fresh_groups.total + len(carried_groups), + self.fresh_groups.qualified + len(carried_groups) - dropped, + tuple(sorted(reasons.items())), + ) self.pending = ReviewCache( - self.review_range, self.digest, self.native_rules, snapshot, _preview_digest(self.full) + self.review_range, + self.digest, + self.native_rules, + snapshot, + _preview_digest(self.full), + diagnostics, ) def save(self) -> None: @@ -863,7 +1110,9 @@ def save(self) -> None: try: if ( self.checkout_scope is not None - and GitRepositoryReader(self.root).checkout_scope(self.review_range.head) + and GitRepositoryReader(self.root, local_only=True).checkout_scope( + self.review_range.head + ) != self.checkout_scope ): raise IncrementalError("incremental checkout moved before state capture") @@ -877,6 +1126,9 @@ def save(self) -> None: f"{len(self.pending.files)} files. Others will be reviewed again.", file=sys.stderr, ) + if self.pending.baseline_groups is not None: + for line in self.pending.baseline_groups.lines(): + print(line, file=sys.stderr) print(f"Private baseline path {str(self.cache_path)!a}", file=sys.stderr) @@ -895,7 +1147,7 @@ def _revalidate( for path, file in files.items() if file.findings } - session = SourceReadSession(root, head, requests) + session = SourceReadSession(root, head, requests, local_only=True) retained = [] dropped = 0 for path, file in files.items(): @@ -953,6 +1205,28 @@ def _admit_finding( return finding +def _runtime_forbidden(config: dict[str, Any]) -> tuple[ForbiddenValue, ...]: + """Keep the current API credential and operator header values out of the replay cache.""" + + llm = config.get("llm") + if not isinstance(llm, dict): + return () + headers = llm.get("extra_headers") + credentials = [llm.get("auth_token")] + if isinstance(headers, dict): + credentials.extend(headers.values()) + for value in headers.values(): + if isinstance(value, str): + scheme, _, secret = value.partition(" ") + if scheme.casefold() in {"basic", "bearer", "token"} and secret.strip(): + credentials.append(secret.strip()) + return tuple( + ForbiddenValue(value, "operator_secret") + for value in credentials + if isinstance(value, str) and value + ) + + def prepare( artifacts: EvidenceArtifacts, review_range: ReviewRange, @@ -983,17 +1257,31 @@ def prepare( reason = "active checkout identity" try: root = artifacts.root - checkout_scope = GitRepositoryReader(root).checkout_scope(review_range.head) + checkout_scope = GitRepositoryReader(root, local_only=True).checkout_scope( + review_range.head + ) if checkout_scope is None: raise IncrementalError("incremental review requires the active checkout HEAD") child_environment = isolated_git_environment() reason = "inherited Git settings" - if any( - name.startswith("GIT_") + for editor_setting in _EDITOR_SELECTION_SETTINGS: + child_environment.pop(editor_setting, None) + # Editor-selection variables only choose an interactive editor, which + # the read-only Git commands used here never invoke, so they must not + # disqualify incremental review. + unsupported_settings = sorted( + name + for name, value in child_environment.items() + if name.startswith("GIT_") and name not in _ISOLATED_GIT_SETTINGS and _SAFE_GIT_RESTRICTIONS.get(name) != value - for name, value in child_environment.items() - ): + ) + if unsupported_settings: + known = [name for name in unsupported_settings if name in _NAMEABLE_GIT_SETTINGS] + detail = ", ".join(known) + if len(known) != len(unsupported_settings): + detail = f"{detail}, others" if detail else "unrecognized" + reason = f"inherited Git settings ({detail})" raise IncrementalError("incremental Git environment is unsupported") reason = "private baseline directory or identity key" cache_path = cache_path_for(operator_home, root) @@ -1070,7 +1358,7 @@ def prepare( digest, tuple(rule_paths), rules, - ForbiddenMatcher.compile(forbidden), + ForbiddenMatcher.compile((*forbidden, *_runtime_forbidden(raw_config))), prior, native_version=native_version or "", checkout_scope=checkout_scope, @@ -1079,6 +1367,7 @@ def prepare( diagram_observed=diagram_run_id is not None, file_summary=file_summary, file_review_inputs_equivalent=equivalent, + store=store, ) if diagram: session.reason = "A change diagram requires a full review." diff --git a/src/ocr_toolkit/local_incremental_dependencies.py b/src/ocr_toolkit/local_incremental_dependencies.py index 436da049..e7fc9bd2 100644 --- a/src/ocr_toolkit/local_incremental_dependencies.py +++ b/src/ocr_toolkit/local_incremental_dependencies.py @@ -13,28 +13,36 @@ from typing import Any from ocr_toolkit.diagrams.contracts import DIAGRAM_TOOL_NAME -from ocr_toolkit.evidence.actions import validate_action_counts -from ocr_toolkit.evidence.mcp import TOOL_NAME +from ocr_toolkit.evidence.actions import UNATTRIBUTED_ACTION, validate_action_counts +from ocr_toolkit.evidence.mcp import COVERAGE_TOOL_NAME, SEARCH_TOOL_NAME, TOOL_NAME from ocr_toolkit.evidence.repository import GitRepositoryReader +from ocr_toolkit.evidence.store import EvidenceStore from ocr_toolkit.evidence.text_contracts import ( MAX_SOURCE_BYTES, MAX_TOTAL_SOURCE_BYTES, SOURCE_SECONDS, ) +from ocr_toolkit.local_incremental_replay import ReplayVerifier, observed_replay from ocr_toolkit.local_incremental_state import ( MAX_FILES, + MAX_GROUP_REPLAYS, + REPLAY_TOOLS, RUN_ID, DependencyScope, IncrementalError, + ToolReplay, canonical_json, literal_path, unique_json, ) +from ocr_toolkit.reporting.incremental import BaselineGroups from ocr_toolkit.review_range import ReviewRange from ocr_toolkit.review_trace import NativeTraceSource _READ_RANGE = re.compile(r"LINE_RANGE: ([0-9]{1,10})-([0-9]{1,10})\Z") _GROUP_TASKS = {"main_task", "plan_task", "review_filter_task", "memory_compression_task"} +_GROUP_CALLS = REPLAY_TOOLS | {"file_read", "code_comment", "task_done", DIAGRAM_TOOL_NAME} +_MAX_RESPONSE_CALLS = 128 _DIAGRAM_SUMMARY_STATES = { "pending", "received", @@ -59,6 +67,14 @@ def dependency_path(path: str) -> str: return hashlib.sha256(path.encode()).hexdigest() +def _replay_reason(tool: str) -> str: + if tool in {"code_search", "file_find"}: + return "search_tool" + if tool == "file_read_diff": + return "diff_read" + return "evidence_action" + + def _digest(value: object) -> bytes: return hashlib.sha256(canonical_json(value)).digest() @@ -70,11 +86,11 @@ class _ReadObservation: start: int end: int total: int - content: bytes = field(repr=False) + content: bytes | None = field(repr=False) def _read_observation( - args: dict[str, Any], response: str, review_range: ReviewRange + args: dict[str, Any], response: str, review_range: ReviewRange, *, ok: bool ) -> _ReadObservation: if not args.keys() <= {"file_path", "start_line", "end_line", "side"}: raise IncrementalError("native read has unsupported arguments") @@ -103,6 +119,15 @@ def _read_observation( if not response.startswith(prefix): raise IncrementalError("native read old-side revision is unavailable") response = response.removeprefix(prefix) + if not ok: + failure = re.fullmatch( + rf'file "{re.escape(path)}" has only ([0-9]{{1,10}}) lines, requested range ' + rf"{requested_start}-{requested_end or 0}", + response, + ) + if failure is None or not 1 <= (total := int(failure[1])) < requested_start: + raise IncrementalError("native read failure has no deterministic range outcome") + return _ReadObservation(path, revision, requested_start, requested_end or 0, total, None) header, truncated, source_range, body = response.split("\n", 3) total_match = re.fullmatch(rf"File: {re.escape(path)} \(Total lines: ([0-9]{{1,10}})\)", header) range_match = _READ_RANGE.fullmatch(source_range) @@ -137,10 +162,14 @@ def _verified_windows(observations: set[_ReadObservation], blob: bytes) -> set[_ observation for observation in observations if len(lines) == observation.total - and _digest( - [line.removesuffix("\r") for line in lines[observation.start - 1 : observation.end]] + and ( + observation.start > len(lines) + if observation.content is None + else _digest( + [line.removesuffix("\r") for line in lines[observation.start - 1 : observation.end]] + ) + == observation.content ) - == observation.content } @@ -175,12 +204,33 @@ def _groups(value: object, selected: set[str]) -> dict[str, tuple[str, ...]]: @dataclass(slots=True) class _GroupObservation: main_request: bool = False - unknown: bool = False - summaries: int = 0 + reasons: set[str] = field(default_factory=set) summary_digests: set[bytes] = field(default_factory=set) diagram_called: bool = False comment_paths: set[str] = field(default_factory=set) + requested_comments: int = 0 + observed_comments: int = 0 reads: set[_ReadObservation] = field(default_factory=set) + replays: set[ToolReplay] = field(default_factory=set) + + +@dataclass(frozen=True, slots=True) +class DependencyAssessment: + scopes: dict[str, DependencyScope] + groups: BaselineGroups | None + + +def unqualified_groups( + payload: dict[str, object], selected: set[str], reason: str +) -> DependencyAssessment: + try: + total = len(_groups(payload.get("groups"), selected)) + except ValueError: + raw = payload.get("groups") + if not isinstance(raw, list) or not 1 <= len(raw) <= len(selected): + return DependencyAssessment({}, None) + total, reason = len(raw), "group_partition" + return DependencyAssessment({}, BaselineGroups(total, 0, ((reason, total),))) @dataclass(slots=True) @@ -192,6 +242,8 @@ class NativeDependencies: session_id: str = "" manifest_digest: bytes | None = None tools: Counter[str] = field(default_factory=Counter) + evidence_attempted: Counter[str] = field(default_factory=Counter) + evidence_completed: Counter[str] = field(default_factory=Counter) groups: dict[str, _GroupObservation] = field(default_factory=dict) @classmethod @@ -223,7 +275,7 @@ def observe(self, record: dict[str, Any]) -> None: if not isinstance(manifest, dict): raise IncrementalError("native dependency terminal manifest is unavailable") self.manifest_digest = _digest(manifest) - elif kind in {"llm_request", "tool_call", "llm_error"}: + elif kind in {"llm_request", "llm_response", "tool_call", "llm_error"}: self._group_record(record, kind) def _group_record(self, record: dict[str, Any], kind: str) -> None: @@ -244,56 +296,70 @@ def _group_record(self, record: dict[str, Any], kind: str) -> None: group = self.groups.setdefault(key, _GroupObservation()) if kind == "llm_request": group.main_request |= task == "main_task" + elif kind == "llm_response": + self._requested_tools(record.get("tool_calls"), group) elif kind == "llm_error": - group.unknown = True + group.reasons.add("llm_error") else: self._tool(record, group) + @staticmethod + def _requested_tools(value: object, group: _GroupObservation) -> None: + """Check model requests that native may reject before recording execution.""" + + if value is None: + return + if not isinstance(value, list) or len(value) > _MAX_RESPONSE_CALLS: + group.reasons.add("invalid_arguments") + return + for item in value: + if not isinstance(item, dict) or not isinstance(name := item.get("name"), str): + group.reasons.add("invalid_arguments") + elif name == "code_comment": + group.requested_comments += 1 + elif name not in _GROUP_CALLS: + group.reasons.add("unsupported_tool") + def _tool(self, record: dict[str, Any], group: _GroupObservation) -> None: tool = record.get("tool_name") if not isinstance(tool, str): raise IncrementalError("native dependency tool identity is unavailable") self.tools[tool] += 1 + ok = record.get("ok") is True + if tool == "code_comment": + group.observed_comments += 1 + if not ok: + # The trace does not prove that an interrupted batch left every group untouched. + group.reasons.add("comment_attribution") + return if tool == DIAGRAM_TOOL_NAME: group.diagram_called = True - group.unknown = True - return - if record.get("ok") is not True: - group.unknown = True + group.reasons.add("diagram") return + reason = "invalid_arguments" try: - if tool not in {TOOL_NAME, "file_read", "code_comment"}: - # Even a successful search can miss newly matching material at the next head. - raise IncrementalError("unqualified native dependency tool") raw_args = record.get("arguments") if not isinstance(raw_args, str) or not isinstance( args := unique_json(raw_args.encode()), dict ): raise IncrementalError("native dependency arguments are unavailable") - if tool == TOOL_NAME: + action = self._evidence_action(tool, args, ok=ok) + if not ok and tool != "file_read": + group.reasons.add("failed_tool_call") + return + response = record.get("result") + if not isinstance(response, str): + raise IncrementalError("native dependency response is unavailable") + if action == "summary": + reason = "evidence_action" if args != {"action": "summary"}: - raise IncrementalError("unqualified evidence arguments") - group.summaries += 1 - if self.diagram: - response = record.get("result") - if not isinstance(response, str) or not isinstance( - summary := unique_json(response.encode()), dict - ): - raise IncrementalError("diagram evidence summary is unavailable") - status = summary.pop("diagram_output", None) - if status is not None and ( - not isinstance(status, dict) - or status.keys() != {"state"} - or not isinstance(status["state"], str) - or status["state"] not in _DIAGRAM_SUMMARY_STATES - ): - raise IncrementalError("diagram evidence summary is ambiguous") - group.summary_digests.add(_digest(summary)) + raise IncrementalError("unqualified evidence summary arguments") + group.summary_digests.add(self._summary(response)) elif tool == "file_read": - if not isinstance(response := record.get("result"), str): - raise IncrementalError("native read response is unavailable") - group.reads.add(_read_observation(args, response, self.review_range)) - else: + reason = "read_verification" if ok else "failed_tool_call" + group.reads.add(_read_observation(args, response, self.review_range, ok=ok)) + elif tool == "code_comment": + reason = "comment_attribution" comments = args.get("comments") if not isinstance(comments, list) or not comments: raise IncrementalError("native comment origin is unavailable") @@ -302,11 +368,53 @@ def _tool(self, record: dict[str, Any], group: _GroupObservation) -> None: if not isinstance(path, str) or not literal_path(path): raise IncrementalError("native comment origin is unavailable") group.comment_paths.add(path) + elif tool in REPLAY_TOOLS: + reason = _replay_reason(tool) + group.replays.add(observed_replay(tool, args, response)) + if len(group.replays) > MAX_GROUP_REPLAYS: + group.replays.clear() + group.reasons.add(reason) + else: + group.reasons.add("unsupported_tool") except (TypeError, ValueError, RecursionError): - group.unknown = True - if tool == "code_comment": + if tool == "code_comment" and ok: # An ambiguously authored finding can be filed against a different group. - raise IncrementalError("native comment attribution is unavailable") from None + reason = "comment_attribution" + group.reasons.add(reason if ok else "failed_tool_call") + + def _evidence_action(self, tool: str, args: dict[str, Any], *, ok: bool) -> str | None: + if tool == TOOL_NAME: + raw = args.get("action") + action = ( + raw + if isinstance(raw, str) and raw in ("summary", "list", "get") + else UNATTRIBUTED_ACTION + ) + elif tool == SEARCH_TOOL_NAME: + action = "search" + elif tool == COVERAGE_TOOL_NAME: + action = "coverage" + else: + return None + self.evidence_attempted[action] += 1 + if ok: + self.evidence_completed[action] += 1 + return action + + def _summary(self, response: str) -> bytes: + summary = unique_json(response.encode()) + if not isinstance(summary, dict): + raise IncrementalError("evidence summary is unavailable") + if self.diagram and "diagram_output" in summary: + status = summary.pop("diagram_output") + if ( + not isinstance(status, dict) + or status.keys() != {"state"} + or not isinstance(status["state"], str) + or status["state"] not in _DIAGRAM_SUMMARY_STATES + ): + raise IncrementalError("diagram evidence summary is ambiguous") + return _digest(summary) def scopes( self, @@ -316,92 +424,153 @@ def scopes( evidence_actions: object, *, path_admitted: Callable[[str], bool], + argument_admitted: Callable[[str], bool], + store: EvidenceStore | None, diagram_owner: str | None = None, file_summary: dict[str, object] | None = None, - ) -> dict[str, DependencyScope]: + ) -> DependencyAssessment: """Join exact native groups to validated reads, leaving uncertain groups unknown.""" - actions = validate_action_counts(evidence_actions) + try: + groups = _groups(payload.get("groups"), selected) + except ValueError: + return unqualified_groups(payload, selected, "group_partition") + + def all_unqualified(reason: str) -> DependencyAssessment: + return DependencyAssessment( + {}, BaselineGroups(len(groups), 0, ((reason, len(groups)),)) + ) + tool_calls = payload.get("tool_calls") manifest = payload.get("manifest") if ( - actions is None - or not isinstance(tool_calls, dict) - or not isinstance(manifest, dict) + not isinstance(manifest, dict) or self.session_id != manifest.get("run_id") or self.manifest_digest != _digest(manifest) + ): + return all_unqualified("native_trace") + if ( + not isinstance(tool_calls, dict) + or not isinstance(by_tool := tool_calls.get("by_tool"), dict) + or any(type(count) is not int for count in by_tool.values()) + or type(tool_calls.get("total")) is not int or tool_calls.get("by_tool") != self.tools or tool_calls.get("total") != self.tools.total() ): - return {} - try: - groups = _groups(payload.get("groups"), selected) - if groups.keys() != self.groups.keys(): - return {} - if self.diagram and ( - diagram_owner not in selected - or file_summary is None + return all_unqualified("native_counters") + if groups.keys() != self.groups.keys(): + return all_unqualified("group_partition") + if self.diagram and ( + diagram_owner not in selected + or file_summary is None + or any( + group.diagram_called and diagram_owner not in groups[key] + for key, group in self.groups.items() + ) + ): + return all_unqualified("diagram") + warnings = payload.get("warnings", []) + if ( + any( + "comment_attribution" in group.reasons + or group.requested_comments != group.observed_comments + or group.comment_paths - set(groups[key]) + for key, group in self.groups.items() + ) + or not isinstance(warnings, list) + or any( + not isinstance(warning, dict) or any( - group.diagram_called and diagram_owner not in groups[key] - for key, group in self.groups.items() + name in warning.values() + for name in ("comment_refiled", "comment_args_repaired") ) - ): - return {} - for key, group in self.groups.items(): - if not group.comment_paths <= set(groups[key]): - return {} - warnings = payload.get("warnings", []) - if not isinstance(warnings, list) or any( - not isinstance(warning, dict) or "comment_refiled" in warning.values() for warning in warnings + ) + ): + return all_unqualified("comment_attribution") + actions = validate_action_counts(evidence_actions) + if actions is None: + if evidence_actions is not None or any( + self.tools[tool] for tool in (TOOL_NAME, SEARCH_TOOL_NAME, COVERAGE_TOOL_NAME) ): - return {} - # The action receipt has no group identity. Require a complete aggregate - # match for all summaries claimed by candidate groups. - if actions["completed"]["summary"] != sum( - group.summaries for group in self.groups.values() - ): - return {} - expected_summaries = {_digest(file_summary)} if self.diagram else set() - candidates = { - key: group - for key, group in self.groups.items() - if group.main_request - and group.summaries - and not group.unknown - and ( - not self.diagram - or ( - diagram_owner not in groups[key] - and group.summary_digests == expected_summaries - ) - ) - and all(path_admitted(item.path) for item in group.reads) - } + return all_unqualified("evidence_counters") + elif ( + Counter(actions["attempted"]) != self.evidence_attempted + or Counter(actions["completed"]) != self.evidence_completed + ): + return all_unqualified("evidence_counters") + expected_summaries = {_digest(file_summary)} if file_summary is not None else set() + reasons = Counter[str]() + candidates = {} + for key, group in self.groups.items(): + rejected = set(group.reasons) + if not group.main_request: + rejected.add("missing_main_request") + if self.diagram and diagram_owner in groups[key]: + rejected.add("diagram") + if not group.summary_digests: + rejected.add("no_evidence_summary") + elif group.summary_digests != expected_summaries: + rejected.add("evidence_action") + if any(not path_admitted(item.path) for item in group.reads): + rejected.add("read_verification") + if rejected: + reasons.update(rejected) + else: + candidates[key] = group + if not candidates: + return DependencyAssessment( + {}, BaselineGroups(len(groups), 0, tuple(sorted(reasons.items()))) + ) + try: + reader = GitRepositoryReader( + root, + max_file_bytes=MAX_SOURCE_BYTES, + deadline=monotonic() + SOURCE_SECONDS, + command_timeout=5, + local_only=True, + ) + except (ValueError, OSError, TimeoutExpired, RecursionError): + return all_unqualified("read_verification") + try: reads = {item for group in candidates.values() for item in group.reads} - verified = self._verify_reads(root, reads) - scopes = {} - for key, group in candidates.items(): - if group.reads <= verified: - paths = { - dependency_path(item.path) - for item in group.reads - if item.revision == self.review_range.head - } - scope = DependencyScope(groups[key], tuple(sorted(paths))) - scopes.update(dict.fromkeys(groups[key], scope)) - return scopes + verified = self._verify_reads(reader, reads) except (ValueError, OSError, TimeoutExpired, RecursionError): - return {} + verified = set() + replay_verifier = ReplayVerifier(reader, self.review_range, store, argument_admitted) + scopes: dict[str, DependencyScope] = {} + qualified = 0 + for key in sorted(candidates): + group = candidates[key] + rejected = set() + if not group.reads <= verified: + rejected.add("read_verification") + replays = tuple( + sorted(group.replays, key=lambda item: (item.tool, item.arguments, item.result)) + ) + for replay in replays: + if not replay_verifier.verifies(replay): + rejected.add(_replay_reason(replay.tool)) + if rejected: + reasons.update(rejected) + continue + paths = { + dependency_path(item.path) + for item in group.reads + if item.revision == self.review_range.head + } + scope = DependencyScope(groups[key], tuple(sorted(paths)), replays) + scopes.update(dict.fromkeys(groups[key], scope)) + qualified += 1 + return DependencyAssessment( + scopes, BaselineGroups(len(groups), qualified, tuple(sorted(reasons.items()))) + ) - def _verify_reads(self, root: Path, reads: set[_ReadObservation]) -> set[_ReadObservation]: + def _verify_reads( + self, reader: GitRepositoryReader, reads: set[_ReadObservation] + ) -> set[_ReadObservation]: if not reads: return set() - reader = GitRepositoryReader( - root, - max_file_bytes=MAX_SOURCE_BYTES, - deadline=monotonic() + SOURCE_SECONDS, - ) remaining = MAX_TOTAL_SOURCE_BYTES verified = set() for revision in (self.review_range.base, self.review_range.head): diff --git a/src/ocr_toolkit/local_incremental_replay.py b/src/ocr_toolkit/local_incremental_replay.py new file mode 100644 index 00000000..66e593f0 --- /dev/null +++ b/src/ocr_toolkit/local_incremental_replay.py @@ -0,0 +1,257 @@ +"""Reproduce bounded observations from the qualified OCR read-only tool family.""" + +from __future__ import annotations + +import hashlib +import re +from collections.abc import Callable, Iterator +from dataclasses import dataclass, field +from pathlib import PurePosixPath +from subprocess import TimeoutExpired +from typing import Any + +from ocr_toolkit.evidence.mcp import ( + COVERAGE_TOOL_NAME, + SEARCH_TOOL_NAME, + TOOL_NAME, + call_named_tool, +) +from ocr_toolkit.evidence.repository import GitRepositoryReader, RepositoryObject +from ocr_toolkit.evidence.store import EvidenceStore +from ocr_toolkit.local_incremental_state import ( + IncrementalError, + ToolReplay, + canonical_json, + literal_path, + unique_json, + validated_replay_arguments, +) +from ocr_toolkit.review_range import ReviewRange + +_EVIDENCE_TOOLS = {TOOL_NAME, SEARCH_TOOL_NAME, COVERAGE_TOOL_NAME} +_SIMPLE_DIFF = re.compile(r"diff --git a/([^ ]+) b/([^ ]+)\Z") +_EXTENSIONLESS = { + "Makefile", + "Dockerfile", + "LICENSE", + "Vagrantfile", + "Containerfile", + "BUILD", + "WORKSPACE", +} +_MAX_MATCHES = 100 +_MAX_RESULT_BYTES = 256 * 1024 +_MAX_REPLAY_CALLS = 64 + + +def _complete_evidence_result(tool: str, args: dict[str, Any], payload: dict[str, Any]) -> bool: + if tool == SEARCH_TOOL_NAME: + return ( + payload.get("schema_version") == "ocr.evidence-search/v1" + and payload.get("truncated") is False + and isinstance(matches := payload.get("matches"), list) + and type(payload.get("returned")) is int + and type(payload.get("total_matches")) is int + and len(matches) == payload["returned"] == payload["total_matches"] + ) + if tool == COVERAGE_TOOL_NAME: + return ( + payload.get("schema_version") == "ocr.evidence-coverage-query/v1" + and payload.get("state") == "complete" + and payload.get("truncated") is False + ) + if args.get("action") == "get": + return ( + isinstance(record := payload.get("record"), dict) + and isinstance(args.get("id"), str) + and record.get("id") == args["id"] + ) + return ( + args.get("cursor") in ("", None) + and "next_cursor" in payload + and payload["next_cursor"] is None + and isinstance(records := payload.get("records"), list) + and type(payload.get("returned")) is int + and len(records) == payload["returned"] + ) + + +def _result_digest(tool: str, args: dict[str, Any], result: str) -> str: + raw = result.encode() + if not raw or len(raw) > _MAX_RESULT_BYTES: + raise IncrementalError("incremental tool result exceeds its replay budget") + if tool in _EVIDENCE_TOOLS: + payload = unique_json(raw) + if not isinstance(payload, dict) or not _complete_evidence_result(tool, args, payload): + raise IncrementalError("incremental evidence result is incomplete or unstructured") + raw = canonical_json(payload) + return hashlib.sha256(raw).hexdigest() + + +def observed_replay(tool: str, args: dict[str, Any], result: str) -> ToolReplay: + raw = canonical_json(args) + validated_replay_arguments(tool, raw) + return ToolReplay(tool, raw.decode(), _result_digest(tool, args, result)) + + +def _arg_texts(args: dict[str, Any]) -> Iterator[str]: + for value in args.values(): + if isinstance(value, str): + yield value + elif isinstance(value, list): + yield from value + + +def _render_search(raw: bytes, revision: str) -> str: + if not raw: + return "No matches found" + if len(raw) > _MAX_RESULT_BYTES or not raw.endswith(b"\n"): + raise IncrementalError("native search output is incomplete or exceeds its budget") + prefix = f"{revision}:".encode() + rows = raw[:-1].split(b"\n", _MAX_MATCHES) + if len(rows) > _MAX_MATCHES: + raise IncrementalError("native search exceeds the complete match limit") + matches: dict[str, list[str]] = {} + for row in rows: + name, number, value = row.split(b"\0", 2) + path, text = name.removeprefix(prefix).decode(), value.decode() + if ( + not name.startswith(prefix) + or not literal_path(path) + or not number.isdigit() + or b"\0" in value + ): + raise IncrementalError("native search match is ambiguous") + matches.setdefault(path, []).append(f"{int(number)}|{text}\n") + return "".join( + f"File: {path}\nMatch lines: {len(lines)}\n{''.join(lines)}\n" + for path, lines in matches.items() + ) + + +def _find_files(tree: tuple[RepositoryObject, ...], query: str, case_sensitive: bool) -> str: + query = query.replace("\\", "/") + if not all(literal_path(entry.path) for entry in tree): + raise IncrementalError("native file inventory cannot be rendered unambiguously") + paths = [ + entry.path + for entry in tree + if "." in (name := PurePosixPath(entry.path).name) or name in _EXTENSIONLESS + ] + compare = str if case_sensitive else str.lower + needle = compare(query) + matches = [path for path in paths if needle in compare(PurePosixPath(path).name)] + if not matches: + matches = [path for path in paths if needle in compare(path)] + if len(matches) > _MAX_MATCHES: + raise IncrementalError("native file search exceeds the complete match limit") + return "\n".join(matches) or "// The file was not found" + + +def _diff_blocks(raw: bytes) -> dict[str, str]: + """Keep normal one-path blocks and the qualified native line projection.""" + + blocks: dict[str, list[str]] = {} + block: list[str] | None = None + in_hunk = False + for line in raw.decode().split("\n"): + line = line.removesuffix("\r") + if line.startswith("diff --git "): + names = _SIMPLE_DIFF.fullmatch(line) + block = None + if names and names[1] == names[2] and literal_path(names[1]): + block = blocks.setdefault(names[1], []) + if block: + raise IncrementalError("native diff path is ambiguous") + in_hunk = False + if block is not None: + in_hunk |= line.startswith("@@") + if in_hunk or not line.startswith("index "): + block.append(line) + return {path: "\n".join(lines) for path, lines in blocks.items()} + + +@dataclass(slots=True) +class ReplayVerifier: + """Match actual observations and re-evaluate them at the next immutable head.""" + + reader: GitRepositoryReader + review_range: ReviewRange + store: EvidenceStore | None + authorize_text: Callable[[str], bool] + trees: dict[str, tuple[RepositoryObject, ...]] = field(default_factory=dict) + _observed: dict[tuple[str, str], str | None] = field(default_factory=dict) + _diffs: dict[str, str] | None = None + + def verifies(self, replay: ToolReplay) -> bool: + key = (replay.tool, replay.arguments) + if key not in self._observed: + if len(self._observed) >= _MAX_REPLAY_CALLS: + return False + self._observed[key] = None + try: + args = validated_replay_arguments(replay.tool, replay.arguments.encode()) + if all(self.authorize_text(value) for value in _arg_texts(args)): + self._observed[key] = _result_digest( + replay.tool, args, self._execute(replay.tool, args) + ) + except (ValueError, OSError, TimeoutExpired, RecursionError): + pass + return self._observed[key] == replay.result + + def _tree(self, revision: str) -> tuple[RepositoryObject, ...]: + if revision not in self.trees: + self.trees[revision] = self.reader.list_objects(revision, local_only=True) + return self.trees[revision] + + def _execute(self, tool: str, args: dict[str, Any]) -> str: + if tool in _EVIDENCE_TOOLS: + if self.store is None: + raise IncrementalError("incremental evidence store is unavailable") + content = call_named_tool(self.store, tool, args).get("content") + if ( + not isinstance(content, list) + or len(content) != 1 + or not isinstance(content[0], dict) + or not isinstance(text := content[0].get("text"), str) + ): + raise IncrementalError("incremental evidence replay has an unsupported result") + return text + if tool == "file_read_diff": + if self._diffs is None: + self._diffs = _diff_blocks( + self.reader.review_patch(self.review_range.base, self.review_range.head) + ) + parts = [] + remaining = _MAX_RESULT_BYTES + for path in args["path_array"]: + if path not in self._diffs: + raise IncrementalError("native diff has a missing or ambiguous path") + header = f"==== FILE: {path} ====\n" + block = self._diffs[path] + remaining -= len(header) + 1 + if len(block) > remaining: + raise IncrementalError("native diff exceeds the replay result budget") + remaining -= len(block.encode()) + if remaining < 0: + raise IncrementalError("native diff exceeds the replay result budget") + parts.extend((header, block, "\n")) + return "".join(parts) + old = args.get("side") == "old" + revision = self.review_range.base if old else self.review_range.head + tree = self._tree(revision) + if tool == "file_find": + result = _find_files(tree, args["query_name"], args.get("case_sensitive", False)) + else: + if any(entry.is_submodule for entry in tree): + raise IncrementalError("native search scope may follow Git submodules") + result = _render_search( + self.reader.grep_tree( + revision, + args["search_text"], + tuple(args.get("file_patterns", ())), + case_sensitive=args.get("case_sensitive", False), + ), + revision, + ) + return f"SIDE: old\nREVISION: {revision}\n{result}" if old else result diff --git a/src/ocr_toolkit/local_incremental_state.py b/src/ocr_toolkit/local_incremental_state.py index 879cde44..d2285b87 100644 --- a/src/ocr_toolkit/local_incremental_state.py +++ b/src/ocr_toolkit/local_incremental_state.py @@ -8,13 +8,14 @@ import re import secrets import stat -from dataclasses import dataclass +from dataclasses import dataclass, field from fcntl import LOCK_EX, flock from pathlib import Path from typing import Any from ocr_toolkit.common.filesystem import fsync_directory, open_private_parent_directory from ocr_toolkit.evidence.repository import normalize_repo_path +from ocr_toolkit.reporting.incremental import BASELINE_REASONS, BaselineGroups from ocr_toolkit.review_range import ReviewRange CACHE_NAME = "incremental.json" @@ -25,8 +26,43 @@ MAX_STATE_BYTES = 2_000_000 MAX_FINDINGS = 512 MAX_FINDING_TEXT = 24_000 -STATE_SCHEMA = "ocr.local-incremental-state/v2" -PREVIOUS_STATE_SCHEMA = "ocr.local-incremental-state/v1" +STATE_SCHEMA = "ocr.local-incremental-state/v3" +PREVIOUS_STATE_SCHEMA = "ocr.local-incremental-state/v2" +_ORIGINAL_STATE_SCHEMA = "ocr.local-incremental-state/v1" +MAX_GROUP_REPLAYS = 32 +MAX_REPLAY_ARGUMENT_BYTES = 2_048 +REPLAY_TOOLS = frozenset( + { + "code_search", + "file_find", + "file_read_diff", + "ocr_toolkit_evidence", + "ocr_toolkit_evidence_search", + "ocr_toolkit_evidence_coverage", + } +) +_SEARCH_PATTERN = re.compile(r"[A-Za-z0-9._/*?-]{1,256}\Z") +_EVIDENCE_REPLAY_FIELDS = { + "ocr_toolkit_evidence": { + "action", + "kind", + "delta_kind", + "component", + "ref", + "page_size", + "cursor", + "id", + }, + "ocr_toolkit_evidence_search": { + "query", + "kind", + "delta_kind", + "component", + "ref", + "max_results", + }, + "ocr_toolkit_evidence_coverage": {"kind", "ref", "component", "path"}, +} PATH_RE = re.compile(r"[A-Za-z0-9._/-]{1,512}\Z") SHA_1 = re.compile(r"[a-f0-9]{40}\Z") SHA_256 = re.compile(r"[a-f0-9]{64}\Z") @@ -54,15 +90,32 @@ class IncrementalError(ValueError): """Incremental review inputs or coverage could not be proved.""" +@dataclass(frozen=True, slots=True) +class ToolReplay: + """Hold bounded admitted arguments and the digest of the witnessed result.""" + + tool: str + arguments: str = field(repr=False) + result: str + + def payload(self) -> dict[str, str]: + return {"tool": self.tool, "arguments": self.arguments, "result": self.result} + + @dataclass(frozen=True, slots=True) class DependencyScope: - """Group membership and hashed current-side path dependencies.""" + """Group membership, hashed head paths and reproducible tool observations.""" members: tuple[str, ...] head_paths: tuple[str, ...] + replays: tuple[ToolReplay, ...] = () def payload(self) -> dict[str, object]: - return {"members": list(self.members), "head_paths": list(self.head_paths)} + return { + "members": list(self.members), + "head_paths": list(self.head_paths), + "replays": [replay.payload() for replay in self.replays], + } @dataclass(frozen=True, slots=True) @@ -84,6 +137,7 @@ class ReviewCache: native_rules_digest: str files: dict[str, CachedFile] preview_digest: str | None = None + baseline_groups: BaselineGroups | None = None def canonical_json(value: object) -> bytes: @@ -110,6 +164,73 @@ def literal_path(value: object) -> bool: ) +def _query_text(value: object) -> bool: + return ( + isinstance(value, str) + and 1 <= len(value) <= 512 + and bool(value.strip()) + and all(character.isprintable() for character in value) + ) + + +def validated_replay_arguments(tool: str, raw: bytes) -> dict[str, Any]: + """Revalidate the closed argument families before any repository or MCP read.""" + + if ( + not isinstance(tool, str) + or tool not in REPLAY_TOOLS + or len(raw) > MAX_REPLAY_ARGUMENT_BYTES + ): + raise IncrementalError("incremental tool replay exceeds its argument contract") + args = unique_json(raw) + if not isinstance(args, dict): + raise IncrementalError("incremental tool replay requires an argument object") + if tool == "file_read_diff": + paths = args.get("path_array") + valid = ( + args.keys() == {"path_array"} + and isinstance(paths, list) + and 1 <= len(paths) <= MAX_FILES + and all(literal_path(path) for path in paths) + ) + elif tool in {"code_search", "file_find"}: + search = tool == "code_search" + key = "search_text" if search else "query_name" + options = {"file_patterns", "use_perl_regexp"} if search else set() + patterns = args.get("file_patterns", []) + valid = ( + args.keys() <= {"side", "case_sensitive", key} | options + and _query_text(args.get(key)) + and (search or args[key].isascii()) + and args.get("side", "new") in ("old", "new") + and type(args.get("case_sensitive", False)) is bool + and args.get("use_perl_regexp", False) is False + and isinstance(patterns, list) + and len(patterns) <= 16 + and all( + isinstance(pattern, str) + and _SEARCH_PATTERN.fullmatch(pattern) + and not pattern.startswith("/") + and ".." not in pattern.split("/") + for pattern in patterns + ) + ) + else: + valid = ( + args.keys() <= _EVIDENCE_REPLAY_FIELDS[tool] + and (tool != "ocr_toolkit_evidence" or args.get("action") in ("list", "get")) + and all( + item is None + or (type(item) is int and 0 <= item <= 1_000_000_000) + or _query_text(item) + for item in args.values() + ) + ) + if not valid: + raise IncrementalError("incremental tool replay arguments are unsupported") + return args + + def closed_finding(value: object, path: str) -> dict[str, Any] | None: if ( not isinstance(value, dict) @@ -119,11 +240,11 @@ def closed_finding(value: object, path: str) -> dict[str, Any] | None: or not value["content"].strip() ): return None - for key, field in value.items(): - if isinstance(field, str): - if len(field) > MAX_FINDING_TEXT or (key in LINE_FIELDS and len(field) > 12): + for key, item in value.items(): + if isinstance(item, str): + if len(item) > MAX_FINDING_TEXT or (key in LINE_FIELDS and len(item) > 12): return None - elif key not in LINE_FIELDS or type(field) is not int or not 1 <= field <= 1_000_000_000: + elif key not in LINE_FIELDS or type(item) is not int or not 1 <= item <= 1_000_000_000: return None return dict(value) @@ -131,13 +252,16 @@ def closed_finding(value: object, path: str) -> dict[str, Any] | None: def _cache_from_payload(raw: object) -> ReviewCache: if not isinstance(raw, dict): raise IncrementalError("incremental state has an unsupported shape") - legacy = raw.get("schema") == PREVIOUS_STATE_SCHEMA + schema = raw.get("schema") + legacy = schema == _ORIGINAL_STATE_SCHEMA keys = {"schema", "base_sha", "head_sha", "inputs", "rules", "files"} if not legacy: keys.add("preview") + if schema == STATE_SCHEMA: + keys.update({"baseline_groups", "scopes"}) if ( raw.keys() != keys - or raw["schema"] not in (STATE_SCHEMA, PREVIOUS_STATE_SCHEMA) + or schema not in (STATE_SCHEMA, PREVIOUS_STATE_SCHEMA, _ORIGINAL_STATE_SCHEMA) or (not legacy and not _sha256(raw["preview"])) or any( not isinstance(raw[key], str) or not SHA_256.fullmatch(raw[key]) @@ -148,6 +272,8 @@ def _cache_from_payload(raw: object) -> ReviewCache: ): raise IncrementalError("incremental state has an unsupported shape") files = {} + scopes = _stored_scopes(raw["scopes"]) if schema == STATE_SCHEMA else {} + scope_refs = set() count = 0 file_keys = {"mode", "blob", "source_head", "source_run", "findings"} if not legacy: @@ -176,14 +302,26 @@ def _cache_from_payload(raw: object) -> ReviewCache: if finding is None: raise IncrementalError("incremental state finding has an unsupported shape") findings.append(finding) + scope_value = file.get("scope") + if schema == STATE_SCHEMA and scope_value is not None: + if not isinstance(scope_value, str) or scope_value not in scopes: + raise IncrementalError("incremental file scope reference is invalid") + scope_refs.add(scope_value) + scope = scopes[scope_value] + if path not in scope.members: + raise IncrementalError("incremental file scope reference disagrees with membership") + else: + scope = _dependency_scope(scope_value, path, replays=False) files[path] = CachedFile( file["mode"], file["blob"], file["source_head"], file["source_run"], tuple(findings), - _dependency_scope(file.get("scope"), path), + scope, ) + if scope_refs != scopes.keys(): + raise IncrementalError("incremental state contains unreferenced group scopes") for item in files.values(): if item.scope is not None and any( member not in files @@ -199,6 +337,7 @@ def _cache_from_payload(raw: object) -> ReviewCache: raw["rules"], files, raw.get("preview"), + _baseline_groups(raw.get("baseline_groups"), files), ) @@ -206,12 +345,75 @@ def _sha256(value: object) -> bool: return isinstance(value, str) and SHA_256.fullmatch(value) is not None -def _dependency_scope(value: object, path: str) -> DependencyScope | None: +def _baseline_groups(value: object, files: dict[str, CachedFile]) -> BaselineGroups | None: + if value is None: + return None + if ( + not isinstance(value, dict) + or value.keys() != {"total", "qualified", "reasons"} + or type(total := value["total"]) is not int + or not 1 <= total <= len(files) + or type(qualified := value["qualified"]) is not int + or qualified != len({item.scope.members for item in files.values() if item.scope}) + or qualified > total + or not isinstance(reasons := value["reasons"], dict) + or not reasons.keys() <= BASELINE_REASONS + or any( + type(count) is not int or not 1 <= count <= total - qualified + for count in reasons.values() + ) + or sum(reasons.values()) < total - qualified + ): + raise IncrementalError("incremental baseline group diagnostics are invalid") + return BaselineGroups(total, qualified, tuple(sorted(reasons.items()))) + + +def _tool_replays(value: object) -> tuple[ToolReplay, ...]: + if not isinstance(value, list) or len(value) > MAX_GROUP_REPLAYS: + raise IncrementalError("incremental group replay list is invalid") + replays = [] + seen = set() + for item in value: + if ( + not isinstance(item, dict) + or item.keys() != {"tool", "arguments", "result"} + or not isinstance(tool := item["tool"], str) + or tool not in REPLAY_TOOLS + or not isinstance(arguments := item["arguments"], str) + or len(raw := arguments.encode()) > MAX_REPLAY_ARGUMENT_BYTES + or not isinstance(args := validated_replay_arguments(tool, raw), dict) + or canonical_json(args) != raw + or not _sha256(item["result"]) + or (tool, arguments) in seen + ): + raise IncrementalError("incremental tool replay is invalid") + seen.add((tool, arguments)) + replays.append(ToolReplay(tool, arguments, item["result"])) + return tuple(replays) + + +def _stored_scopes(value: object) -> dict[str, DependencyScope]: + if not isinstance(value, dict) or len(value) > MAX_FILES: + raise IncrementalError("incremental group scope map is invalid") + scopes = {} + for path, item in value.items(): + if ( + not literal_path(path) + or (scope := _dependency_scope(item, path, replays=True)) is None + or scope.members[0] != path + ): + raise IncrementalError("incremental group scope key disagrees with membership") + scopes[path] = scope + return scopes + + +def _dependency_scope(value: object, path: str, *, replays: bool) -> DependencyScope | None: if value is None: return None if ( not isinstance(value, dict) - or value.keys() != {"members", "head_paths"} + or value.keys() + != ({"members", "head_paths", "replays"} if replays else {"members", "head_paths"}) or not isinstance(members := value["members"], list) or not 1 <= len(members) <= MAX_FILES or any(not literal_path(member) for member in members) @@ -222,7 +424,9 @@ def _dependency_scope(value: object, path: str) -> DependencyScope | None: or sorted(set(head_paths)) != head_paths ): raise IncrementalError("incremental file dependency scope is invalid") - return DependencyScope(tuple(members), tuple(head_paths)) + return DependencyScope( + tuple(members), tuple(head_paths), _tool_replays(value["replays"]) if replays else () + ) def cache_path_for(home: Path, checkout: Path) -> Path: @@ -336,17 +540,24 @@ def read_cache(path: Path) -> ReviewCache | None: def write_cache(path: Path, cache: ReviewCache) -> None: - files = { - path: { + files = {} + scopes: dict[str, DependencyScope] = {} + for member, item in cache.files.items(): + scope_ref = None + if item.scope is not None: + if not item.scope.members: + raise IncrementalError("incremental group scope lacks members") + scope_ref = item.scope.members[0] + if scopes.setdefault(scope_ref, item.scope) != item.scope: + raise IncrementalError("incremental group scope is inconsistent") + files[member] = { "mode": item.mode, "blob": item.blob, "source_head": item.source_head, "source_run": item.source_run, "findings": list(item.findings), - "scope": item.scope.payload() if item.scope is not None else None, + "scope": scope_ref, } - for path, item in cache.files.items() - } payload = { "schema": STATE_SCHEMA, "base_sha": cache.review_range.base, @@ -354,7 +565,9 @@ def write_cache(path: Path, cache: ReviewCache) -> None: "inputs": cache.inputs_digest, "rules": cache.native_rules_digest, "files": files, + "scopes": {anchor: scope.payload() for anchor, scope in scopes.items()}, "preview": cache.preview_digest, + "baseline_groups": cache.baseline_groups.payload() if cache.baseline_groups else None, } _cache_from_payload(payload) raw = canonical_json(payload) diff --git a/src/ocr_toolkit/mcp_config.py b/src/ocr_toolkit/mcp_config.py index 2bb22ea6..16187d61 100644 --- a/src/ocr_toolkit/mcp_config.py +++ b/src/ocr_toolkit/mcp_config.py @@ -15,7 +15,7 @@ from ocr_toolkit.diagrams.lifecycle import diagram_warning from ocr_toolkit.diagrams.mcp import DIAGRAM_TOOL_NAME from ocr_toolkit.evidence.mcp import COVERAGE_TOOL_NAME, SEARCH_TOOL_NAME, TOOL_NAME -from ocr_toolkit.federation.contracts import FederationError, ServerSpec +from ocr_toolkit.federation.contracts import REGISTRY_VERSION, FederationError, ServerSpec from ocr_toolkit.federation.registry import parse_registry MAX_MCP_CONFIG_BYTES = 64 * 1024 @@ -62,10 +62,12 @@ class MCPContextConfig: def parse_mcp_servers(raw: str | None = None, *, profile: str = "local") -> list[ServerSpec]: - """Parse only version-two governed operator configuration.""" + """Parse the current governed operator configuration.""" if "OCR_MCP_REPLACE" in os.environ: - raise MCPConfigError("OCR_MCP_REPLACE was removed; use the governed version 2 registry") + raise MCPConfigError( + f"OCR_MCP_REPLACE was removed; use the governed version {REGISTRY_VERSION} registry" + ) source = os.environ.get("OCR_MCP_SERVERS_JSON", "") if raw is None else raw if not source.strip(): return [] @@ -73,7 +75,7 @@ def parse_mcp_servers(raw: str | None = None, *, profile: str = "local") -> list registry = parse_registry(source, profile=profile) except FederationError as exc: raise MCPConfigError( - "Invalid governed MCP registry; migrate OCR_MCP_SERVERS_JSON to version 2" + f"Invalid governed MCP registry; migrate OCR_MCP_SERVERS_JSON to version {REGISTRY_VERSION}" ) from exc return list(registry.servers) @@ -104,7 +106,7 @@ def compose_mcp_servers( name not in {BUILTIN_EVIDENCE_SERVER, FEDERATION_SERVER} for name in current ): raise MCPConfigError( - "Inherited direct MCP configuration was removed; migrate to registry version 2" + f"Inherited direct MCP configuration was removed; migrate to registry version {REGISTRY_VERSION}" ) payload: dict[str, dict[str, Any]] = {} capabilities: list[MCPCapability] = [] diff --git a/src/ocr_toolkit/native_capabilities.py b/src/ocr_toolkit/native_capabilities.py index 329db2ee..b7718adb 100644 --- a/src/ocr_toolkit/native_capabilities.py +++ b/src/ocr_toolkit/native_capabilities.py @@ -59,6 +59,12 @@ def supports_native_capability(version: str | None, capability: NativeCapability return isinstance(version, str) and capability in _QUALIFIED_HANDOFFS.get(version, ()) +def native_omits_gitignore_exclusions(version: str | None) -> bool: + """Recognize the qualified version reporting Git-ignored paths only in preview.""" + + return version == "1.14.6" and supports_native_capability(version, "gitlink_projection") + + def supports_incremental_selection(version: str | None) -> bool: """Check the version's incremental eligibility after executable qualification.""" diff --git a/src/ocr_toolkit/ocr_result.py b/src/ocr_toolkit/ocr_result.py index 04355e01..e19a68e7 100644 --- a/src/ocr_toolkit/ocr_result.py +++ b/src/ocr_toolkit/ocr_result.py @@ -14,7 +14,7 @@ from typing import Any from ocr_toolkit.common.filesystem import fsync_directory -from ocr_toolkit.common.redaction import sanitize_ocr_value +from ocr_toolkit.common.redaction import RedactedKeyCollision, sanitize_ocr_value DEFAULT_MAX_RESULT_BYTES = 2_000_000 MAX_RESULT_BYTES_HARD_LIMIT = 20_000_000 @@ -22,9 +22,10 @@ TOOLKIT_RESULT_KEY = "_ocr_toolkit" TOOLKIT_PRIVATE_DIAGNOSTIC_KEY = "_ocr_toolkit_private_diagnostic" TOOLKIT_GITLINK_SELECTION_KEY = "_ocr_toolkit_gitlink_selection" -TOOLKIT_RESULT_SCHEMA_VERSION = 13 +TOOLKIT_REVIEW_SELECTION_KEY = "_ocr_toolkit_review_selection" +TOOLKIT_RESULT_SCHEMA_VERSION = 15 PARTIAL_TOOLKIT_RESULT_SCHEMA_VERSION = 14 -HISTORICAL_TOOLKIT_RESULT_SCHEMA_VERSIONS = frozenset({9, 10, 11, 12}) +HISTORICAL_TOOLKIT_RESULT_SCHEMA_VERSIONS = frozenset({9, 10, 11, 12, 13}) SUPPORTED_TOOLKIT_RESULT_SCHEMA_VERSIONS = HISTORICAL_TOOLKIT_RESULT_SCHEMA_VERSIONS | { TOOLKIT_RESULT_SCHEMA_VERSION, PARTIAL_TOOLKIT_RESULT_SCHEMA_VERSION, @@ -306,8 +307,8 @@ def _read_descriptor(descriptor: int, *, limit: int) -> bytes: return data -def _decode_result(data: bytes) -> Any: - """Decode one bounded UTF-8 JSON result payload.""" +def decode_ocr_json(data: bytes) -> Any: + """Decode bounded native OCR JSON with unique keys and controlled errors.""" try: text = data.decode("utf-8") @@ -330,18 +331,113 @@ def reject_duplicate_advisory(pairs: list[tuple[str, Any]]) -> dict[str, Any]: raise OcrResultMalformed(str(exc)) from exc +class _RedactedPathResult(dict[str, Any]): + """Keep loader-owned omission accounting outside the artifact schema.""" + + def __init__(self, value: dict[str, Any], omitted_findings: int) -> None: + super().__init__(value) + self.omitted_findings = omitted_findings + + +def readback_omitted_findings(result: object) -> int: + """Return the number of findings whose native path was redacted on readback.""" + + return result.omitted_findings if isinstance(result, _RedactedPathResult) else 0 + + +def _disabled_coverage_readback( + original: dict[str, Any], sanitized: dict[str, Any] +) -> dict[str, Any]: + """Keep only private Git identity exact and omit any finding whose path changed.""" + + manifest = original.get("manifest") + safe_manifest = sanitized.get("manifest") + selected_paths: set[str] = set() + if isinstance(manifest, dict) and isinstance(safe_manifest, dict): + coverage = manifest.get("coverage") + safe_coverage = safe_manifest.get("coverage") + if isinstance(coverage, dict) and isinstance(safe_coverage, dict): + for kind in ("selected", "completed", "excluded", "reused", "failed", "waived"): + records = coverage.get(kind) + sanitized_records = safe_coverage.get(kind) + if not isinstance(records, list) or not isinstance(sanitized_records, list): + continue + fields = ( + ("item_id", "path", "old_path", "fingerprint") + if kind in {"selected", "completed", "excluded"} + else ("item_id",) + ) + for record, safe_record in zip(records, sanitized_records, strict=True): + if isinstance(record, dict) and isinstance(safe_record, dict): + for field in fields: + value = record.get(field) + if isinstance(value, str): + safe_record[field] = value + if kind == "selected" and isinstance(path := record.get("path"), str): + selected_paths.add(path) + + comments = original.get("comments") + safe_comments = sanitized.get("comments") + if not isinstance(comments, list) or not isinstance(safe_comments, list): + return sanitized + retained: list[object] = [] + for comment, safe_comment in zip(comments, safe_comments, strict=True): + if ( + isinstance(comment, dict) + and isinstance(safe_comment, dict) + and any(comment.get(field) != safe_comment.get(field) for field in ("path", "old_path")) + ): + path = comment.get("path") + if not isinstance(path, str) or path not in selected_paths: + raise OcrResultMalformed("OCR redacted finding is outside native selected coverage") + continue + retained.append(safe_comment) + if len(retained) == len(comments): + return sanitized + sanitized["comments"] = retained + return _RedactedPathResult(sanitized, len(comments) - len(retained)) + + +def _sanitize_receipted_result(raw: dict[str, Any], metadata: dict[str, Any]) -> dict[str, Any]: + """Keep optional Analysis redaction failures separate from required review data.""" + + from ocr_toolkit.review_analysis import PRIVATE_RESULT_KEY + + if "analysis_hmac_sha256" not in metadata or PRIVATE_RESULT_KEY not in raw: + return sanitize_ocr_value(raw) + # Keep the canonical top-level key in collision detection while handling + # the optional subtree independently of the primary review. + placeholder = object() + sanitized = sanitize_ocr_value({**raw, PRIVATE_RESULT_KEY: placeholder}) + # A configured secret can redact the key itself, so locate it by identity. + del sanitized[next(key for key, value in sanitized.items() if value is placeholder)] + analysis = raw[PRIVATE_RESULT_KEY] + try: + sanitize_ocr_value(analysis) + except (RecursionError, RedactedKeyCollision): + return sanitized + # Posting verifies the exact candidate by HMAC and rechecks publication DLP. + sanitized[PRIVATE_RESULT_KEY] = analysis + return sanitized + + def load_ocr_result(path: Path) -> Any: """Load and sanitize one bounded OCR JSON result from disk.""" descriptor = _open_result(path) try: try: - raw = _decode_result(_read_descriptor(descriptor, limit=max_result_bytes())) + raw = decode_ocr_json(_read_descriptor(descriptor, limit=max_result_bytes())) metadata = raw.get(TOOLKIT_RESULT_KEY) if isinstance(raw, dict) else None if ( isinstance(metadata, dict) and type(metadata.get("schema_version")) is int - and metadata["schema_version"] in {13, 14} + and metadata["schema_version"] + in { + 13, + TOOLKIT_RESULT_SCHEMA_VERSION, + PARTIAL_TOOLKIT_RESULT_SCHEMA_VERSION, + } ): from ocr_toolkit.review_receipt import toolkit_receipt_is_valid @@ -370,7 +466,10 @@ def load_ocr_result(path: Path) -> Any: dlp = metadata.get("dlp") enabled = not isinstance(dlp, dict) or dlp.get("enabled") is not False - if enabled: + if enabled or metadata["schema_version"] in { + TOOLKIT_RESULT_SCHEMA_VERSION, + PARTIAL_TOOLKIT_RESULT_SCHEMA_VERSION, + }: prose_budgets = TextBudgets(2_000_000, 8_000_000, 100_000) # Bound complete consumer slots before leaf admission or # generic recursive sanitization traverses their contents. @@ -385,7 +484,7 @@ def load_ocr_result(path: Path) -> Any: checked = check_text( text, publication=True, - enabled=True, + enabled=enabled, budgets=prose_budgets, ) if not checked.admitted or ( @@ -405,23 +504,23 @@ def load_ocr_result(path: Path) -> Any: if not text: continue checked = check_text( - text, publication=True, enabled=True, budgets=prose_budgets + text, publication=True, enabled=enabled, budgets=prose_budgets ) if not checked.admitted or (not warning and checked.text != text): raise OcrResultMalformed("OCR publication prose is not prepared") - # Preserve the exact canonical optional candidate. Generic - # redaction could turn a legitimate empty/template credential - # into a different branch condition. The publication owner - # revalidates the entire original diagram text and source proof, - # omitting the whole optional channel on admission failure. - sanitized = sanitize_ocr_value(raw) + sanitized = _sanitize_receipted_result(raw, metadata) + # Preserve exact diagram conditions for source-proof and DLP + # validation by the publication owner. sanitized[TOOLKIT_RESULT_KEY] = metadata - if "analysis_hmac_sha256" in metadata and "toolkit_analysis" in raw: - sanitized["toolkit_analysis"] = raw["toolkit_analysis"] + if not enabled and metadata["schema_version"] in { + TOOLKIT_RESULT_SCHEMA_VERSION, + PARTIAL_TOOLKIT_RESULT_SCHEMA_VERSION, + }: + sanitized = _disabled_coverage_readback(raw, sanitized) else: sanitized = sanitize_ocr_value(raw) return sanitized - except RecursionError as exc: + except (RecursionError, RedactedKeyCollision) as exc: raise OcrResultMalformed(str(exc)) from exc finally: os.close(descriptor) @@ -438,7 +537,7 @@ def inspect_ocr_result(path: Path, *, analysis_input: bool = False) -> Any: descriptor = _open_result(path) try: limit = max_result_bytes() - return _decode_result( + return decode_ocr_json( _read_descriptor( descriptor, limit=_analysis_input_limit(limit) if analysis_input else limit ) @@ -478,7 +577,7 @@ def transform_ocr_result( descriptor = _open_result_at(parent_descriptor, path) opened = os.fstat(descriptor) input_limit = _analysis_input_limit(limit) if optional_field is not None else limit - result = _decode_result(_read_descriptor(descriptor, limit=input_limit)) + result = decode_ocr_json(_read_descriptor(descriptor, limit=input_limit)) if not isinstance(result, dict): raise OcrResultMalformed("OCR result JSON must be an object") try: diff --git a/src/ocr_toolkit/posting/approval.py b/src/ocr_toolkit/posting/approval.py index 5e5a0c28..8b368a64 100644 --- a/src/ocr_toolkit/posting/approval.py +++ b/src/ocr_toolkit/posting/approval.py @@ -6,6 +6,7 @@ from enum import Enum from typing import Any +from ocr_toolkit.ocr_result import TOOLKIT_RESULT_SCHEMA_VERSION from ocr_toolkit.posting.settings import BooleanSetting from ocr_toolkit.result_contract import ReviewOutcome from ocr_toolkit.review_receipt import ( @@ -83,14 +84,18 @@ def evaluate_approval_policy( metadata_reason = automatic_approval_metadata_reason(toolkit_metadata) if metadata_reason: reason = metadata_reason + elif toolkit_metadata["schema_version"] != TOOLKIT_RESULT_SCHEMA_VERSION: + reason = "a current ordinary review receipt is required" elif toolkit_metadata["evidence"]["mandatory"] is not outcome.requires_evidence_mcp: reason = "the review-time approval receipt is missing or invalid" elif not outcome.manifest_present: reason = "the OCR result has no authoritative coverage manifest" elif outcome.kind != "clean" or outcome.budget_exceeded: reason = "the OCR review did not complete cleanly" - elif outcome.failed_count or outcome.waived_count: - reason = "coverage contained failed or waived items" + elif outcome.failed_count or outcome.waived_count or outcome.excluded_count: + reason = "coverage contained failed, waived, or excluded items" + elif outcome.reused_count: + reason = "coverage reused items without a verified prior GitLab review" elif warnings: reason = "the OCR review reported warnings" elif omitted_count: diff --git a/src/ocr_toolkit/posting/formatting.py b/src/ocr_toolkit/posting/formatting.py index c651abe6..fc231484 100644 --- a/src/ocr_toolkit/posting/formatting.py +++ b/src/ocr_toolkit/posting/formatting.py @@ -82,6 +82,7 @@ from ocr_toolkit.reporting.usage import nonnegative_int as nonnegative_int from ocr_toolkit.reporting.usage import tool_call_counts_from_items as tool_call_counts_from_items from ocr_toolkit.reporting.usage import tool_call_name as tool_call_name +from ocr_toolkit.result_contract import ReviewOutcome from ocr_toolkit.review_model import admitted_model from ocr_toolkit.review_range import ReviewRange from ocr_toolkit.review_receipt import toolkit_receipt_is_valid @@ -152,6 +153,37 @@ def format_finding_tags( return " · ".join(tags) +def rendered_finding_severity(line: str) -> str | None: + """Read known severity or its explicit absence from a canonical tag.""" + + text = re.fullmatch( + r"(?:\*\*Severity:\*\* `([a-z]+)`(?: · )?)?(?:\*\*Category:\*\* `([a-z]+)`)?", + line, + ) + if text is not None and line: + severity, category = text.groups() + return ( + severity or "" + if line + == format_finding_tags({"severity": severity, "category": category}, badge_mode="plain") + else None + ) + badge = re.match(r"!\[(?:([a-z]+) · )?([a-z]+)\]\(", line) + if badge is not None: + category, severity = badge.groups() + if category is None and severity in OCR_FINDING_CATEGORIES: + category, severity = severity, "" + return ( + severity + if line + == format_finding_tags( + {"severity": severity, "category": category}, badge_mode="shields" + ) + else None + ) + return None + + def format_suggestion_block(decision: SuggestionDecision) -> str: """Render one previously validated GitLab suggestion decision.""" @@ -439,6 +471,8 @@ def format_publication_dlp_details(signal: dict[str, Any] | None) -> str: "One or more public projection units were omitted. OCR coverage is reported " "separately, and automatic approval remains unavailable." if omitted["comments"] or omitted["warnings"] + else "Private manifest fields were sanitized. Automatic approval remains unavailable." + if not any(signal["reason_counts"].values()) else "The public projection changed, so automatic approval remains unavailable." ) return "\n".join( @@ -607,8 +641,10 @@ def format_reviewer_guide( *, outcome_status: str = "success", coverage_summary: str = "", + readback_omitted_count: int = 0, + carried_forward_count: int = 0, ) -> str: - """Build a bounded reviewer guide from already published OCR findings.""" + """Build a bounded reviewer guide from the current publication's findings.""" if not comments and omitted_count <= 0: return "" @@ -620,7 +656,7 @@ def format_reviewer_guide( if security_comments: lines.append("## Security review focus") lines.append( - f"- **Security signal:** {len(security_comments)} published OCR finding(s) explicitly mention security-sensitive terms." + f"- **Security signal:** {len(security_comments)} newly published OCR finding(s) explicitly mention security-sensitive terms." ) lines.append( "- Prioritize these findings before ordinary reliability or maintainability items." @@ -640,13 +676,17 @@ def format_reviewer_guide( if coverage_summary: lines.append(f"- Review coverage: {coverage_summary}") - if not security_comments and omitted_count: + if not security_comments and (omitted_count or readback_omitted_count): lines.append( - "- Security signal: none in published OCR findings; omitted findings were not inspected for this guide." + "- Security signal: none in newly published OCR findings. The assessment covers the findings shown here." ) elif not security_comments: lines.append( - "- Security signal: no security-sensitive findings detected in the published OCR comments." + "- Security signal: no security-sensitive findings detected in newly published OCR comments." + ) + if carried_forward_count: + lines.append( + "- Earlier OCR discussions contain retained findings outside this guide's security assessment." ) if omitted_count: @@ -686,23 +726,30 @@ def _review_outcome_line( *, total: int, omitted_count: int, + readback_omitted_count: int, suppressed_count: int, + carried_forward_count: int, warning_count: int, outcome_status: str, outcome_message: str, - diagnostics: CoverageDiagnostics, + unreviewed_file_count: int | None, emoji: bool, ) -> str: """Combine review health and finding publication into one visible status.""" return review_outcome_line( findings=FindingVisibility( - count=total, published=True, omitted=omitted_count, suppressed=suppressed_count + count=total, + published=True, + omitted=omitted_count, + readback_omitted=readback_omitted_count, + suppressed=suppressed_count, + carried_forward=carried_forward_count, ), warning_count=warning_count, outcome_status=outcome_status, outcome_message=outcome_message, - unreviewed_file_count=diagnostics.file_count, + unreviewed_file_count=unreviewed_file_count, emoji=emoji, ) @@ -715,6 +762,7 @@ def summarize_result( *, comments: Sequence[dict[str, Any]] = (), omitted_count: int = 0, + readback_omitted_count: int = 0, tool_calls_summary: str = "", mcp_usage_summary: str = "", token_usage_summary: str = "", @@ -733,8 +781,10 @@ def summarize_result( coverage_summary: str = "", repository_coverage_summary: str = "", coverage_diagnostics: CoverageDiagnostics | None = None, + coverage_outcome: ReviewOutcome | None = None, warnings: Sequence[Any] = (), suppressed_count: int = 0, + carried_forward_count: int = 0, approval_result: ApprovalResult | None = None, unprotected_target: bool = False, protected_policy_anchor_sha: str = "", @@ -753,11 +803,17 @@ def summarize_result( outcome_line = _review_outcome_line( total=total, omitted_count=omitted_count, + readback_omitted_count=readback_omitted_count, suppressed_count=suppressed_count, + carried_forward_count=carried_forward_count, warning_count=warning_count, outcome_status=outcome_status, outcome_message=outcome_message, - diagnostics=diagnostics, + unreviewed_file_count=( + diagnostics.unreviewed_file_count(coverage_outcome) + if coverage_outcome is not None + else diagnostics.file_count + ), emoji=use_emoji, ) lines = ["## Open Code Review", "", outcome_line] diff --git a/src/ocr_toolkit/posting/snapshot.py b/src/ocr_toolkit/posting/snapshot.py index 14606657..3dfd3967 100644 --- a/src/ocr_toolkit/posting/snapshot.py +++ b/src/ocr_toolkit/posting/snapshot.py @@ -9,6 +9,7 @@ from typing import Any from ocr_toolkit.posting.comments import comment_line, line_number +from ocr_toolkit.posting.formatting import rendered_finding_severity from ocr_toolkit.posting.gitlab import ( GitLabConfig, api_get_paginated, @@ -25,7 +26,6 @@ author_id_from_note, comment_fingerprint, comment_fingerprint_candidates, - finding_fingerprints_from_marked_body, fingerprint_from_marker, has_setup_pending_marker, has_summary_run_marker, @@ -36,9 +36,11 @@ line_based_comment_fingerprint, note_review_revision, reviewer_command_from_body, + write_id_from_body, ) from ocr_toolkit.posting.settings import post_mode, strict_posting from ocr_toolkit.posting.transaction import PostingTransaction +from ocr_toolkit.reporting.metadata import finding_metadata @dataclass @@ -60,10 +62,8 @@ class BotCommentRefs: # Fingerprints from past resolved, human-touched, or explicitly suppressed # comments. Matching findings are dropped regardless of ordinary line shifts. suppressed_fingerprints: set[str] = field(default_factory=set) - # Every finding already visible in the previous OCR review. A partial - # publication preserves those notes and suppresses matching duplicates. - published_fingerprints: set[str] = field(default_factory=set) - published_fingerprint_counts: dict[str, int] = field(default_factory=dict) + # Carry-forward requires the same rendered severity as well as the stable finding identity. + published_finding_counts: dict[tuple[str, str], int] = field(default_factory=dict) summary_plain_note_ids: list[int] = field(default_factory=list) summary_draft_note_ids: list[int] = field(default_factory=list) setup_plain_note_ids: list[int] = field(default_factory=list) @@ -123,32 +123,41 @@ def filter_suppressed_comments( def filter_previously_published_comments( - comments: Sequence[dict[str, Any]], previous_refs: BotCommentRefs | None + comments: Sequence[dict[str, Any]], + previous_refs: BotCommentRefs | None, + *, + review_comments: Sequence[dict[str, Any]] | None = None, ) -> tuple[list[dict[str, Any]], int]: """Avoid duplicating prior findings when a partial review preserves old notes.""" - if previous_refs is None or ( - not previous_refs.published_fingerprints and not previous_refs.published_fingerprint_counts - ): + if previous_refs is None or not previous_refs.published_finding_counts: return list(comments), 0 - available = Counter(previous_refs.published_fingerprint_counts) - for fingerprint in previous_refs.published_fingerprints: - if available[fingerprint] == 0: - available[fingerprint] = 1 + # Occurrence ordinals can move when the current review adds an anchor. + # Count before reviewer suppression so it cannot make a repeat look unique. + occurrences = Counter( + comment_fingerprint(comment) + for comment in (comments if review_comments is None else review_comments) + ) + available = Counter(previous_refs.published_finding_counts) kept: list[dict[str, Any]] = [] dropped = 0 for comment in comments: - ordered_candidates = ( - comment.get("_ocr_fingerprint"), - comment_fingerprint(comment), - line_based_comment_fingerprint(comment), - legacy_comment_fingerprint(comment), - ) + base = comment_fingerprint(comment) + if occurrences[base] > 1: + kept.append(comment) + continue + severity, _ = finding_metadata(comment) + current = comment.get("_ocr_fingerprint") or base + ordered_candidates = [current] + if line_number(comment.get("start_line") or comment.get("line")) > 0: + ordered_candidates.extend( + (line_based_comment_fingerprint(comment), legacy_comment_fingerprint(comment)) + ) matched = next( ( - fingerprint + (fingerprint, severity) for fingerprint in ordered_candidates - if isinstance(fingerprint, str) and available[fingerprint] > 0 + if isinstance(fingerprint, str) and available[fingerprint, severity] > 0 ), None, ) @@ -160,6 +169,20 @@ def filter_previously_published_comments( return kept, dropped +def _record_published_finding(refs: BotCommentRefs, fingerprint: str, body: str) -> None: + """Record carry-forward only when the owned note has recognizable visible metadata.""" + + lines = body.split("\n", 4) + start = 2 if write_id_from_body(body) is not None else 1 + if len(lines) > start + 1 and not lines[start + 1].rstrip("\r"): + severity = rendered_finding_severity(lines[start].rstrip("\r")) + if severity is not None: + identity = (fingerprint, severity) + refs.published_finding_counts[identity] = ( + refs.published_finding_counts.get(identity, 0) + 1 + ) + + def discussion_inline_key(discussion: dict[str, Any]) -> tuple[str, int] | None: """Return (path, new_line) for an inline discussion, if available. @@ -260,17 +283,15 @@ def process_discussion_for_refs( continue bot_notes.append(note) - fingerprint = fingerprint_from_marker(str(note.get("body") or "")) + body = str(note.get("body") or "") + fingerprint = fingerprint_from_marker(body) if fingerprint: fingerprints.append(fingerprint) if not scope_review or ( REVIEW_REVISION.get() is not None and note_review_revision(note["body"]) == REVIEW_REVISION.get() ): - refs.published_fingerprints.add(fingerprint) - refs.published_fingerprint_counts[fingerprint] = ( - refs.published_fingerprint_counts.get(fingerprint, 0) + 1 - ) + _record_published_finding(refs, fingerprint, body) if not bot_notes: return @@ -402,12 +423,9 @@ def replaceable(note: dict[str, Any], field: str) -> bool: refs.terminal_plain_note_ids.append(note_id) if not replaceable(note, "body"): continue - fingerprints = finding_fingerprints_from_marked_body(str(note.get("body") or "")) - refs.published_fingerprints.update(fingerprints) - for fingerprint in fingerprints: - refs.published_fingerprint_counts[fingerprint] = ( - refs.published_fingerprint_counts.get(fingerprint, 0) + 1 - ) + body = str(note.get("body") or "") + if fingerprint := fingerprint_from_marker(body): + _record_published_finding(refs, fingerprint, body) draft_notes: list[Any] = [] if post_mode() == "draft": diff --git a/src/ocr_toolkit/posting/workflow.py b/src/ocr_toolkit/posting/workflow.py index 2e4cd3ee..237dfd75 100644 --- a/src/ocr_toolkit/posting/workflow.py +++ b/src/ocr_toolkit/posting/workflow.py @@ -32,11 +32,14 @@ from ocr_toolkit.evidence.gitlink_projection import ( make_gitlink_projection, qualify_gitlink_manifest, + qualify_review_manifest, selected_gitlink_manifest_entries, selected_gitlink_proof_entries, + selection_from_manifest, + selection_from_review_proof, verify_gitlink_projection, ) -from ocr_toolkit.evidence.gitlinks import plan_gitlink_input +from ocr_toolkit.evidence.gitlinks import plan_gitlink_input, plan_review_input from ocr_toolkit.evidence.repository import GitRepositoryReader, RepositoryEvidenceError from ocr_toolkit.ocr_result import ( PARTIAL_TOOLKIT_RESULT_SCHEMA_VERSION, @@ -45,11 +48,13 @@ TOOLKIT_PRIVATE_DIAGNOSTIC_KEY, TOOLKIT_RESULT_KEY, TOOLKIT_RESULT_SCHEMA_VERSION, + TOOLKIT_REVIEW_SELECTION_KEY, OcrResultMalformed, OcrResultMissing, OcrResultTooLarge, load_ocr_result, parse_toolkit_advisory, + readback_omitted_findings, ) from ocr_toolkit.posting import gitlab as gitlab_api from ocr_toolkit.posting.approval import ( @@ -167,6 +172,12 @@ repository_coverage_summary, ) from ocr_toolkit.result_contract import OcrResultContractError, ReviewOutcome, parse_result_outcome +from ocr_toolkit.review_coverage import ( + ReviewCoverage, + ReviewCoverageError, + coverage_from_selection, + parse_review_coverage, +) from ocr_toolkit.review_identity import effective_reviewed_sha, full_sha from ocr_toolkit.review_range import ReviewRange, admit_native_range, parse_range_payload from ocr_toolkit.review_receipt import ( @@ -993,6 +1004,42 @@ def verified_partial_repository_coverage( return actual +def verified_review_coverage( + result: dict[str, Any], identity: ReceiptReviewIdentity +) -> ReviewCoverage: + """Rebuild the full ordinary diff and selection before any GitLab write.""" + + if identity.diff_base_sha is None: + raise RepositoryEvidenceError("ordinary review has no original diff identity") + reader = GitRepositoryReader(Path.cwd()) + plan = plan_review_input(reader, identity.diff_base_sha, identity.source_sha) + if plan.changes: + raise RepositoryEvidenceError("ordinary review receipt contains a changed gitlink") + projection = make_gitlink_projection(reader, plan) + metadata = result.get(TOOLKIT_RESULT_KEY) + publication = metadata.get("publication") if isinstance(metadata, dict) else None + filtered = isinstance(publication, dict) and publication.get("state") == "publication-filtered" + has_selection_proof = TOOLKIT_REVIEW_SELECTION_KEY in result + if filtered or has_selection_proof: + selection = selection_from_review_proof(projection, result) + else: + selection = selection_from_manifest(projection, result) + if ( + not filtered + and qualify_review_manifest(projection, selection, result) != has_selection_proof + ): + raise RepositoryEvidenceError("OCR ordinary selection proof is unexpected") + try: + actual = coverage_from_selection(projection, selection) + claimed = parse_review_coverage(metadata["review_coverage"]) + except (KeyError, TypeError, ReviewCoverageError) as exc: + raise RepositoryEvidenceError("ordinary review coverage is invalid") from exc + if claimed != actual: + raise RepositoryEvidenceError("ordinary review coverage disagrees with Git and OCR") + verify_gitlink_projection(reader, projection) + return actual + + def verified_no_model_repository_coverage(status: PreExecutionStatus) -> RepositoryCoverage: """Rebuild a path-free gitlink-only advisory before publishing it.""" @@ -1146,6 +1193,20 @@ def _post_results(config: GitLabConfig, result: dict[str, Any], *, include_analy file=sys.stderr, ) return 1 + ordinary_coverage: ReviewCoverage | None = None + if ( + receipt_identity is not None + and receipt_identity.schema_version == TOOLKIT_RESULT_SCHEMA_VERSION + ): + try: + ordinary_coverage = verified_review_coverage(result, receipt_identity) + except (RepositoryEvidenceError, OSError) as exc: + print( + f"Ordinary review coverage could not be revalidated ({exc}); no merge-request " + "note was written. Previous review preserved.", + file=sys.stderr, + ) + return 1 constrained_target = unprotected_target_limitation(toolkit_metadata) policy_anchor_sha = protected_policy_anchor_sha(toolkit_metadata) publication = toolkit_metadata.get("publication") if toolkit_metadata is not None else None @@ -1191,6 +1252,11 @@ def _post_results(config: GitLabConfig, result: dict[str, Any], *, include_analy outcome = parse_result_outcome(result) except OcrResultContractError as exc: return invalid_ocr_schema_exit(config, str(exc)) + if ordinary_coverage is not None and outcome.manifest_present: + outcome = replace(outcome, excluded_count=ordinary_coverage.excluded) + if readback_omitted := readback_omitted_findings(result): + outcome = replace(outcome, publication_incomplete=True) + print(f"Omitted {readback_omitted} finding(s) with redacted locations at readback.") outcome_message = clean_text(result.get("message")) if not isinstance(comments_value, list): @@ -1261,16 +1327,21 @@ def _post_results(config: GitLabConfig, result: dict[str, Any], *, include_analy "suppressed by the reviewer." ) carried_forward_count = 0 - if publication_state == "publication-filtered": + if preserves_previous_findings(outcome, receipt_identity): comments, carried_forward_count = filter_previously_published_comments( - comments, previous_bot_comment_refs + comments, previous_bot_comment_refs, review_comments=approval_comments ) if carried_forward_count: print( f"Preserved {carried_forward_count} matching finding(s) from the previous " "OCR review instead of publishing duplicates." ) - dlp_signal = publication_dlp_signal(publication, carried_forward_comments=carried_forward_count) + dlp_signal = publication_dlp_signal( + publication, + carried_forward_comments=( + carried_forward_count if publication_state == "publication-filtered" else 0 + ), + ) dlp_details = format_publication_dlp_details(dlp_signal) if dlp_signal is not None: print( @@ -1305,11 +1376,17 @@ def _post_results(config: GitLabConfig, result: dict[str, Any], *, include_analy reviewed_commit = receipt_sha or reviewed_sha() publication_lifecycle: GitLabMergeRequestLifecycle | None = None summary_status = ( - "publication-filtered" - if publication_state == "publication-filtered" - and summary_outcome.kind in {"clean", "warning"} + "skipped" + if summary_outcome.kind == "skipped" else "budget_exceeded" if summary_outcome.budget_exceeded + else "partial" + if summary_outcome.excluded_count + or summary_outcome.waived_count + or (ordinary_coverage is not None and summary_outcome.reused_count) + else "publication-filtered" + if publication_state == "publication-filtered" + and summary_outcome.kind in {"clean", "warning"} else summary_outcome.kind ) reviewer_guide = format_reviewer_guide( @@ -1317,6 +1394,8 @@ def _post_results(config: GitLabConfig, result: dict[str, Any], *, include_analy omitted_count, outcome_status=summary_status, coverage_summary=summary_outcome.coverage_summary, + readback_omitted_count=readback_omitted, + carried_forward_count=carried_forward_count, ) if publishable_comment_count == 0: @@ -1341,6 +1420,7 @@ def render_no_comments_summary(approval_result: ApprovalResult) -> str: inline_count=0, fallback_count=0, warning_count=len(warnings), + readback_omitted_count=readback_omitted, comments=(), tool_calls_summary=tool_calls_summary, mcp_usage_summary=mcp_usage_summary, @@ -1363,8 +1443,10 @@ def render_no_comments_summary(approval_result: ApprovalResult) -> str: else "" ), coverage_diagnostics=coverage_diagnostics, + coverage_outcome=summary_outcome, warnings=warnings, suppressed_count=suppressed_count, + carried_forward_count=carried_forward_count, approval_result=approval_result, unprotected_target=constrained_target, protected_policy_anchor_sha=policy_anchor_sha, @@ -1580,6 +1662,7 @@ def render_findings_summary(approval_result: ApprovalResult) -> str: warning_count=len(warnings), comments=comments, omitted_count=omitted_count, + readback_omitted_count=readback_omitted, tool_calls_summary=tool_calls_summary, mcp_usage_summary=mcp_usage_summary, token_usage_summary=token_usage_summary, @@ -1602,8 +1685,10 @@ def render_findings_summary(approval_result: ApprovalResult) -> str: else "" ), coverage_diagnostics=coverage_diagnostics, + coverage_outcome=summary_outcome, warnings=warnings, suppressed_count=suppressed_count, + carried_forward_count=carried_forward_count, approval_result=approval_result, unprotected_target=constrained_target, protected_policy_anchor_sha=policy_anchor_sha, @@ -1655,6 +1740,26 @@ def render_findings_summary(approval_result: ApprovalResult) -> str: return approval_exit +def preserves_previous_findings( + outcome: ReviewOutcome, review_identity: ReceiptReviewIdentity | None +) -> bool: + """Share the prior finding policy between carry-forward and cleanup.""" + + return ( + outcome.kind == "partial" + or outcome.publication_incomplete + or ( + review_identity is not None + and ( + outcome.excluded_count > 0 + or outcome.waived_count > 0 + or outcome.reused_count > 0 + or review_identity.schema_version == PARTIAL_TOOLKIT_RESULT_SCHEMA_VERSION + ) + ) + ) + + def finalize_previous_review_state( config: GitLabConfig, previous_refs: BotCommentRefs, @@ -1667,13 +1772,10 @@ def finalize_previous_review_state( ) -> bool: """Replace prior notes only after a complete outcome; preserve them for partial coverage.""" + preserve_findings = preserves_previous_findings(outcome, review_identity) if review_identity is not None: if transaction is None: raise ValueError("current-receipt cleanup requires the posting transaction") - partial_effective = ( - outcome.kind == "partial" - or review_identity.schema_version == PARTIAL_TOOLKIT_RESULT_SCHEMA_VERSION - ) cleanup_started = False def remove_if_current(delete: Callable[..., bool], *args: object) -> bool: @@ -1705,7 +1807,7 @@ def remove_if_current(delete: Callable[..., bool], *args: object) -> bool: return False return True - if partial_effective: + if preserve_findings: note_ids = previous_refs.summary_plain_note_ids draft_ids = previous_refs.summary_draft_note_ids discussion_refs: list[tuple[str, int]] = [] @@ -1732,17 +1834,17 @@ def remove_if_current(delete: Callable[..., bool], *args: object) -> bool: for note_id in draft_ids: if not remove_if_current(gitlab_api.delete_draft_note, note_id): return False - if partial_effective: + if preserve_findings: for note_id in previous_refs.terminal_plain_note_ids: if not remove_if_current(gitlab_api.delete_plain_note, note_id): return False - if not partial_effective: + if not preserve_findings: for discussion_id in previous_refs.discussions_to_resolve: if not remove_if_current(resolve_discussion, discussion_id): return False return True - if outcome.kind == "partial": + if preserve_findings: if publication_dlp_state(publication) == "publication-filtered": original = publication["original"] coverage = "complete" if original["outcome"] in {"clean", "warning"} else "incomplete" diff --git a/src/ocr_toolkit/preflight.py b/src/ocr_toolkit/preflight.py index f06a3923..5fc50b49 100644 --- a/src/ocr_toolkit/preflight.py +++ b/src/ocr_toolkit/preflight.py @@ -58,7 +58,7 @@ "Accept": "application/json", "User-Agent": "open-code-review-ci-preflight/1.0", } -RECOMMENDED_OCR_VERSION = "1.14.5" +RECOMMENDED_OCR_VERSION = "1.14.6" SUPPORTED_OCR_VERSIONS = ( "1.14.0", "1.14.1", @@ -66,6 +66,7 @@ "1.14.3", "1.14.4", "1.14.5", + "1.14.6", ) DEPRECATED_OCR_VERSIONS = () # Retain the public constant as the recommended pin, not as the runtime acceptance policy. diff --git a/src/ocr_toolkit/providers/gitlab_discussions.py b/src/ocr_toolkit/providers/gitlab_discussions.py index d545ea09..a127c4df 100644 --- a/src/ocr_toolkit/providers/gitlab_discussions.py +++ b/src/ocr_toolkit/providers/gitlab_discussions.py @@ -278,7 +278,12 @@ def _project_discussions( ): omitted += 1 continue - checked = check_text(note.get("body"), budgets=policy.budgets, forbidden=forbidden) + checked = check_text( + note.get("body"), + budgets=policy.budgets, + model_egress=True, + forbidden=forbidden, + ) if not checked.admitted or checked.text is None: omitted += 1 dlp_rejected += int(checked.reason != "limit") diff --git a/src/ocr_toolkit/providers/gitlab_remediation.py b/src/ocr_toolkit/providers/gitlab_remediation.py index 0c98857f..157936e2 100644 --- a/src/ocr_toolkit/providers/gitlab_remediation.py +++ b/src/ocr_toolkit/providers/gitlab_remediation.py @@ -142,7 +142,12 @@ def project_remediation_threads( root_anchor, outdated, anchor_invalid = anchor(root.get("position"), source_sha=source_sha) resolved = root.get("resolved") is True body = root.get("body") - checked_root = check_text(body, budgets=policy.budgets, forbidden=forbidden) + checked_root = check_text( + body, + budgets=policy.budgets, + model_egress=True, + forbidden=forbidden, + ) visible_root = ( _visible_root_text(checked_root.text) if checked_root.admitted and isinstance(checked_root.text, str) @@ -151,6 +156,7 @@ def project_remediation_threads( visible_checked = check_text( visible_root, budgets=policy.budgets, + model_egress=True, forbidden=forbidden, ) root_dlp_rejected = not checked_root.admitted or not visible_checked.admitted @@ -216,7 +222,12 @@ def project_remediation_threads( note.get("position"), source_sha=source_sha ) reply_resolved = note.get("resolved") is True - checked = check_text(note_body, budgets=policy.budgets, forbidden=forbidden) + checked = check_text( + note_body, + budgets=policy.budgets, + model_egress=True, + forbidden=forbidden, + ) if ( reply_created is None or reply_updated is None diff --git a/src/ocr_toolkit/providers/local.py b/src/ocr_toolkit/providers/local.py index 78119345..1d66bcac 100644 --- a/src/ocr_toolkit/providers/local.py +++ b/src/ocr_toolkit/providers/local.py @@ -5,6 +5,7 @@ import os import secrets from collections.abc import Iterator +from dataclasses import replace from pathlib import Path from typing import TextIO @@ -26,9 +27,26 @@ def local_summary(report: ReviewReport) -> str: + """Render common review facts for private Markdown.""" + incomplete = report.incremental is not None and report.incremental.incomplete unconfirmed = len(report.incremental.unconfirmed_files) if report.incremental else 0 - """Render common facts, with neither forge publication claims nor remote badges.""" + reused_paths = {file.path for file in report.incremental.files} if report.incremental else set() + reused_exclusions = sum( + entry.path in reused_paths and entry.reason == "user_exclude" + for entry in report.outcome.excluded_items + ) + effective = replace( + report.outcome, excluded_count=report.outcome.excluded_count - reused_exclusions + ) + unreviewed = report.diagnostics.unreviewed_file_count(effective) + if unconfirmed: + # Show native and incremental counts separately when paths can overlap. + unreviewed = ( + None + if effective.excluded_count or effective.waived_count or effective.failed_count + else (unreviewed or 0) + unconfirmed + ) lines = [ "## Open Code Review", @@ -37,17 +55,22 @@ def local_summary(report: ReviewReport) -> str: findings=FindingVisibility(count=len(report.comments)), warning_count=len(report.warnings), outcome_status=( - "partial" - if incomplete and report.outcome.kind in {"clean", "warning"} + effective.kind + if effective.kind == "failed" + or (effective.kind == "skipped" and not reused_exclusions) + else "budget_exceeded" + if effective.budget_exceeded + else "partial" + if effective.excluded_count or effective.waived_count or incomplete else "admission-filtered" if admission_dlp_state(report.publication) == "publication-filtered" - and report.outcome.kind in {"clean", "warning"} - else report.outcome.status + and effective.kind in {"clean", "warning"} + else "complete" + if effective.kind == "skipped" + else effective.status ), outcome_message=report.outcome_message, - unreviewed_file_count=(report.diagnostics.file_count or 0) + unconfirmed - if unconfirmed - else report.diagnostics.file_count, + unreviewed_file_count=unreviewed, ), ] if report.failure_stage is not None: @@ -76,12 +99,14 @@ def local_summary(report: ReviewReport) -> str: ["", "### Incremental review", "", f"Toolkit coverage: reused {len(reuse.files)}."] ) if reuse.full_reason: - lines.append(f"Full review. {reuse.full_reason}") + lines.append(f"Full review selected. {reuse.full_reason}") if reuse.baseline_qualified_files is not None: lines.append( "Files with verified dependencies for the next incremental review " f"{reuse.baseline_qualified_files}." ) + if reuse.baseline_groups is not None: + lines.extend(reuse.baseline_groups.lines()) if reuse.dropped_findings: lines.append( f"Prior findings dropped during current validation: {reuse.dropped_findings}." diff --git a/src/ocr_toolkit/reporting/dlp.py b/src/ocr_toolkit/reporting/dlp.py index 0a5e169e..025da706 100644 --- a/src/ocr_toolkit/reporting/dlp.py +++ b/src/ocr_toolkit/reporting/dlp.py @@ -7,6 +7,7 @@ from ocr_toolkit.ocr_result import MAX_TOOLKIT_MCP_USAGE_COUNT from ocr_toolkit.result_contract import ( FORBIDDEN_SOURCE_CLASSES, + MAX_COVERAGE_RECORDS, OcrResultContractError, ReviewOutcome, ) @@ -55,9 +56,13 @@ def format_dlp_admission(publication: Any) -> str: line = ( f"- DLP admission: filtered; retained {retained['comments']} finding(s), " f"{retained['warnings']} warning(s); omitted {omitted['comments']} finding(s), " - f"{omitted['warnings']} warning(s), {field_description}; reasons: {reasons}" - + format_forbidden_sources(publication) + f"{omitted['warnings']} warning(s), {field_description}" ) + if reasons: + line += f"; reasons: {reasons}" + else: + line += "; native manifest omitted after private field sanitization" + line += format_forbidden_sources(publication) if versioned: private = publication["private_sanitization"] line += f"; private-only sanitization: {private['fields']} field(s)" @@ -92,6 +97,7 @@ def _dlp_state(value: Any, *, allow_unknown_coverage: bool) -> str | None: """Validate closed DLP facts with an explicit coverage-knowledge boundary.""" versioned = isinstance(value, dict) and value.get("schema") == "ocr.publication/v2" + private_fields = 0 if isinstance(value, dict) and "source_attribution" in value: attribution = value["source_attribution"] if ( @@ -104,7 +110,7 @@ def _dlp_state(value: Any, *, allow_unknown_coverage: bool) -> str | None: type(v) is not int or not 0 <= v <= MAX_TOOLKIT_MCP_USAGE_COUNT for v in attribution["counts"].values() ) - or value.get("state") not in {"private-sanitized", "publication-filtered"} + or value.get("state") not in ("private-sanitized", "publication-filtered") ): return None private_value = value.get("private_sanitization") @@ -158,6 +164,7 @@ def _dlp_state(value: Any, *, allow_unknown_coverage: bool) -> str | None: ) if value.get("state") != "publication-filtered": return None + private_fields = private["fields"] if set(value) != { "schema", "state", @@ -225,7 +232,6 @@ def _dlp_state(value: Any, *, allow_unknown_coverage: bool) -> str | None: original = value.get("original") if ( not _valid_dlp_reason_counts(reason_counts) - or not any(reason_counts.values()) or not isinstance(retained, dict) or set(retained) != {"comments", "warnings"} or not isinstance(omitted, dict) @@ -238,8 +244,21 @@ def _dlp_state(value: Any, *, allow_unknown_coverage: bool) -> str | None: for count in counts.values() ) or not isinstance(original, dict) - or set(original) != {"outcome", "selected", "completed", "reused", "failed", "waived"} - or original.get("outcome") not in {"clean", "warning", "partial", "failed", "skipped"} + or set(original) + not in ( + {"outcome", "selected", "completed", "reused", "failed", "waived"}, + { + "outcome", + "selected", + "completed", + "reused", + "failed", + "waived", + "excluded", + }, + ) + or not isinstance(original.get("outcome"), str) + or original["outcome"] not in {"clean", "warning", "partial", "failed", "skipped"} or any( not isinstance(original.get(field), int) or isinstance(original.get(field), bool) @@ -248,11 +267,16 @@ def _dlp_state(value: Any, *, allow_unknown_coverage: bool) -> str | None: ) ): return None + if not any(reason_counts.values()) and (not private_fields or any(omitted.values())): + return None selected = original["selected"] completed = original["completed"] reused = original["reused"] failed = original["failed"] waived = original["waived"] + excluded = original.get("excluded", 0) + if type(excluded) is not int or not 0 <= excluded <= MAX_COVERAGE_RECORDS: + return None outcome = original["outcome"] derived_outcomes = {"failed"} | ( {"skipped"} @@ -263,7 +287,10 @@ def _dlp_state(value: Any, *, allow_unknown_coverage: bool) -> str | None: if failed == selected else {"partial"} ) - if allow_unknown_coverage and selected == completed == reused == failed == waived == 0: + if ( + allow_unknown_coverage + and selected == completed == reused == failed == waived == excluded == 0 + ): derived_outcomes |= {"clean", "warning", "partial"} if selected != completed + reused + failed + waived or outcome not in derived_outcomes: return None @@ -315,7 +342,8 @@ def _original_outcome(outcome: ReviewOutcome, publication: Any) -> ReviewOutcome counts = { field: original[field] for field in ("selected", "completed", "reused", "failed", "waived") } - manifest_present = any(counts.values()) + excluded = original.get("excluded", 0) + manifest_present = any(counts.values()) or excluded > 0 status = { "clean": "complete" if manifest_present else "success", "warning": "completed_with_warnings", @@ -333,6 +361,7 @@ def _original_outcome(outcome: ReviewOutcome, publication: Any) -> ReviewOutcome reused_count=counts["reused"], failed_count=counts["failed"], waived_count=counts["waived"], + excluded_count=excluded, ) diff --git a/src/ocr_toolkit/reporting/incremental.py b/src/ocr_toolkit/reporting/incremental.py index 38569a26..f44c6ba4 100644 --- a/src/ocr_toolkit/reporting/incremental.py +++ b/src/ocr_toolkit/reporting/incremental.py @@ -6,6 +6,51 @@ from typing import Any RESULT_KEY = "toolkit_incremental" +BASELINE_REASONS = frozenset( + { + "comment_attribution", + "diagram", + "diff_read", + "evidence_action", + "evidence_counters", + "failed_tool_call", + "finding_admission", + "group_partition", + "invalid_arguments", + "llm_error", + "missing_main_request", + "narrowed_context", + "native_counters", + "native_trace", + "no_evidence_summary", + "read_verification", + "search_tool", + "unsupported_tool", + } +) + + +@dataclass(frozen=True, slots=True) +class BaselineGroups: + """Count each reason once per affected group.""" + + total: int + qualified: int + reasons: tuple[tuple[str, int], ...] + + def payload(self) -> dict[str, object]: + return { + "total": self.total, + "qualified": self.qualified, + "reasons": dict(self.reasons), + } + + def lines(self) -> tuple[str, ...]: + summary = f"Incremental baseline: {self.total} groups, {self.qualified} qualified." + if not self.reasons: + return (summary,) + reasons = ", ".join(f"{reason} {count}" for reason, count in self.reasons) + return summary, f"Unqualified groups by reason: {reasons}." @dataclass(frozen=True, slots=True) @@ -31,6 +76,7 @@ class IncrementalReport: full_reason: str = "" baseline_qualified_files: int | None = None unconfirmed_files: tuple[ReusedFile, ...] = () + baseline_groups: BaselineGroups | None = None @property def incomplete(self) -> bool: @@ -42,6 +88,7 @@ def compact_payload(self, *, native_findings_omitted: int = 0) -> dict[str, obje "reused_count": len(self.files), "dropped_findings": self.dropped_findings, "details_in_report": True, + **({"full_reason": self.full_reason} if self.full_reason else {}), **({"status": "incomplete"} if self.incomplete or native_findings_omitted else {}), **( {"native_findings_omitted": native_findings_omitted} @@ -62,6 +109,11 @@ def payload(self) -> dict[str, object]: "dropped_findings": self.dropped_findings, "full_reason": self.full_reason or None, "baseline_qualified_files": self.baseline_qualified_files, + **( + {"baseline_groups": self.baseline_groups.payload()} + if self.baseline_groups is not None + else {} + ), "reused": [file.payload() for file in self.files], **( { diff --git a/src/ocr_toolkit/reporting/outcome.py b/src/ocr_toolkit/reporting/outcome.py index ec306527..1f136397 100644 --- a/src/ocr_toolkit/reporting/outcome.py +++ b/src/ocr_toolkit/reporting/outcome.py @@ -12,7 +12,9 @@ class FindingVisibility: count: int published: bool = False omitted: int = 0 + readback_omitted: int = 0 suppressed: int = 0 + carried_forward: int = 0 def review_outcome_line( @@ -30,7 +32,12 @@ def review_outcome_line( outcome_status == "partial" and "budget" in outcome_message.casefold() ) partial_result = outcome_status in {"partial", "completed_with_errors", "budget_exceeded"} - has_finding_state = findings.count > 0 or findings.omitted > 0 or findings.suppressed > 0 + has_finding_state = ( + findings.count > 0 + or findings.omitted > 0 + or findings.suppressed > 0 + or findings.carried_forward > 0 + ) if outcome_status == "skipped": marker, status_text = "ℹ️", "Review skipped" # noqa: RUF001 result_text = "no supported files changed" @@ -44,6 +51,8 @@ def review_outcome_line( marker, status_text = "⚠️", "Review incomplete" elif outcome_status == "publication-filtered" or outcome_status == "admission-filtered": marker, status_text = "⚠️", "Analysis complete; output incomplete" + elif findings.readback_omitted: + marker, status_text = "⚠️", "Review complete; output incomplete" elif outcome_status in {"warning", "completed_with_warnings"} or warning_count: marker, status_text = "⚠️", "Review complete with warnings" elif has_finding_state: @@ -57,11 +66,11 @@ def review_outcome_line( result_text = f"{findings.count} {noun}{delivered}" if partial_result: result_text += " from reviewed files" - elif findings.omitted: + elif findings.omitted or findings.readback_omitted: result_text = f"no findings{delivered}" if partial_result: result_text += " from reviewed files" - elif findings.suppressed: + elif findings.suppressed or findings.carried_forward: result_text = f"no new findings{delivered}" if partial_result: result_text += " from reviewed files" @@ -73,9 +82,15 @@ def review_outcome_line( if findings.omitted: noun = "finding" if findings.omitted == 1 else "findings" result_text += f"; {findings.omitted} {noun} omitted by posting limit" + if findings.readback_omitted: + noun = "finding" if findings.readback_omitted == 1 else "findings" + result_text += f"; {findings.readback_omitted} {noun} withheld after location redaction" if findings.suppressed: noun = "finding" if findings.suppressed == 1 else "findings" result_text += f"; {findings.suppressed} {noun} matched prior reviewer decisions" + if findings.carried_forward: + noun = "finding" if findings.carried_forward == 1 else "findings" + result_text += f"; {findings.carried_forward} matching previous {noun} retained" if partial_result and unreviewed_file_count is not None: noun = "file" if unreviewed_file_count == 1 else "files" result_text += f"; {unreviewed_file_count} {noun} not reviewed" diff --git a/src/ocr_toolkit/reporting/result.py b/src/ocr_toolkit/reporting/result.py index b2f10bae..2969b0a5 100644 --- a/src/ocr_toolkit/reporting/result.py +++ b/src/ocr_toolkit/reporting/result.py @@ -79,6 +79,22 @@ def file_count(self) -> int | None: return self.unique_file_count if self.unique_file_count > 0 and self.invalid == 0 else None + def unreviewed_file_count(self, outcome: ReviewOutcome) -> int | None: + """Count excluded, failed, and waived files when their paths are known.""" + + if not (outcome.waived_count or outcome.excluded_count): + return self.file_count + selected_paths = outcome.unreviewed_selected_paths + if selected_paths is None: + return ( + None + if outcome.failed_count or outcome.waived_count or self.failed_total + else outcome.excluded_count + ) + if any(not _safe_repository_path(path) for path in selected_paths): + return None + return len(selected_paths) + outcome.excluded_count + def _safe_repository_path(value: object) -> str: """Return one normalized repository-relative path or an empty value.""" @@ -91,6 +107,8 @@ def _safe_repository_path(value: object) -> str: return "" if any(character == "\x7f" or ord(character) < 32 for character in value): return "" + if redact_sensitive(value) != value: + return "" return path.as_posix() diff --git a/src/ocr_toolkit/result_contract.py b/src/ocr_toolkit/result_contract.py index 7b76a6c3..90ad46ba 100644 --- a/src/ocr_toolkit/result_contract.py +++ b/src/ocr_toolkit/result_contract.py @@ -22,6 +22,20 @@ MANIFEST_SCHEMA = "ocr.run-manifest/v1" MAX_COVERAGE_RECORDS = 10_000 MAX_ITEM_ID_CHARS = 256 +MAX_COVERAGE_PATH_CHARS = 4_096 +EXCLUSION_REASONS = frozenset( + { + "binary", + "default_path", + "deleted", + "gitignore", + "provider_directory", + "secret_exclude", + "too_large", + "unsupported_ext", + "user_exclude", + } +) FAILURE_CLASSES = { "provider", "timeout", @@ -70,6 +84,14 @@ class CoverageFailure: reason: object +@dataclass(frozen=True, slots=True) +class CoverageExclusion: + """Keep the native exclusion reason and path for local reuse reconciliation.""" + + path: str + reason: str + + @dataclass(frozen=True, slots=True) class ReviewOutcome: """Expose one validated OCR outcome without provider-specific branching.""" @@ -83,7 +105,11 @@ class ReviewOutcome: reused_count: int = 0 failed_count: int = 0 waived_count: int = 0 + excluded_count: int = 0 failed_items: tuple[CoverageFailure, ...] = () + excluded_items: tuple[CoverageExclusion, ...] = () + unreviewed_selected_paths: tuple[str, ...] | None = None + publication_incomplete: bool = False @property def operational_partial(self) -> bool: @@ -107,11 +133,14 @@ def coverage_summary(self) -> str: if not self.manifest_present: return "" - return ( + summary = ( f"Coverage: selected {self.selected_count}; completed {self.completed_count}; " f"reused {self.reused_count}; failed {self.failed_count}; " f"waived {self.waived_count}." ) + if self.excluded_count: + summary = summary[:-1] + f"; excluded {self.excluded_count}." + return summary def _budget_exceeded(result: Mapping[str, Any]) -> bool: @@ -188,6 +217,44 @@ def _validate_waived_records(records: list[Mapping[str, Any]]) -> None: ) +def _validate_excluded_records( + records: list[Mapping[str, Any]], selected_records: list[Mapping[str, Any]] +) -> tuple[CoverageExclusion, ...]: + """Require closed reasons and disjoint path identity for native exclusions.""" + + selected_paths = { + path for record in selected_records if isinstance(path := record.get("path"), str) + } + excluded_paths: set[str] = set() + exclusions: list[CoverageExclusion] = [] + for index, record in enumerate(records): + path = record.get("path") + old_path = record.get("old_path") + reason = record.get("exclude_reason") + if ( + set(record) - {"old_path"} != {"item_id", "path", "exclude_reason"} + or not isinstance(path, str) + or not path + or len(path) > MAX_COVERAGE_PATH_CHARS + or ( + "old_path" in record + and ( + not isinstance(old_path, str) + or not 0 < len(old_path) <= MAX_COVERAGE_PATH_CHARS + or old_path == path + ) + ) + or path in selected_paths + or path in excluded_paths + or not isinstance(reason, str) + or reason not in EXCLUSION_REASONS + ): + raise OcrResultContractError(f"field 'manifest.coverage.excluded[{index}]' is invalid") + excluded_paths.add(path) + exclusions.append(CoverageExclusion(path, reason)) + return tuple(exclusions) + + def _manifest_outcome( status: str, manifest: Mapping[str, Any], budget_exceeded: bool ) -> ReviewOutcome: @@ -207,11 +274,15 @@ def _manifest_outcome( if not isinstance(coverage, Mapping): raise OcrResultContractError("field 'manifest.coverage' must be an object") - selected, _selected_records = _coverage_ids(coverage.get("selected"), "selected") + selected, selected_records = _coverage_ids(coverage.get("selected"), "selected") completed, _completed_records = _coverage_ids(coverage.get("completed"), "completed") reused, _reused_records = _coverage_ids(coverage.get("reused"), "reused") failed, failed_records = _coverage_ids(coverage.get("failed"), "failed") waived, waived_records = _coverage_ids(coverage.get("waived"), "waived") + excluded, excluded_records = _coverage_ids(coverage.get("excluded", []), "excluded") + + if selected.intersection(excluded): + raise OcrResultContractError("manifest selected and excluded coverage overlap") terminal_sets = (completed, reused, failed, waived) terminal_union: set[str] = set() @@ -226,6 +297,18 @@ def _manifest_outcome( budget_failure = _validate_failure_records(failed_records) _validate_waived_records(waived_records) + exclusions = _validate_excluded_records(excluded_records, selected_records) + selected_paths = { + record["item_id"]: path + for record in selected_records + if isinstance(path := record.get("path"), str) and path + } + unreviewed = failed | waived + unreviewed_selected_paths = ( + tuple(sorted({selected_paths[item_id] for item_id in unreviewed})) + if unreviewed <= selected_paths.keys() + else None + ) run_failure = manifest.get("run_failure") if run_failure is not None: @@ -274,15 +357,18 @@ def _manifest_outcome( reused_count=len(reused), failed_count=len(failed), waived_count=len(waived), + excluded_count=len(excluded), failed_items=tuple( CoverageFailure( item_id=str(record["item_id"]), - path=record.get("path"), + path=selected_paths.get(record["item_id"], record.get("path")), classification=str(record["classification"]), reason=record.get("reason"), ) for record in failed_records ), + excluded_items=exclusions, + unreviewed_selected_paths=unreviewed_selected_paths, ) diff --git a/src/ocr_toolkit/review_coverage.py b/src/ocr_toolkit/review_coverage.py new file mode 100644 index 00000000..bdcb2d2f --- /dev/null +++ b/src/ocr_toolkit/review_coverage.py @@ -0,0 +1,90 @@ +"""Closed path-free coverage for an immutable ordinary review diff.""" + +from __future__ import annotations + +from collections import Counter +from dataclasses import asdict, dataclass +from typing import Any, Literal + +from ocr_toolkit.evidence.gitlink_projection import ( + GitlinkProjection, + ReviewSelection, + review_selection_digest, +) +from ocr_toolkit.result_contract import EXCLUSION_REASONS, MAX_COVERAGE_RECORDS + +REVIEW_COVERAGE_SCHEMA = "ocr.review-coverage/v1" +ReviewCoverageState = Literal["complete", "partial"] + + +class ReviewCoverageError(ValueError): + """Reject an unsupported or inconsistent immutable-diff coverage claim.""" + + +@dataclass(frozen=True, slots=True) +class ReviewCoverage: + """Path-free immutable-diff counts and a digest of every selection decision.""" + + schema_version: str + state: ReviewCoverageState + changed: int + selected: int + excluded: int + exclusion_reasons: dict[str, int] + selection_sha256: str + + def payload(self) -> dict[str, object]: + return asdict(self) + + +def parse_review_coverage(value: Any) -> ReviewCoverage: + """Parse one exact current ordinary-review coverage receipt.""" + + if not isinstance(value, dict) or set(value) != set(ReviewCoverage.__dataclass_fields__): + raise ReviewCoverageError("review coverage has an unsupported shape") + if ( + value.get("schema_version") != REVIEW_COVERAGE_SCHEMA + or value.get("state") not in ("complete", "partial") + or any( + type(value.get(field)) is not int or not 0 <= value[field] <= MAX_COVERAGE_RECORDS + for field in ("changed", "selected", "excluded") + ) + or not isinstance(value.get("selection_sha256"), str) + or len(value["selection_sha256"]) != 64 + or any(character not in "0123456789abcdef" for character in value["selection_sha256"]) + ): + raise ReviewCoverageError("review coverage has invalid values") + reasons = value.get("exclusion_reasons") + if ( + not isinstance(reasons, dict) + or set(reasons) != EXCLUSION_REASONS + or any( + type(count) is not int or not 0 <= count <= MAX_COVERAGE_RECORDS + for count in reasons.values() + ) + or value["changed"] != value["selected"] + value["excluded"] + or value["excluded"] != sum(reasons.values()) + or (value["state"] == "complete") != (value["excluded"] == 0) + ): + raise ReviewCoverageError("review coverage counts are inconsistent") + return ReviewCoverage(**value) + + +def coverage_from_selection( + projection: GitlinkProjection, selection: ReviewSelection +) -> ReviewCoverage: + """Construct coverage only from a qualified immutable full-diff partition.""" + + reason_counts = Counter(exclusion.reason for exclusion in selection.excluded) + value = { + "schema_version": REVIEW_COVERAGE_SCHEMA, + "state": "partial" if selection.excluded else "complete", + "changed": len(projection.ordinary_diff), + "selected": len(selection.selected), + "excluded": len(selection.excluded), + "exclusion_reasons": { + reason: reason_counts.get(reason, 0) for reason in sorted(EXCLUSION_REASONS) + }, + "selection_sha256": review_selection_digest(projection, selection), + } + return parse_review_coverage(value) diff --git a/src/ocr_toolkit/review_receipt.py b/src/ocr_toolkit/review_receipt.py index 81106bcc..e6d5101e 100644 --- a/src/ocr_toolkit/review_receipt.py +++ b/src/ocr_toolkit/review_receipt.py @@ -11,6 +11,7 @@ from ocr_toolkit.evidence.invocation import MAX_CI_IDENTIFIER_CHARS from ocr_toolkit.evidence.mcp import COVERAGE_TOOL_NAME, SEARCH_TOOL_NAME, TOOL_NAME from ocr_toolkit.ocr_result import ( + HISTORICAL_TOOLKIT_RESULT_SCHEMA_VERSIONS, MAX_TOOLKIT_MCP_TOOL_NAME_CHARS, MAX_TOOLKIT_MCP_TOOLS_PER_SERVER, MAX_TOOLKIT_MCP_USAGE_COUNT, @@ -25,6 +26,7 @@ from ocr_toolkit.reporting.federation import valid_reconciliation from ocr_toolkit.repository_coverage import RepositoryCoverageError, parse_repository_coverage from ocr_toolkit.result_contract import OcrResultContractError +from ocr_toolkit.review_coverage import ReviewCoverageError, parse_review_coverage from ocr_toolkit.review_model import model_slug from ocr_toolkit.review_range import parse_range_payload @@ -35,7 +37,8 @@ RECEIPT_V12 = 12 RECEIPT_V13 = 13 RECEIPT_V14 = 14 -SUPPORTED_REVIEW_TUPLE_VERSIONS = frozenset({11, 12, 13, 14}) +RECEIPT_V15 = 15 +SUPPORTED_REVIEW_TUPLE_VERSIONS = frozenset({11, 12, 13, 14, 15}) _FEDERATION_SCHEMA_BY_RECEIPT_VERSION = { 9: "ocr.federation/v1", 10: "ocr.federation/v2", @@ -43,6 +46,7 @@ RECEIPT_V12: "ocr.federation/v2", RECEIPT_V13: "ocr.federation/v2", RECEIPT_V14: "ocr.federation/v2", + RECEIPT_V15: "ocr.federation/v2", } _PUBLICATION_SCHEMA_BY_RECEIPT_VERSION = { 9: None, @@ -51,6 +55,7 @@ RECEIPT_V12: "ocr.publication/v2", RECEIPT_V13: "ocr.publication/v2", RECEIPT_V14: "ocr.publication/v2", + RECEIPT_V15: "ocr.publication/v2", } UNPROTECTED_APPROVAL_REASON = ( "the GitLab target branch was unprotected; limited reviews are comment-only" @@ -254,9 +259,13 @@ def _parse_review_identity(review: Any, receipt_version: int) -> ReceiptReviewId schema_version=receipt_version, policy_sha=review["policy_sha"], ) - if receipt_version not in {RECEIPT_V11, RECEIPT_V12, RECEIPT_V13, RECEIPT_V14} or set( - review - ) not in { + if receipt_version not in { + RECEIPT_V11, + RECEIPT_V12, + RECEIPT_V13, + RECEIPT_V14, + RECEIPT_V15, + } or set(review) not in { _V11_REVIEW_KEYS, _V11_REVIEW_KEYS | {"ci_job_id"}, }: @@ -355,18 +364,23 @@ def automatic_approval_metadata_reason(toolkit_metadata: Any) -> str: } | ( {"review_model"} - if receipt_version in {RECEIPT_V13, RECEIPT_V14} + if receipt_version in {RECEIPT_V13, RECEIPT_V14, RECEIPT_V15} and model_slug(toolkit_metadata.get("review_model")) else set() ) | ( {"analysis_hmac_sha256"} - if receipt_version in {RECEIPT_V13, RECEIPT_V14} + if receipt_version in {RECEIPT_V13, RECEIPT_V14, RECEIPT_V15} and _sha256(toolkit_metadata.get("analysis_hmac_sha256")) else set() ) | ({"repository_coverage"} if receipt_version in {RECEIPT_V12, RECEIPT_V14} else set()) - | ({"range", "diagram"} if receipt_version in {RECEIPT_V13, RECEIPT_V14} else set()) + | ({"review_coverage"} if receipt_version == RECEIPT_V15 else set()) + | ( + {"range", "diagram"} + if receipt_version in {RECEIPT_V13, RECEIPT_V14, RECEIPT_V15} + else set() + ) ): return invalid @@ -375,13 +389,13 @@ def automatic_approval_metadata_reason(toolkit_metadata: Any) -> str: return invalid current_range = None diagram = None - if receipt_version in {RECEIPT_V13, RECEIPT_V14}: + if receipt_version in {RECEIPT_V13, RECEIPT_V14, RECEIPT_V15}: try: current_range = parse_range_payload(toolkit_metadata["range"]) diagram = parse_diagram_payload(toolkit_metadata["diagram"], review_range=current_range) except (OcrResultContractError, DiagramError): return invalid - if receipt_version == RECEIPT_V14 and current_range is None: + if receipt_version in {RECEIPT_V14, RECEIPT_V15} and current_range is None: return invalid if current_range is not None and (current_range.base, current_range.head) != ( review_identity.diff_base_sha, @@ -395,6 +409,12 @@ def automatic_approval_metadata_reason(toolkit_metadata: Any) -> str: ) except RepositoryCoverageError: return invalid + review_coverage = None + if receipt_version == RECEIPT_V15: + try: + review_coverage = parse_review_coverage(toolkit_metadata["review_coverage"]) + except ReviewCoverageError: + return invalid context = toolkit_metadata.get("context") if not isinstance(context, dict) or set(context) != { @@ -616,12 +636,32 @@ def automatic_approval_metadata_reason(toolkit_metadata: Any) -> str: cleanup = toolkit_metadata.get("cleanup") original = publication.get("original") if ( - receipt_version not in {RECEIPT_V13, RECEIPT_V14} + receipt_version not in {RECEIPT_V13, RECEIPT_V14, RECEIPT_V15} and isinstance(original, dict) and "operational_partial" in original ): return invalid + if ( + receipt_version in HISTORICAL_TOOLKIT_RESULT_SCHEMA_VERSIONS + and isinstance(original, dict) + and "excluded" in original + ): + return invalid publication_state = publication_dlp_state(publication) + if publication_state == "publication-filtered" and ( + ( + receipt_version in HISTORICAL_TOOLKIT_RESULT_SCHEMA_VERSIONS + and not any(publication["reason_counts"].values()) + ) + or ( + review_coverage is not None + and ( + original["selected"] != review_coverage.selected + or original.get("excluded") != review_coverage.excluded + ) + ) + ): + return invalid failure_state = tool_execution.get("state") if isinstance(tool_execution, dict) else None failed_tools = tool_execution.get("failed") if isinstance(tool_execution, dict) else None if ( @@ -681,15 +721,17 @@ def automatic_approval_metadata_reason(toolkit_metadata: Any) -> str: return "mutable review context was admitted" if external and federation["state"] == "degraded": return "external MCP use was advisory, incomplete or accounting-mismatched" - if receipt_version in {RECEIPT_V13, RECEIPT_V14} and current_range is None: + if receipt_version in {RECEIPT_V13, RECEIPT_V14, RECEIPT_V15} and current_range is None: return "native review range identity was not verified" if receipt_version in {RECEIPT_V12, RECEIPT_V14}: return "changed Git submodule pointers were not reviewed; automatic approval is unavailable" + if review_coverage is not None and review_coverage.state == "partial": + return "one or more immutable changed paths were excluded from review" return "" def toolkit_receipt_is_valid(toolkit_metadata: Any) -> bool: - """Return whether metadata is an exact current receipt, including valid blockers.""" + """Return whether metadata matches its supported receipt schema.""" return automatic_approval_metadata_reason(toolkit_metadata) != INVALID_APPROVAL_RECEIPT_REASON diff --git a/src/ocr_toolkit/review_runner.py b/src/ocr_toolkit/review_runner.py index 7477871e..a29fd32e 100644 --- a/src/ocr_toolkit/review_runner.py +++ b/src/ocr_toolkit/review_runner.py @@ -99,14 +99,17 @@ from ocr_toolkit.evidence.collect import collect_repository_evidence from ocr_toolkit.evidence.gitlink_projection import ( GitlinkProjection, + PreviewExclusion, RawDiffEntry, + ReviewSelection, gitlink_selection_proof, make_gitlink_projection, - qualify_gitlink_manifest, - qualify_gitlink_preview, + qualify_review_manifest, + qualify_review_preview, + review_selection_proof, verify_gitlink_projection, ) -from ocr_toolkit.evidence.gitlinks import changed_gitlinks, plan_gitlink_input +from ocr_toolkit.evidence.gitlinks import changed_gitlinks, plan_gitlink_input, plan_review_input from ocr_toolkit.evidence.invocation import collect_invocation_evidence from ocr_toolkit.evidence.mcp import ( COVERAGE_TOOL_NAME, @@ -152,6 +155,7 @@ TOOLKIT_PRIVATE_DIAGNOSTIC_KEY, TOOLKIT_RESULT_KEY, TOOLKIT_RESULT_SCHEMA_VERSION, + TOOLKIT_REVIEW_SELECTION_KEY, OcrResultMalformed, OcrResultMissing, OcrResultTooLarge, @@ -212,6 +216,7 @@ from ocr_toolkit.providers.local_config import validate_local_context from ocr_toolkit.reporting.federation import reconcile as reconcile_federation from ocr_toolkit.reporting.incremental import RESULT_KEY as INCREMENTAL_RESULT_KEY +from ocr_toolkit.reporting.incremental import IncrementalReport from ocr_toolkit.reporting.metadata import format_token_usage_summary from ocr_toolkit.reporting.model import ( ExecutionFacts, @@ -224,6 +229,7 @@ from ocr_toolkit.result_contract import OcrResultContractError, ReviewOutcome, parse_result_outcome from ocr_toolkit.result_diagnostics import ResultDiagnostic, result_diagnostic from ocr_toolkit.result_usage import normalize_token_usage, token_usage_mapping +from ocr_toolkit.review_coverage import ReviewCoverageError, coverage_from_selection from ocr_toolkit.review_debug import DebugBundle, DebugStatus from ocr_toolkit.review_identity import validate_detached_merge_request_pipeline from ocr_toolkit.review_model import admitted_model @@ -285,6 +291,9 @@ MAX_TOOL_FAILURE_ARGUMENT_CHARS = 32_768 MAX_TOOL_FAILURE_ARGUMENT_BYTES = 131_072 MAX_TOOL_FAILURE_LOG_FIELD_CHARS = 500 +FEDERATED_INCREMENTAL_REASON = ( + "Incremental reuse is unavailable while governed external MCP tools are configured." +) class ReviewRunnerError(Exception): @@ -379,6 +388,7 @@ class BackgroundQualification: advisory: OcrToolkitAdvisory | None = None operator_notices: tuple[str, ...] = () selected_diff: tuple[RawDiffEntry, ...] = () + excluded_diff: tuple[PreviewExclusion, ...] = () preview_stdout: bytes = b"" @@ -937,6 +947,7 @@ def _dlp_reasons( allow_opaque_code: bool = False, code_context: CodeTextContext | None = None, sink: TextSink = TextSink.PROSE, + enabled: bool = True, debug: DebugBundle | None = None, path: tuple[object, ...] = (), action: str = "detect-sink", @@ -976,7 +987,7 @@ def _dlp_reasons( allow_opaque_code=allow_opaque_code, code_context=code_context, sink=sink, - enabled=True, + enabled=enabled, ) unsafe_key = ( is_key @@ -1012,6 +1023,84 @@ def _dlp_reasons( return reasons +def _project_disabled_publication_prose( + payload: dict[str, object], + *, + budgets: TextBudgets, + debug: DebugBundle | None = None, +) -> dict[str, object]: + """Apply mandatory inert presentation without semantic material rejection.""" + + matcher = ForbiddenMatcher.compile(()) + prepared: dict[tuple[object, ...], str] = {} + for path, value in prose_slots(payload): + try: + bounded_prose_text(value, budgets) + except (RepresentationLimit, UnicodeError, ValueError) as exc: + if debug is not None: + debug.decision( + path=path, + action="reject-rendered-prose", + reason="invalid_text" if isinstance(exc, UnicodeError) else "limit", + detector="rendered_representation", + value=None, + ) + raise ReviewRunnerError( + "OCR result prose exceeds mandatory safe-presentation bounds" + ) from exc + + for sink, allow_horizontal_tabs, sink_path in _publication_sinks(payload): + reasons = _dlp_reasons( + sink, + budgets=budgets, + matcher=matcher, + allow_horizontal_tabs=allow_horizontal_tabs, + sink=TextSink.LITERAL_CODE if allow_horizontal_tabs else TextSink.PROSE, + enabled=False, + debug=debug, + path=sink_path, + action="reject-unsafe-presentation", + prepared=prepared, + ) + if reasons: + raise ReviewRunnerError("OCR result prose failed mandatory safe presentation") + + for path, value in prose_slots(prepared_copy(payload, prepared)): + try: + text = bounded_prose_text(value, budgets) + if path[0] == "warnings": + text = ocr_warning_text(value) + except (RepresentationLimit, UnicodeError, ValueError) as exc: + if debug is not None: + debug.decision( + path=path, + action="reject-rendered-prose", + reason="invalid_text" if isinstance(exc, UnicodeError) else "limit", + detector="rendered_representation", + value=None, + ) + raise ReviewRunnerError( + "OCR result prose exceeds mandatory safe-presentation bounds" + ) from exc + if isinstance(value, str) or not text: + continue + checked = check_text(text, budgets=budgets, publication=True, enabled=False) + if not checked.admitted: + if debug is not None: + debug.decision( + path=path, + action="reject-rendered-prose", + reason=checked.reason, + detector=checked.detector, + value=text, + ) + raise ReviewRunnerError("OCR result prose failed mandatory safe presentation") + if path[0] != "warnings": + assert checked.text is not None + prepared[path] = checked.text + return prepared_copy(payload, prepared) if prepared else payload + + def _code_field_allows_horizontal_tabs(path: tuple[object, ...]) -> bool: """Allow HTAB only in the two closed code-bearing finding fields.""" @@ -1212,8 +1301,9 @@ def _safe_publication_comments( debug: DebugBundle | None = None, prepared_comments: object = None, unsafe_rendered: frozenset[tuple[object, ...]] = frozenset(), + require_bound_path: bool = False, ) -> tuple[list[dict[str, object]], int, int]: - """Retain safe finding fields and omit only findings with unsafe content.""" + """Retain safe findings and any path required by the immutable proof.""" if not isinstance(value, list): return [], 0, 0 @@ -1251,13 +1341,21 @@ def _safe_publication_comments( if isinstance(prepared_comments, list) else field_value ) - if projected and not content_unsafe: + path_missing = require_bound_path and "path" not in projected + if projected and not content_unsafe and not path_missing: retained.append(projected) elif debug is not None: + reason = ( + "unsafe_content" + if content_unsafe + else "unsafe_path" + if path_missing + else "empty_projection" + ) debug.decision( path=("comments", index), action="omit-finding", - reason="unsafe_content" if content_unsafe else "empty_projection", + reason=reason, detector=None, value=None, ) @@ -1509,6 +1607,7 @@ def _canonical_result_projection( "reused": outcome.reused_count, "failed": outcome.failed_count, "waived": outcome.waived_count, + "excluded": outcome.excluded_count, "failed_items": [ { "item_id": failure.item_id, @@ -1539,21 +1638,22 @@ def _publication_projection( allowed_tools: frozenset[str], dlp_enabled: bool = True, code_proof: Callable[[dict[str, object]], OpaqueCodeProof] | None = None, + review_manifest_check: Callable[[dict[str, object]], bool] | None = None, debug: DebugBundle | None = None, ) -> tuple[dict[str, object], dict[str, object], bool]: """Return a DLP-safe result plus one disjoint v2 publication state.""" failures = _tool_failure_telemetry(payload.get("tool_calls")) + budgets = TextBudgets(max_chars=2_000_000, max_bytes=8_000_000, max_lines=100_000) if not dlp_enabled: - projected = payload + projected = _project_disabled_publication_prose(payload, budgets=budgets, debug=debug) if failures.present: - projected = dict(payload) + projected = dict(projected) projected["tool_calls"] = _closed_tool_calls( payload.get("tool_calls"), allowed_tools=allowed_tools, failures=failures ) return projected, {"schema": "ocr.publication/v2", "state": "disabled"}, False - budgets = TextBudgets(max_chars=2_000_000, max_bytes=8_000_000, max_lines=100_000) matcher = ForbiddenMatcher.compile(forbidden) sink_reasons: Counter[str] = Counter() unsafe_rendered: set[tuple[object, ...]] = set() @@ -1727,7 +1827,11 @@ def _publication_projection( publication_changed = original_projection != _canonical_result_projection( sanitized, failures=failures ) - except OcrResultContractError: + if not publication_changed and review_manifest_check is not None: + # The native manifest backs the current receipt at posting time. + # Preserve safe findings if sanitization invalidates that proof. + review_manifest_check(sanitized) + except (OcrResultContractError, RepositoryEvidenceError): publication_changed = True if publication_changed: publication_prepared = prepared_copy(bounded_payload, prepared) @@ -1740,6 +1844,7 @@ def _publication_projection( debug=debug, prepared_comments=publication_prepared.get("comments"), unsafe_rendered=frozenset(unsafe_rendered), + require_bound_path=review_manifest_check is not None, ) warnings, omitted_warnings = _safe_publication_warnings( payload.get("warnings"), @@ -1821,6 +1926,7 @@ def _publication_projection( "reused": outcome.reused_count, "failed": outcome.failed_count, "waived": outcome.waived_count, + "excluded": outcome.excluded_count, }, } return projected, publication, True @@ -1835,14 +1941,14 @@ def _discard_unadmitted_result(result_path: Path) -> None: pass -def _verify_gitlink_after_execution(result_path: Path, projection: GitlinkProjection) -> None: - """Reject drift and dispose of raw model output before any publication DLP work.""" +def _verify_projection_after_execution(result_path: Path, projection: GitlinkProjection) -> None: + """Reject review-input drift before any publication DLP work.""" try: verify_gitlink_projection(GitRepositoryReader(Path.cwd()), projection) except (RepositoryEvidenceError, OSError, subprocess.TimeoutExpired) as exc: _discard_unadmitted_result(result_path) - raise ReviewRunnerError("OCR gitlink inputs drifted during model execution") from exc + raise ReviewRunnerError("OCR review inputs drifted during model execution") from exc def _finalize_ocr_result( @@ -1859,6 +1965,7 @@ def _finalize_ocr_result( state: ReviewRunState | None = None, projection: GitlinkProjection | None = None, selected_diff: tuple[RawDiffEntry, ...] = (), + excluded_diff: tuple[PreviewExclusion, ...] = (), expected_range: ReviewRange | None = None, diagram_execution: DiagramExecution | None = None, ocr_exit_code: int | None = None, @@ -1911,6 +2018,7 @@ def finalize(payload: dict[str, object]) -> dict[str, object]: TOOLKIT_ADVISORY_KEY, TOOLKIT_PRIVATE_DIAGNOSTIC_KEY, TOOLKIT_GITLINK_SELECTION_KEY, + TOOLKIT_REVIEW_SELECTION_KEY, INCREMENTAL_RESULT_KEY, ): if reserved in payload: @@ -1939,11 +2047,24 @@ def finalize(payload: dict[str, object]) -> dict[str, object]: incremental.verify_native(payload, evidence_actions=evidence_action_counts) except IncrementalError as exc: raise ReviewRunnerError(str(exc)) from exc + + def check_review_manifest(candidate: dict[str, object]) -> bool: + assert projection is not None + return qualify_review_manifest( + projection, + ReviewSelection(selected_diff, excluded_diff), + candidate, + require_fresh_complete=bool(projection.gitlink_diff), + ) + + missing_gitignore_exclusions = False if projection is not None: try: - qualify_gitlink_manifest(projection, selected_diff, payload) + missing_gitignore_exclusions = check_review_manifest(payload) except RepositoryEvidenceError as exc: - raise ReviewRunnerError("OCR gitlink manifest did not prove selected work") from exc + raise ReviewRunnerError( + "OCR manifest did not prove the immutable selected/excluded partition" + ) from exc failure_telemetry = _tool_failure_telemetry(payload.get("tool_calls")) if state is not None: state.enter("mcp-use") @@ -2033,6 +2154,7 @@ def finalize(payload: dict[str, object]) -> dict[str, object]: allowed_tools=allowed_tools, dlp_enabled=dlp_enabled, code_proof=lambda comment: proofs.get(id(comment), OpaqueCodeProof()), + review_manifest_check=check_review_manifest if projection is not None else None, **({"debug": state.debug} if state is not None and state.debug is not None else {}), ) if state is not None: @@ -2042,22 +2164,42 @@ def finalize(payload: dict[str, object]) -> dict[str, object]: facts={"dlp_state": publication["state"]}, ) state.enter("result-validation") - if filtered and ocr_exit_code == 1: - # The native operational partial was validated before its manifest was filtered. + if filtered and (ocr_exit_code == 1 or missing_gitignore_exclusions): original = publication["original"] assert isinstance(original, dict) - original["operational_partial"] = True + if ocr_exit_code == 1: + # The native operational partial was validated before its manifest was filtered. + original["operational_partial"] = True + if ( + missing_gitignore_exclusions + and projection is not None + and not projection.gitlink_diff + ): + original["excluded"] = len(excluded_diff) + provider_receipt = identity.target_protection in {"protected", "unprotected"} + if provider_receipt and projection is None and filtered: + original = publication["original"] + assert isinstance(original, dict) + original.pop("excluded") metadata["publication"] = publication effective_coverage: RepositoryCoverage | None = None - if projection is not None: + if projection is not None and projection.gitlink_diff: effective_coverage = coverage_from_projection( projection, selected_diff, state="partial" ) metadata["repository_coverage"] = effective_coverage.payload() metadata["schema_version"] = PARTIAL_TOOLKIT_RESULT_SCHEMA_VERSION - else: + elif projection is not None: + try: + metadata["review_coverage"] = coverage_from_selection( + projection, ReviewSelection(selected_diff, excluded_diff) + ).payload() + except ReviewCoverageError as exc: + raise ReviewRunnerError("immutable review coverage could not be receipted") from exc metadata["schema_version"] = TOOLKIT_RESULT_SCHEMA_VERSION - provider_receipt = identity.target_protection in {"protected", "unprotected"} + else: + # Historical receipts carry no proof of the complete changed-path set. + metadata["schema_version"] = 13 if provider_receipt: if analysis_result is not None and ( signature := review_analysis.publication_digest(analysis_result, metadata["review"]) @@ -2085,10 +2227,15 @@ def finalize(payload: dict[str, object]) -> dict[str, object]: finalized = {**projected, TOOLKIT_RESULT_KEY: metadata} if provider_receipt else projected if analysis_result is not None: finalized[review_analysis.PRIVATE_RESULT_KEY] = analysis_result - if projection is not None and filtered and provider_receipt: - finalized[TOOLKIT_GITLINK_SELECTION_KEY] = gitlink_selection_proof( - projection, selected_diff - ) + if projection is not None and provider_receipt: + if filtered and projection.gitlink_diff: + finalized[TOOLKIT_GITLINK_SELECTION_KEY] = gitlink_selection_proof( + projection, selected_diff + ) + elif not projection.gitlink_diff and (filtered or missing_gitignore_exclusions): + finalized[TOOLKIT_REVIEW_SELECTION_KEY] = review_selection_proof( + projection, ReviewSelection(selected_diff, excluded_diff) + ) if toolkit_advisory is not None and provider_receipt: finalized[TOOLKIT_ADVISORY_KEY] = toolkit_advisory_payload(toolkit_advisory) if report_consumer is not None: @@ -2108,7 +2255,7 @@ def finalize(payload: dict[str, object]) -> dict[str, object]: effective_coverage, review_range=admitted_range, diagram=admitted_diagram, - prepared_prose=dlp_enabled, + prepared_prose=True, ), reviewed_sha=identity.source_sha, ) @@ -2121,6 +2268,10 @@ def finalize(payload: dict[str, object]) -> dict[str, object]: raise ReviewRunnerError( "carried findings could not be safely revalidated" ) from exc + elif state is not None and state.incremental and composition.external_servers: + full_review = IncrementalReport((), 0, full_reason=FEDERATED_INCREMENTAL_REASON) + finalized = local_incremental.bounded_incremental_result(finalized, full_review) + report = replace(report, incremental=full_review) return finalized try: @@ -2447,12 +2598,16 @@ def _qualify_review_background( qualification = replace(qualification, preview_stdout=stdout) if projection is not None: try: - selected = qualify_gitlink_preview(projection, stdout) + selection = qualify_review_preview(projection, stdout) except RepositoryEvidenceError as exc: raise ReviewRunnerError( - "OCR gitlink preview did not match the ordinary diff" + "OCR preview did not exactly partition the immutable ordinary diff" ) from exc - return replace(qualification, selected_diff=selected) + return replace( + qualification, + selected_diff=selection.selected, + excluded_diff=selection.excluded, + ) return qualification finally: active_error = sys.exception() @@ -2580,6 +2735,7 @@ def _run_background_qualified_review( narrowed_args, ocr_binary=ocr_binary, session_home=session_home, + projection=projection, retain_preview=True, child_environment=incremental.child_environment, ) @@ -2601,7 +2757,7 @@ def _run_background_qualified_review( if state is not None: state.observe("preview", "degraded" if qualification.advisory is not None else "passed") if projection is not None: - if not qualification.selected_diff: + if projection.gitlink_diff and not qualification.selected_diff: coverage = coverage_from_projection(projection, (), state="not_started") if state is not None: state.repository_coverage = coverage @@ -2632,7 +2788,7 @@ def _run_background_qualified_review( try: verify_gitlink_projection(GitRepositoryReader(Path.cwd()), projection) except (RepositoryEvidenceError, OSError, subprocess.TimeoutExpired) as exc: - raise ReviewRunnerError("OCR gitlink inputs drifted before model execution") from exc + raise ReviewRunnerError("OCR review inputs drifted before model execution") from exc if state is not None: state.enter("subprocess") continuation = state.continuation if state is not None else None @@ -3882,7 +4038,7 @@ def _run_evidence_review( evidence_action_counts: dict[str, dict[str, int]] | None = None background_qualification = BackgroundQualification() gateway = None - federation_forbidden: tuple[str, ...] = () + federation_forbidden: tuple[ForbiddenValue, ...] = () diagram_execution: DiagramExecution | None = None previous_handlers = _install_termination_handlers() try: @@ -4060,11 +4216,12 @@ def _run_evidence_review( ocr_binary = native_binary or _resolve_ocr_binary() projection: GitlinkProjection | None = None gitlink_detected = False - gitlink_plan = None + review_plan = None try: reader = GitRepositoryReader(Path.cwd()) - gitlink_plan = plan_gitlink_input(reader, refs.base, refs.head) - if gitlink_plan is not None: + plan_input = plan_gitlink_input if state.local else plan_review_input + review_plan = plan_input(reader, refs.base, refs.head) + if review_plan is not None and review_plan.changes: if native_version is None: try: native_version = preflight.validate_ocr_binary( @@ -4073,21 +4230,21 @@ def _run_evidence_review( except preflight.PreflightError as exc: raise ReviewRunnerError(str(exc)) from exc if supports_native_capability(native_version, "gitlink_projection"): - projection = make_gitlink_projection(reader, gitlink_plan) + projection = make_gitlink_projection(reader, review_plan) else: gitlink_detected = True + elif review_plan is not None: + projection = make_gitlink_projection(reader, review_plan) except RepositoryEvidenceError as exc: - if gitlink_plan is not None: + if review_plan is not None and review_plan.changes: gitlink_detected = True else: try: gitlink_detected = bool(changed_gitlinks(reader, refs.base, refs.head)) except RepositoryEvidenceError: - raise ReviewRunnerError( - "changed gitlink evidence could not be qualified" - ) from exc + pass if not gitlink_detected: - raise ReviewRunnerError("changed gitlink evidence could not be qualified") from exc + raise ReviewRunnerError("immutable review coverage could not be qualified") from exc print( "OCR gitlink qualification: immutable changed pointer is outside the " "qualified subset; model review did not run", @@ -4101,7 +4258,7 @@ def _run_evidence_review( and not servers and (not state.continue_local or not local_diagram) and not gitlink_detected - and projection is None + and (projection is None or not projection.gitlink_diff) ): reuse_binary = preflight.stage_local_review_executable( ocr_binary, @@ -4134,7 +4291,9 @@ def _run_evidence_review( "Local continuation could not bind the inputs. Starting a full review.", file=sys.stderr, ) - if state.incremental and reuse_binary is None: + if state.incremental and servers: + print(f"{FEDERATED_INCREMENTAL_REASON} Starting a full review.", file=sys.stderr) + elif state.incremental and reuse_binary is None: print( "Local incremental review is unavailable for these inputs. Starting a full review.", file=sys.stderr, @@ -4273,15 +4432,13 @@ def _run_evidence_review( forbidden: tuple[str | ForbiddenValue, ...] = tuple( ForbiddenValue(v, "operator_secret") for v in composition.secret_values ) - forbidden += tuple( - ForbiddenValue(v, "external_context") for v in federation_forbidden - ) + forbidden += federation_forbidden if enrichment is not None: forbidden += enrichment.forbidden_sources or tuple( ForbiddenValue(v, "other") for v in enrichment.forbidden_publication ) if projection is not None: - _verify_gitlink_after_execution(result_path, projection) + _verify_projection_after_execution(result_path, projection) usage, publication_filtered, publication = _finalize_ocr_result( result_path, composition, @@ -4300,6 +4457,7 @@ def _run_evidence_review( { "projection": projection, "selected_diff": background_qualification.selected_diff, + "excluded_diff": background_qualification.excluded_diff, } if projection is not None else {} @@ -4433,6 +4591,7 @@ def _failed_review_result_is_partial( TOOLKIT_ADVISORY_KEY, TOOLKIT_PRIVATE_DIAGNOSTIC_KEY, TOOLKIT_GITLINK_SELECTION_KEY, + TOOLKIT_REVIEW_SELECTION_KEY, INCREMENTAL_RESULT_KEY, review_analysis.PRIVATE_RESULT_KEY, ) diff --git a/src/ocr_toolkit/telemetry/locales/en.json b/src/ocr_toolkit/telemetry/locales/en.json index 9f4eff3c..1a5780db 100644 --- a/src/ocr_toolkit/telemetry/locales/en.json +++ b/src/ocr_toolkit/telemetry/locales/en.json @@ -160,6 +160,7 @@ "estimated_cost_per_100_priced_successful_results": "Estimated USD per 100 priced successful results", "estimated_usd": "Estimated usd", "evidence_budget_exceeded": "Evidence budget exceeded", + "excluded": "Excluded", "exclusions": "Exclusions", "execution": "Execution", "explicit": "Explicit", diff --git a/src/ocr_toolkit/telemetry/locales/ru.json b/src/ocr_toolkit/telemetry/locales/ru.json index 23ff7c88..07f25d20 100644 --- a/src/ocr_toolkit/telemetry/locales/ru.json +++ b/src/ocr_toolkit/telemetry/locales/ru.json @@ -160,6 +160,7 @@ "estimated_cost_per_100_priced_successful_results": "Оценка USD на 100 успешных результатов с известной ценой", "estimated_usd": "Оценка, USD", "evidence_budget_exceeded": "Исчерпан бюджет доказательств", + "excluded": "Исключено из отбора", "exclusions": "Исключения", "execution": "Выполнение", "explicit": "Указанные проекты", @@ -491,7 +492,7 @@ "verified_calls": "Подтверждённые вызовы", "versions": "Версии", "waiting_for_resource": "Ожидает ресурса", - "waived": "Исключено", + "waived": "Пропущено по решению", "warning_count": "Число предупреждений", "warnings": "Предупреждения", "wed": "Ср", diff --git a/src/ocr_toolkit/telemetry/metrics/technical.py b/src/ocr_toolkit/telemetry/metrics/technical.py index bfd8fa29..4ee89809 100644 --- a/src/ocr_toolkit/telemetry/metrics/technical.py +++ b/src/ocr_toolkit/telemetry/metrics/technical.py @@ -38,7 +38,7 @@ "carried_forward", "publication_limit", ), - "coverage": ("selected", "completed", "reused", "failed", "waived"), + "coverage": ("selected", "completed", "reused", "failed", "waived", "excluded"), "tool_calls_by_name": (*sorted(PUBLIC_REVIEW_TOOL_CALL_NAMES), "other"), "mcp": ("servers", "calls"), "completed_evidence_actions": ("summary", "list", "get", "search", "coverage"), diff --git a/src/ocr_toolkit/telemetry/publications/metrics.py b/src/ocr_toolkit/telemetry/publications/metrics.py index 9aabfd22..c9b82256 100644 --- a/src/ocr_toolkit/telemetry/publications/metrics.py +++ b/src/ocr_toolkit/telemetry/publications/metrics.py @@ -6,6 +6,7 @@ from ocr_toolkit.reporting.metadata import OCR_FINDING_CATEGORIES as OCR_CATEGORIES from ocr_toolkit.reporting.metadata import OCR_FINDING_SEVERITIES as SEVERITIES +from ocr_toolkit.result_contract import MAX_COVERAGE_RECORDS from .grammar import ( OCR_CORE_ADVISORY_MAX_COUNT, @@ -94,12 +95,31 @@ def groups(pattern: str, names: tuple[str, ...]) -> dict[str, int]: ) if match is not None } - coverage = groups( - r"^(?:- )?Coverage: selected ([0-9]{1,12}); completed ([0-9]{1,12}); reused ([0-9]{1,12}); failed ([0-9]{1,12}); waived ([0-9]{1,12})\.?$", - ("selected", "completed", "reused", "failed", "waived"), - ) - if coverage and coverage["selected"] != sum( - coverage[name] for name in ("completed", "reused", "failed", "waived") + coverage_matches = re.findall( + r"^(?:- )?Coverage: selected ([0-9]{1,12}); " + r"completed ([0-9]{1,12}); reused ([0-9]{1,12}); " + r"failed ([0-9]{1,12}); waived ([0-9]{1,12})" + r"(?:; excluded ([0-9]{1,12}))?\.?$", + metrics_text, + re.M, + ) + coverage = {} + if len(coverage_matches) == 1: + values = coverage_matches[0] + coverage = { + name: int(value) + for name, value in zip( + ("selected", "completed", "reused", "failed", "waived"), + values[:5], + strict=True, + ) + } + if values[5]: + coverage["excluded"] = int(values[5]) + if coverage and ( + coverage["selected"] + != sum(coverage[name] for name in ("completed", "reused", "failed", "waived")) + or coverage.get("excluded", 0) > MAX_COVERAGE_RECORDS ): coverage = {} return posting, coverage diff --git a/src/ocr_toolkit/telemetry/publications/signals.py b/src/ocr_toolkit/telemetry/publications/signals.py index b7a23837..a41cf33a 100644 --- a/src/ocr_toolkit/telemetry/publications/signals.py +++ b/src/ocr_toolkit/telemetry/publications/signals.py @@ -189,7 +189,6 @@ def normalize_dlp_v4(signal: dict[str, Any], counts: Any) -> tuple[dict[str, Any coverage_keys = {"selected", "completed", "reused", "failed", "waived"} if ( not counts(reasons, OCR_PUBLICATION_DLP_REASON_KEYS) - or not any(reasons.values()) or not counts(signal.get("retained"), {"comments", "warnings"}) or not counts(signal.get("omitted"), {"comments", "warnings", "fields"}) or not counts({"count": signal.get("carried_forward_comments")}, {"count"}) @@ -199,6 +198,8 @@ def normalize_dlp_v4(signal: dict[str, Any], counts: Any) -> tuple[dict[str, Any or not counts({key: original[key] for key in coverage_keys}, coverage_keys) ): return None, True + if not any(reasons.values()) and (not private["fields"] or any(signal["omitted"].values())): + return None, True selected, failed = original["selected"], original["failed"] allowed = {"failed"} | ( {"skipped"} diff --git a/src/ocr_toolkit/telemetry/publications/status.py b/src/ocr_toolkit/telemetry/publications/status.py index dbd7bc37..9d42adc8 100644 --- a/src/ocr_toolkit/telemetry/publications/status.py +++ b/src/ocr_toolkit/telemetry/publications/status.py @@ -337,7 +337,8 @@ def parse_ocr_review_rejection(body: str) -> dict[str, Any] | None: r"completed (?P0|[1-9][0-9]{0,4}); " r"reused (?P0|[1-9][0-9]{0,4}); " r"failed (?P0|[1-9][0-9]{0,4}); " - r"waived (?P0|[1-9][0-9]{0,4})\.)?", + r"waived (?P0|[1-9][0-9]{0,4})" + r"(?:; excluded (?P0|[1-9][0-9]{0,4}))?\.)?", lines[0], ) if not diagnostic: @@ -369,6 +370,8 @@ def parse_ocr_review_rejection(body: str) -> dict[str, Any] | None: key: int(diagnostic.group(key)) for key in ("selected", "completed", "reused", "failed", "waived") } + if diagnostic.group("excluded") is not None: + coverage["excluded"] = int(diagnostic.group("excluded")) if max(coverage.values()) > 10_000 or coverage["selected"] != sum( coverage[key] for key in ("completed", "reused", "failed", "waived") ): diff --git a/src/ocr_toolkit/telemetry/publications/summary.py b/src/ocr_toolkit/telemetry/publications/summary.py index 13c72281..225f0bfe 100644 --- a/src/ocr_toolkit/telemetry/publications/summary.py +++ b/src/ocr_toolkit/telemetry/publications/summary.py @@ -26,12 +26,13 @@ def _summary_outcome(status_text: str, layout: str) -> tuple[str, bool]: """Distinguish an explicit historical outcome from the shared current filtering heading.""" outcome_match = re.search( - r"\*\*(?:Review (complete with publication filtering|complete with warnings|complete|incomplete|stopped at token budget|skipped|failed)\b|(Analysis complete; output incomplete) — )", + r"\*\*(?:Review (complete; output incomplete|complete with publication filtering|complete with warnings|complete|incomplete|stopped at token budget|skipped|failed)\b|(Analysis complete; output incomplete) — )", status_text, re.IGNORECASE, ) outcome = { "complete": "complete", + "complete; output incomplete": "incomplete", "complete with warnings": "complete_with_warnings", "complete with publication filtering": "complete_publication_filtered", "incomplete": "incomplete", diff --git a/tests/federation/sdk_peer.py b/tests/federation/sdk_peer.py index 44a6fda9..ef3f6f31 100644 --- a/tests/federation/sdk_peer.py +++ b/tests/federation/sdk_peer.py @@ -39,6 +39,11 @@ def response_probe(kind: str) -> types.CallToolResult: return types.CallToolResult( content=[types.ImageContent(type="image", data="AA==", mime_type="image/png")] ) + if kind == "structured": + return types.CallToolResult( + content=[types.TextContent(type="text", text="controlled structured response")], + structured_content={"controlled structured key": "controlled structured value"}, + ) text = ( "x" * (128 * 1024 + 1) if kind == "oversized" diff --git a/tests/federation/test_admission.py b/tests/federation/test_admission.py index cee15100..8f9cc657 100644 --- a/tests/federation/test_admission.py +++ b/tests/federation/test_admission.py @@ -1,10 +1,18 @@ """Bounded validator and nested argument authorization through their production owners.""" +import mcp_types as types import pytest -from ocr_toolkit.context.dlp import ForbiddenMatcher +from ocr_toolkit.context.dlp import ForbiddenMatcher, ForbiddenValue from ocr_toolkit.federation import FederationError, ToolPolicy -from ocr_toolkit.federation.admission import arguments, compile_schema +from ocr_toolkit.federation.admission import ( + arguments, + check_provenance, + compile_argument_schema, + compile_schema, + index_result, + publication_values, +) MATCHER = ForbiddenMatcher.compile(()) @@ -28,6 +36,61 @@ def test_unsupported_schema_constraints_are_rejected(schema: object) -> None: compile_schema(schema, MATCHER) +@pytest.mark.parametrize( + "schema", + [ + {"type": "object", "properties": {"query": {"type": "string"}}}, + { + "type": "object", + "additionalProperties": False, + "properties": {"key": {"type": ["string", "null"]}}, + }, + { + "type": "object", + "properties": {"filters": {"type": "object", "properties": {}}}, + "additionalProperties": False, + }, + { + "type": "object", + "oneOf": [{"type": "object", "properties": {}, "additionalProperties": False}], + "additionalProperties": False, + }, + ], +) +def test_operator_argument_schema_must_close_every_object(schema: object) -> None: + """Reject interfaces that leave undeclared model-selected data fields reachable.""" + with pytest.raises(FederationError, match="schema_invalid"): + compile_argument_schema(schema, MATCHER) + + +def test_operator_argument_schema_preserves_declared_nested_values() -> None: + """Accept a closed useful interface and preserve its ordinary declared arguments.""" + schema = { + "type": "object", + "properties": { + "query": {"type": "string", "maxLength": 80}, + "filters": { + "type": "object", + "properties": {"state": {"type": "string", "enum": ["open", "closed"]}}, + "additionalProperties": False, + }, + }, + "required": ["query"], + "additionalProperties": False, + } + validator = compile_argument_schema(schema, MATCHER) + value = {"query": "controlled issue", "filters": {"state": "open"}} + admitted, _ = arguments(value, ToolPolicy("lookup", "synthetic__lookup"), validator, MATCHER) + assert admitted == value + with pytest.raises(FederationError, match="arguments_invalid"): + arguments( + {**value, "repository_source": "private"}, + ToolPolicy("lookup", "synthetic__lookup"), + validator, + MATCHER, + ) + + def test_nested_origins_and_dlp_are_independent_of_schema() -> None: validator = compile_schema({"type": "object"}, MATCHER) policy = ToolPolicy( @@ -53,6 +116,20 @@ def test_nested_origins_and_dlp_are_independent_of_schema() -> None: ) +def test_unicode_hostname_cannot_alias_ascii_resource_origin() -> None: + validator = compile_schema({"type": "object"}, MATCHER) + policy = ToolPolicy( + "lookup", + "synthetic__lookup", + resource_origins=("https://fass.invalid", "https://xn--fa-hia.invalid"), + ) + for url in ("https://fass.invalid/document", "https://xn--fa-hia.invalid/document"): + value = {"link": url} + assert arguments(value, policy, validator, MATCHER)[0] == value + with pytest.raises(FederationError, match="origin_denied"): + arguments({"link": "https://faß.invalid/document"}, policy, validator, MATCHER) + + def test_deep_and_oversized_arguments_fail_before_validation_work() -> None: validator = compile_schema({"type": "object"}, MATCHER) value = {"leaf": "controlled"} @@ -70,3 +147,110 @@ def test_schema_dlp_rejection_has_closed_boundary_without_tool_attempt() -> None assert captured.value.boundary == "schema" assert captured.value.detector == "pii" assert "person@example.test" not in str(captured.value) + + +def test_result_provenance_includes_structured_keys_and_values() -> None: + result = types.CallToolResult( + content=[types.TextContent(type="text", text="controlled text")], + structured_content={"id": {"nested": "controlled value"}}, + ) + + indexed = index_result(result) + assert indexed.provenance.raw == { + "controlled text", + "id", + "nested", + "controlled value", + } + validator = compile_argument_schema( + { + "type": "object", + "properties": {"id": {"type": "string"}}, + "required": ["id"], + "additionalProperties": False, + }, + MATCHER, + ) + policy = ToolPolicy("lookup", "synthetic__lookup") + values, _ = arguments({"id": "ordinary argument"}, policy, validator, MATCHER) + check_provenance(values, (indexed.provenance,)) + for copied in ("id", "nested", "controlled value"): + values, _ = arguments({"id": copied}, policy, validator, MATCHER) + with pytest.raises(FederationError, match="dlp_rejected") as captured: + check_provenance(values, (indexed.provenance,)) + assert (captured.value.boundary, captured.value.detector) == ("arguments", "forbidden") + + +def test_publication_projection_includes_structured_keys_and_values() -> None: + projected = set( + publication_values( + {"controlled structured key": ["controlled structured value", {"nested key": "leaf"}]} + ) + ) + assert projected == { + ForbiddenValue("controlled structured key", "external_context", structural_key=True), + ForbiddenValue("controlled structured value", "external_context"), + ForbiddenValue("nested key", "external_context", structural_key=True), + ForbiddenValue("leaf", "external_context"), + } + + +def test_schema_publication_projection_tracks_model_visible_external_data() -> None: + projected = { + value.value + for value in publication_values( + { + "type": "object", + "title": "controlled title", + "description": "controlled description", + "default": {"controlled default key": "controlled default value"}, + "examples": [{"controlled example key": "controlled example value"}], + "enum": ["controlled enum"], + "properties": { + "controlled property": { + "type": "string", + "description": "controlled property description", + } + }, + "required": ["controlled property"], + }, + schema=True, + ) + } + assert { + "controlled title", + "controlled description", + "controlled default key", + "controlled default value", + "controlled example key", + "controlled example value", + "controlled enum", + "controlled property", + "controlled property description", + } <= projected + + +def test_schema_publication_safe_keys_are_contextual() -> None: + fixed = set( + publication_values( + { + "type": "object", + "properties": {"id": {"type": "string"}}, + "required": ["id"], + }, + schema=True, + ) + ) + assert fixed == {ForbiddenValue("id", "external_context", structural_key=True)} + + dynamic = { + value.value + for value in publication_values( + { + "default": {"type": "controlled default", "string": "object"}, + "properties": {"description": {"type": "string"}}, + }, + schema=True, + ) + } + assert {"type", "description", "controlled default", "string", "object"} <= dynamic diff --git a/tests/federation/test_gateway.py b/tests/federation/test_gateway.py index 5e4b0387..8859857e 100644 --- a/tests/federation/test_gateway.py +++ b/tests/federation/test_gateway.py @@ -6,6 +6,7 @@ import json import os import sys +import threading from pathlib import Path from typing import Any @@ -13,15 +14,41 @@ from mcp import Client from mcp.client.stdio import StdioServerParameters -from ocr_toolkit.federation import FederationError, parse_registry, start_gateway +from ocr_toolkit import review_runner +from ocr_toolkit.context.dlp import ForbiddenValue +from ocr_toolkit.federation import FederationError, Registry, parse_registry, start_gateway PEER = Path(__file__).with_name("sdk_peer.py") +def tool_policy(name: str) -> dict[str, Any]: + """Return an explicit operator-owned interface for one synthetic peer tool.""" + properties: dict[str, Any] = {} + required: list[str] = [] + if name == "echo": + properties = { + "text": {"type": "string"}, + "delay": {"type": "number", "minimum": 0, "maximum": 1}, + } + required = ["text"] + elif name == "response_probe": + properties = {"kind": {"type": "string"}} + required = ["kind"] + return { + "description": f"Use the operator-authorized {name} test interface.", + "input_schema": { + "type": "object", + "properties": properties, + "required": required, + "additionalProperties": False, + }, + } + + def registry_value() -> dict[str, Any]: """Return one selected synthetic tool over an explicit absolute argv.""" return { - "version": 2, + "version": 3, "servers": { "synthetic": { "transport": { @@ -29,7 +56,7 @@ def registry_value() -> dict[str, Any]: "command": sys.executable, "args": ["-I", str(PEER)], }, - "tools": {"echo": {}}, + "tools": {"echo": tool_policy("echo")}, } }, } @@ -57,12 +84,18 @@ def test_actual_sdk_relay_cache_dlp_and_closed_receipt() -> None: assert gateway._gateway.budget.requests == 2 # Upstream discovery and tools/list. assert endpoint.stat().st_mode & 0o777 == 0o600 assert endpoint.parent.stat().st_mode & 0o777 == 0o700 + definition = gateway._gateway.tools["synthetic__echo"].definition + protected_metadata = {item.value for item in gateway.forbidden_publication} + assert definition.description and definition.description in protected_metadata + assert set(definition.input_schema["properties"]) <= protected_metadata async def exercise() -> None: async with relay_client(gateway) as client: assert client.protocol_version == "2026-07-28" listing = await client.list_tools() assert [tool.name for tool in listing.tools] == ["synthetic__echo"] + assert listing.tools[0].description == tool_policy("echo")["description"] + assert listing.tools[0].input_schema == tool_policy("echo")["input_schema"] for _ in range(2): response = await client.call_tool("synthetic__echo", {"text": "controlled result"}) assert response.content[0].text == "controlled result" @@ -83,7 +116,7 @@ async def exercise() -> None: assert counts["denied"] == counts["dlp_rejected"] == counts["cache_hits"] == 1 assert counts["dlp_gates"]["arguments"]["forbidden"] == 1 assert sum(counts["dlp_gates"]["result"].values()) == 0 - assert "controlled result" in gateway.forbidden_publication + assert ForbiddenValue("controlled result", "external_context") in gateway.forbidden_publication assert "controlled protected phrase" not in json.dumps(receipt) assert not endpoint.parent.exists() assert gateway.close() == receipt @@ -115,13 +148,216 @@ async def exercise() -> None: assert counts["single_flight"] == 2 +@pytest.mark.parametrize("dlp_enabled", [True, False]) +def test_cross_server_result_egress_is_denied_without_blocking_source_reuse( + dlp_enabled: bool, +) -> None: + value = registry_value() + value["servers"]["other"] = { + "transport": dict(value["servers"]["synthetic"]["transport"]), + "tools": {"echo": tool_policy("echo")}, + } + gateway = start_gateway( + parse_registry(json.dumps(value)), + environment={}, + run_id="a" * 32, + dlp_enabled=dlp_enabled, + ) + + async def exercise() -> None: + async with relay_client(gateway) as client: + learned = "controlled upstream result material" + shared = await asyncio.gather( + *( + client.call_tool("synthetic__echo", {"text": learned, "delay": 0.1}) + for _ in range(2) + ) + ) + assert all(result.content[0].text == learned for result in shared) + assert not ( + await client.call_tool("synthetic__echo", {"text": learned, "delay": 0.1}) + ).is_error + + assert not ( + await client.call_tool("other__echo", {"text": "independent controlled input"}) + ).is_error + assert (await client.call_tool("other__echo", {"text": learned})).is_error + + assert not (await client.call_tool("synthetic__echo", {"text": "id"})).is_error + assert not (await client.call_tool("other__echo", {"text": "candidate"})).is_error + assert (await client.call_tool("other__echo", {"text": "id"})).is_error + + try: + asyncio.run(exercise()) + finally: + receipt = gateway.close() + source = receipt["tools"]["synthetic__echo"] + destination = receipt["tools"]["other__echo"] + assert source["attempted"] == source["completed"] == 4 + assert source["cache_hits"] == 1 + assert source["single_flight"] == 1 + assert destination["attempted"] == 4 + assert destination["completed"] == destination["denied"] == 2 + assert destination["dlp_rejected"] == 2 + assert destination["dlp_gates"]["arguments"]["forbidden"] == 2 + + def test_missing_tool_fails_before_gateway_is_returned() -> None: value = registry_value() - value["servers"]["synthetic"]["tools"] = {"missing": {}} + value["servers"]["synthetic"]["tools"] = {"missing": tool_policy("missing")} with pytest.raises(FederationError, match="inventory_invalid"): start_gateway(parse_registry(json.dumps(value)), environment={}, run_id="a" * 32) +def test_dlp_disabled_relay_preserves_exact_result_provenance_and_admits_unrelated_inputs() -> None: + value = registry_value() + value["servers"]["other"] = { + "transport": dict(value["servers"]["synthetic"]["transport"]), + "tools": {"echo": tool_policy("echo")}, + } + gateway = start_gateway( + parse_registry(json.dumps(value)), environment={}, run_id="a" * 32, dlp_enabled=False + ) + + async def exercise() -> None: + async with relay_client(gateway) as client: + for learned in ("controlled\u0001text", "***", ""): + result = await client.call_tool("synthetic__echo", {"text": learned}) + assert not result.is_error and result.content[0].text == learned + assert (await client.call_tool("other__echo", {"text": learned})).is_error + + raw_excerpt = "sample evidence fragment" + raw = f"Synthetic prefix.\u0001{raw_excerpt} with a suffix." + returned = await client.call_tool("synthetic__echo", {"text": raw}) + assert not returned.is_error and returned.content[0].text == raw + copied = await client.call_tool("other__echo", {"text": raw_excerpt}) + assert copied.is_error + + long_text = "x" * (16 * 1024) + assert not (await client.call_tool("synthetic__echo", {"text": long_text})).is_error + independent = "y" * (4 * 1024) + returned = await client.call_tool("other__echo", {"text": independent}) + assert not returned.is_error and returned.content[0].text == independent + excerpt = f"prose with an excerpt **{long_text[:24].upper()}**" + assert (await client.call_tool("other__echo", {"text": excerpt})).is_error + + try: + asyncio.run(exercise()) + finally: + receipt = gateway.close() + destination = receipt["tools"]["other__echo"] + assert destination["completed"] == 1 + assert destination["dlp_gates"]["arguments"]["forbidden"] == 5 + assert destination["dlp_gates"]["arguments"]["limit"] == 0 + + +def test_queued_call_rechecks_result_provenance_before_peer_dispatch() -> None: + value = registry_value() + value["servers"]["other"] = { + "transport": dict(value["servers"]["synthetic"]["transport"]), + "tools": {"echo": tool_policy("echo")}, + } + gateway = start_gateway(parse_registry(json.dumps(value)), environment={}, run_id="a" * 32) + assert gateway._gateway is not None and gateway._loop is not None + runtime = gateway._gateway + loop = gateway._loop + queued = threading.Event() + + class PausedFirstAcquire(asyncio.Semaphore): + def __init__(self) -> None: + super().__init__(4) + self.resume = asyncio.Event() + + async def acquire(self) -> bool: + if not queued.is_set(): + queued.set() + await self.resume.wait() + return await super().acquire() + + limiter = PausedFirstAcquire() + loop.call_soon_threadsafe(setattr, runtime, "semaphore", limiter) + + async def exercise() -> None: + material = "Controlled queued result text" + async with relay_client(gateway) as client: + pending = asyncio.create_task(client.call_tool("other__echo", {"text": material})) + try: + assert await asyncio.to_thread(queued.wait, 5) + learned = await client.call_tool("synthetic__echo", {"text": material}) + assert not learned.is_error and learned.content[0].text == material + wire_requests = runtime.budget.requests + finally: + loop.call_soon_threadsafe(limiter.resume.set) + assert (await pending).is_error + assert runtime.budget.requests == wire_requests + + try: + asyncio.run(exercise()) + finally: + receipt = gateway.close() + destination = receipt["tools"]["other__echo"] + assert destination["attempted"] == destination["denied"] == 1 + assert destination["dlp_gates"]["arguments"]["forbidden"] == 1 + + +def test_publication_dlp_protects_short_schema_keys_as_tokens() -> None: + value = registry_value() + schema = value["servers"]["synthetic"]["tools"]["echo"]["input_schema"] + schema["properties"] = {"id": {"type": "string"}} + schema["required"] = ["id"] + gateway = start_gateway(parse_registry(json.dumps(value)), environment={}, run_id="a" * 32) + assert gateway.close()["tools"]["synthetic__echo"]["attempted"] == 0 + + safe = {"path": "src/sample.py", "line": 1, "content": "Handle valid input here."} + copied = {"path": "src/sample.py", "line": 2, "content": "Preserve the `id` value here."} + projected, publication, filtered = review_runner._publication_projection( + {"status": "success", "comments": [safe, copied]}, + forbidden=gateway.forbidden_publication, + allowed_tools=frozenset(), + ) + assert filtered and projected["comments"] == [safe] + attribution = publication["source_attribution"] + assert isinstance(attribution, dict) and attribution["counts"]["external_context"] >= 1 + + +@pytest.mark.parametrize("field", ["description", "input_schema"]) +def test_registry_requires_operator_owned_interface_fields(field: str) -> None: + """Reject policies that would delegate any model-interface field to the upstream.""" + value = registry_value() + del value["servers"]["synthetic"]["tools"]["echo"][field] + with pytest.raises(FederationError, match="registry_invalid"): + parse_registry(json.dumps(value)) + + +@pytest.mark.parametrize("invalid_field", ["input_schema", "description"]) +def test_operator_interfaces_are_checked_before_any_peer_opens( + monkeypatch: pytest.MonkeyPatch, invalid_field: str +) -> None: + from ocr_toolkit.federation import gateway as module + + opened: list[str] = [] + + def observe_transport(spec: Any, *_args: Any) -> None: + opened.append(spec.name) + + monkeypatch.setattr(module, "stdio_transport", observe_transport) + value = registry_value() + tools = {"echo": tool_policy("echo")} + if invalid_field == "input_schema": + tools["echo"]["input_schema"]["additionalProperties"] = True + reason = "schema_invalid" + else: + tools["echo"]["description"] = "Contact person@example.test" + reason = "dlp_rejected" + value["servers"]["zinvalid"] = { + "transport": dict(value["servers"]["synthetic"]["transport"]), + "tools": tools, + } + with pytest.raises(FederationError, match=reason): + start_gateway(parse_registry(json.dumps(value)), environment={}, run_id="a" * 32) + assert not opened + + def test_schema_rejection_preserves_closed_stage_through_gateway_thread( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -140,7 +376,7 @@ def test_stdio_child_receives_only_explicit_environment(monkeypatch: pytest.Monk monkeypatch.setenv("SYNTHETIC_UNSELECTED", "synthetic-parent-value") value = registry_value() value["servers"]["synthetic"]["transport"]["env_from"] = {"SELECTED_VALUE": "SYNTHETIC_SOURCE"} - value["servers"]["synthetic"]["tools"] = {"environment_probe": {}} + value["servers"]["synthetic"]["tools"] = {"environment_probe": tool_policy("environment_probe")} gateway = start_gateway( parse_registry(json.dumps(value)), environment={ @@ -163,7 +399,7 @@ async def exercise() -> None: def test_upstream_response_admission_is_atomic_and_rejections_are_not_cached() -> None: value = registry_value() - value["servers"]["synthetic"]["tools"] = {"response_probe": {}} + value["servers"]["synthetic"]["tools"] = {"response_probe": tool_policy("response_probe")} gateway = start_gateway( parse_registry(json.dumps(value)), environment={}, @@ -171,6 +407,8 @@ def test_upstream_response_admission_is_atomic_and_rejections_are_not_cached() - run_id="a" * 32, ) + discovery_material = gateway.forbidden_publication + async def exercise() -> None: async with relay_client(gateway) as client: for kind in ("items", "image", "oversized", "protected", "protected"): @@ -189,29 +427,38 @@ async def exercise() -> None: assert counts["oversized"] == 1 assert counts["dlp_gates"]["result"]["forbidden"] == 2 assert sum(counts["dlp_gates"]["arguments"].values()) == 0 - assert not gateway.forbidden_publication + assert gateway.forbidden_publication == discovery_material -def test_result_contact_rejection_is_attributed_without_content_or_double_counting() -> None: +def test_result_rejection_and_structured_provenance_are_independent() -> None: value = registry_value() - value["servers"]["synthetic"]["tools"] = {"response_probe": {}} + value["servers"]["synthetic"]["tools"] = {"response_probe": tool_policy("response_probe")} gateway = start_gateway(parse_registry(json.dumps(value)), environment={}, run_id="a" * 32) async def exercise() -> None: async with relay_client(gateway) as client: - for kind in ("contact", "clean"): + for kind in ("contact", "clean", "structured"): response = await client.call_tool("synthetic__response_probe", {"kind": kind}) assert response.is_error is (kind == "contact") + if kind == "structured": + assert response.structured_content == { + "controlled structured key": "controlled structured value" + } try: asyncio.run(exercise()) finally: receipt = gateway.close() counts = receipt["tools"]["synthetic__response_probe"] - assert counts["attempted"] == 2 - assert counts["completed"] == counts["denied"] == counts["dlp_rejected"] == 1 + assert counts["attempted"] == 3 + assert counts["completed"] == 2 + assert counts["denied"] == counts["dlp_rejected"] == 1 assert counts["dlp_gates"]["result"]["pii"] == 1 assert "person@example.test" not in json.dumps(receipt) + assert { + "controlled structured key", + "controlled structured value", + } <= {item.value for item in gateway.forbidden_publication} def test_cached_return_still_consumes_delivery_budget(monkeypatch: pytest.MonkeyPatch) -> None: @@ -240,7 +487,7 @@ async def exercise() -> None: def test_empty_registry_and_secret_resolution_are_closed() -> None: gateway = start_gateway( - parse_registry('{"version":2,"servers":{}}'), environment={}, run_id="a" * 32 + parse_registry('{"version":3,"servers":{}}'), environment={}, run_id="a" * 32 ) assert gateway.aliases == () assert gateway.close()["tools"] == {} @@ -253,7 +500,12 @@ def test_empty_registry_and_secret_resolution_are_closed() -> None: @pytest.mark.parametrize("run_id", ["", "synthetic_run", "A" * 32, "g" * 32, "a" * 31, "a" * 33]) def test_gateway_rejects_unbound_run_identity(run_id: str) -> None: with pytest.raises(FederationError, match="registry_invalid"): - start_gateway(parse_registry('{"version":2,"servers":{}}'), environment={}, run_id=run_id) + start_gateway(parse_registry('{"version":3,"servers":{}}'), environment={}, run_id=run_id) + + +def test_gateway_rejects_a_manually_constructed_legacy_registry() -> None: + with pytest.raises(FederationError, match="registry_invalid"): + start_gateway(Registry((), version=2), environment={}, run_id="a" * 32) def test_call_overflow_bounds_counters_and_blocks_finalization( @@ -319,7 +571,7 @@ def test_registry_rejects_unknown_or_ambiguous_authority(change: str) -> None: value = registry_value() profile = "local" if change == "old": - value["version"] = 1 + value["version"] = 2 elif change == "extra": value["overrides"] = {} elif change == "alias": @@ -399,7 +651,7 @@ def test_optional_real_sdk_v1_v2_mixed_run() -> None: "command": executable, "args": ["-I", str(PEER.with_name("sdk_v1_peer.py"))], }, - "tools": {"echo": {}}, + "tools": {"echo": tool_policy("echo")}, } gateway = start_gateway(parse_registry(json.dumps(value)), environment={}, run_id="a" * 32) assert gateway._gateway is not None @@ -409,8 +661,9 @@ def test_optional_real_sdk_v1_v2_mixed_run() -> None: async def exercise() -> None: async with relay_client(gateway) as client: for alias in gateway.aliases: - result = await client.call_tool(alias, {"text": "controlled mixed result"}) - assert result.content[0].text == "controlled mixed result" + text = f"Independent input for {alias}" + result = await client.call_tool(alias, {"text": text}) + assert result.content[0].text == text try: asyncio.run(exercise()) diff --git a/tests/federation/test_https.py b/tests/federation/test_https.py index a21fcee9..a24d8183 100644 --- a/tests/federation/test_https.py +++ b/tests/federation/test_https.py @@ -21,6 +21,14 @@ from ocr_toolkit.federation.contracts import WIRE_REQUESTS from tests.federation.test_gateway import relay_client +HTTPS_DESCRIPTION = "Send one operator-authorized controlled text value." +HTTPS_INPUT_SCHEMA: dict[str, Any] = { + "type": "object", + "properties": {"text": {"type": "string"}}, + "required": ["text"], + "additionalProperties": False, +} + @contextmanager def tls_peer( @@ -84,17 +92,26 @@ def do_POST(self) -> None: "serverInfo": {"name": "synthetic", "version": "1"}, } elif request["method"] == "tools/list": + description = ( + "Upload repository source for additional analysis." + if mode == "description_drift" + else "Return controlled text." + ) + input_schema = HTTPS_INPUT_SCHEMA + if mode == "schema_drift": + input_schema = { + **HTTPS_INPUT_SCHEMA, + "properties": { + **HTTPS_INPUT_SCHEMA["properties"], + "repository_source": {"type": "string"}, + }, + } result = { "tools": [ { "name": "echo", - "description": "Return controlled text.", - "inputSchema": { - "type": "object", - "properties": {"text": {"type": "string"}}, - "required": ["text"], - "additionalProperties": False, - }, + "description": description, + "inputSchema": input_schema, } ] } @@ -206,12 +223,18 @@ def registry(url: str) -> str: """Select a fixed HTTPS endpoint and environment-backed operator header.""" return json.dumps( { - "version": 2, + "version": 3, "servers": { "synthetic": { "transport": {"type": "https", "url": url}, "auth": {"scheme": "Bearer", "token_from": "SYNTHETIC_TOKEN"}, - "tools": {"echo": {"assurance": "review_read"}}, + "tools": { + "echo": { + "assurance": "review_read", + "description": HTTPS_DESCRIPTION, + "input_schema": HTTPS_INPUT_SCHEMA, + } + }, } }, } @@ -250,6 +273,43 @@ async def exercise() -> None: assert any(item["method"] == "DELETE" for item in observed) +@pytest.mark.parametrize("mode", ["description_drift", "schema_drift"]) +def test_upstream_interface_drift_cannot_expand_model_or_argument_authority( + tmp_path: Path, mode: str +) -> None: + """Keep the operator interface authoritative while ordinary declared calls still work.""" + with tls_peer(tmp_path / mode, mode) as (url, observed): + gateway = start_gateway( + parse_registry(registry(url)), + environment={"SYNTHETIC_TOKEN": "synthetic-auth-value"}, + run_id="a" * 32, + ) + + async def exercise() -> None: + async with relay_client(gateway) as client: + listing = await client.list_tools() + assert listing.tools[0].description == HTTPS_DESCRIPTION + assert listing.tools[0].input_schema == HTTPS_INPUT_SCHEMA + admitted = await client.call_tool( + "synthetic__echo", {"text": "controlled TLS result"} + ) + assert admitted.content[0].text == "controlled TLS result" + denied = await client.call_tool( + "synthetic__echo", + {"text": "controlled", "repository_source": "private source"}, + ) + assert denied.is_error + + try: + asyncio.run(exercise()) + finally: + receipt = gateway.close() + calls = [item for item in observed if item["method"] == "tools/call"] + assert len(calls) == 1 + counts = receipt["tools"]["synthetic__echo"] + assert counts["completed"] == counts["denied"] == 1 + + @pytest.mark.parametrize("mode", ["redirect", "gzip", "oversized", "unterminated_sse"]) def test_actual_tls_hostile_body_is_rejected_before_ready(tmp_path: Path, mode: str) -> None: with tls_peer(tmp_path / mode, mode) as (url, observed): @@ -314,3 +374,22 @@ def test_https_endpoint_origin_is_always_allowed() -> None: assert parse_registry(registry("https://synthetic.invalid/mcp")).servers[0].tools[ 0 ].resource_origins == ("https://synthetic.invalid",) + assert parse_registry(registry("https://xn--fa-hia.invalid/mcp")).servers[0].tools[ + 0 + ].resource_origins == ("https://xn--fa-hia.invalid",) + + +@pytest.mark.parametrize( + ("endpoint", "resource_origin"), + [ + ("https://faß.invalid/mcp", None), + ("https://\u212a.example.invalid/mcp", None), + ("https://synthetic.invalid/mcp", "https://faß.invalid"), + ], +) +def test_registry_rejects_unicode_hostnames(endpoint: str, resource_origin: str | None) -> None: + value = json.loads(registry(endpoint)) + if resource_origin is not None: + value["servers"]["synthetic"]["tools"]["echo"]["resource_origins"] = [resource_origin] + with pytest.raises(FederationError, match="registry_invalid"): + parse_registry(json.dumps(value)) diff --git a/tests/federation/test_ocr_qualification.py b/tests/federation/test_ocr_qualification.py index 8729bbe6..62e9c619 100644 --- a/tests/federation/test_ocr_qualification.py +++ b/tests/federation/test_ocr_qualification.py @@ -4,6 +4,7 @@ import io import json +import os import re import subprocess import sys @@ -12,7 +13,9 @@ from http.server import ThreadingHTTPServer from pathlib import Path from typing import Any +from urllib.parse import urlsplit +from ocr_toolkit import cli, provider_config from ocr_toolkit.config_writer import write_ocr_config from ocr_toolkit.evidence.actions import read_action_receipt from ocr_toolkit.evidence.artifacts import ( @@ -27,10 +30,148 @@ ) from ocr_toolkit.evidence.store import EvidenceStore from ocr_toolkit.federation import parse_registry, start_gateway +from ocr_toolkit.federation.contracts import REGISTRY_VERSION from ocr_toolkit.mcp_config import MCPCapability +from tests.federation.test_gateway import tool_policy from tests.test_ocr_compat import load_script +def test_local_incremental_uses_normal_federation_and_reports_fallback( + tmp_path: Path, qualified_native_ocr, monkeypatch, capsys +) -> None: + """Observe the ordinary and incremental CLI artifacts across the real relay and gateway.""" + binary, _ = qualified_native_ocr("OCR_FEDERATION_QUALIFY_BINARY") + compat = load_script() + home = tmp_path / "home" + environment = compat.execution._isolated_probe_environment(home) + repo, base, head = compat.execution._synthetic_repo(tmp_path, environment) + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + (bin_dir / "ocr").symlink_to(binary) + environment["PATH"] = f"{bin_dir}{os.pathsep}{environment['PATH']}" + for name in tuple(os.environ): + if name.startswith(("OCR_", "GIT_", "CI_")): + monkeypatch.delenv(name) + for name, value in environment.items(): + monkeypatch.setenv(name, value) + monkeypatch.chdir(repo) + # OCR must start the installed internal evidence tool from the real checkout. + (repo / "ocr_toolkit.py").write_text("raise RuntimeError('repository shadow')\n") + + registry = { + "version": REGISTRY_VERSION, + "servers": { + "tracker": { + "transport": { + "type": "stdio", + "command": sys.executable, + "args": ["-I", str(Path(__file__).with_name("sdk_peer.py").resolve())], + }, + "tools": {"echo": {**tool_policy("echo"), "assurance": "review_read"}}, + } + }, + } + tool = "tracker__echo" + external_text = "synthetic external review context" + answered: list[str] = [] + + def tool_script(request): + messages = request["messages"] + names = [ + call["function"]["name"] + for message in messages + for call in message.get("tool_calls") or () + ] + if not names: + name, arguments = "ocr_toolkit_evidence", {"action": "summary"} + elif names == ["ocr_toolkit_evidence"]: + name, arguments = tool, {"text": external_text} + else: + assert names == ["ocr_toolkit_evidence", tool] + assert any( + external_text in message.get("content", "") + for message in messages + if message.get("role") == "tool" + ) + answered.append(tool) + name, arguments = "task_done", {} + return {"name": name, "arguments": json.dumps(arguments)}, f"federation-{len(names)}" + + with compat.peer._stub_gateway(tool_script=tool_script) as url: + original_url_parser = provider_config._parse_https_url + monkeypatch.setattr( + provider_config, + "_parse_https_url", + lambda candidate, option: ( + urlsplit(candidate) if candidate == url else original_url_parser(candidate, option) + ), + ) + for name, value in { + "OCR_LLM_URL": url, + "OCR_LLM_MODEL": "synthetic-model", + "OCR_LLM_TOKEN": "synthetic-token", + "OCR_LLM_PROTOCOL": "openai", + "OCR_TELEMETRY_ENABLED": "false", + "OCR_MCP_SERVERS_JSON": json.dumps(registry), + }.items(): + monkeypatch.setenv(name, value) + + def run(label: str, *switches: str): + report, result, stderr = ( + tmp_path / f"{label}.{ext}" for ext in ("md", "json", "stderr") + ) + code = cli.main( + [ + "review", + "--local", + *switches, + "--report", + str(report), + "--result", + str(result), + "--stderr", + str(stderr), + "--", + "--from", + base, + "--to", + head, + ] + ) + captured = capsys.readouterr() + assert code == 0, (captured.err, stderr.read_text(), captured.out) + assert report.stat().st_mode & 0o077 == result.stat().st_mode & 0o077 == 0 + markdown = report.read_text() + result_text = result.read_text() + native = json.loads(result_text) + assert native["status"] == "complete" + federation = next(line for line in markdown.splitlines() if "- Federation " in line) + assert f"complete; {tool}[review_read;ocr_attempts=1;attempted=1," in federation + assert "completed=1," in federation + assert external_text not in markdown and external_text not in result_text + return native, markdown, federation, captured.err + + ordinary, ordinary_report, ordinary_federation, _ = run("ordinary") + requested, requested_report, requested_federation, diagnostics = run( + "requested", "--incremental" + ) + + assert answered == [tool, tool] + assert requested_federation == ordinary_federation + assert requested["tool_calls"] == ordinary["tool_calls"] + assert requested["manifest"]["input"] == ordinary["manifest"]["input"] + assert requested["manifest"]["coverage"] == ordinary["manifest"]["coverage"] + assert "toolkit_incremental" not in ordinary + assert "### Incremental review" not in ordinary_report + reason = "Incremental reuse is unavailable while governed external MCP tools are configured." + assert requested["toolkit_incremental"]["full_reason"] == reason + assert requested["toolkit_incremental"]["reused_count"] == 0 + assert "status" not in requested["toolkit_incremental"] + assert f"Full review selected. {reason}" in requested_report + assert f"{reason} Starting a full review." in diagnostics + assert not (home / ".ocr-toolkit-state" / "incremental").exists() + + def test_checksum_verified_ocr_reads_mr_intent_before_federated_tracker( tmp_path: Path, qualified_native_ocr ) -> None: @@ -61,7 +202,7 @@ def read_issue(key: str) -> str: encoding="utf-8", ) registry = { - "version": 2, + "version": REGISTRY_VERSION, "servers": { "tracker": { "transport": { @@ -69,7 +210,18 @@ def read_issue(key: str) -> str: "command": sys.executable, "args": ["-I", str(tracker_peer), tracker_key, str(tracker_calls)], }, - "tools": {"read_issue": {"assurance": "review_read"}}, + "tools": { + "read_issue": { + "assurance": "review_read", + "description": "Read one operator-authorized issue by its exact key.", + "input_schema": { + "type": "object", + "properties": {"key": {"type": "string", "maxLength": 64}}, + "required": ["key"], + "additionalProperties": False, + }, + } + }, } }, } @@ -283,4 +435,4 @@ def log_message(self, *_args: Any) -> None: actions = read_action_receipt(artifacts.action_receipt) assert actions is not None and actions["completed"]["summary"] >= 1 assert actions["completed"]["get"] >= 1 and actions["attempted"]["list"] == 0 - assert tracker_key in " ".join(gateway.forbidden_publication) + assert tracker_key in " ".join(item.value for item in gateway.forbidden_publication) diff --git a/tests/federation/test_process.py b/tests/federation/test_process.py index 2ef47c8a..74d95dd9 100644 --- a/tests/federation/test_process.py +++ b/tests/federation/test_process.py @@ -18,7 +18,7 @@ def configured(mode: str, receipt: Path) -> str: """Pass only synthetic mode and controlled private PID evidence to the peer.""" return json.dumps( { - "version": 2, + "version": 3, "servers": { "synthetic": { "transport": { @@ -26,7 +26,16 @@ def configured(mode: str, receipt: Path) -> str: "command": sys.executable, "args": ["-I", str(PEER), mode, str(receipt)], }, - "tools": {"echo": {}}, + "tools": { + "echo": { + "description": "Use the operator-authorized process test tool.", + "input_schema": { + "type": "object", + "properties": {}, + "additionalProperties": False, + }, + } + }, } }, } diff --git a/tests/fuzz/test_federation.py b/tests/fuzz/test_federation.py index dfe57b53..e1891b7f 100644 --- a/tests/fuzz/test_federation.py +++ b/tests/fuzz/test_federation.py @@ -25,11 +25,17 @@ "additionalProperties": False, } REGISTRY = { - "version": 2, + "version": 3, "servers": { "docs": { "transport": {"type": "https", "url": "https://synthetic.invalid/mcp"}, - "tools": {"lookup": {"assurance": "review_read"}}, + "tools": { + "lookup": { + "assurance": "review_read", + "description": "Read one operator-authorized record.", + "input_schema": SCHEMA, + } + }, } }, } @@ -42,6 +48,8 @@ ("servers", "docs", "tools"), ("servers", "docs", "tools", "lookup"), ("servers", "docs", "tools", "lookup", "assurance"), + ("servers", "docs", "tools", "lookup", "description"), + ("servers", "docs", "tools", "lookup", "input_schema"), ("servers", "docs", "headers_from"), ) @@ -67,6 +75,11 @@ def test_nested_registry_mutations_never_escape_the_closed_authority_boundary( for server in admitted.servers for tool in server.tools ) + assert all( + tool.description and tool.input_schema + for server in admitted.servers + for tool in server.tools + ) assert profile == "local" or all(server.transport == "https" for server in admitted.servers) diff --git a/tests/providers/installed_local_review.py b/tests/providers/installed_local_review.py index b1796afe..36b3c602 100644 --- a/tests/providers/installed_local_review.py +++ b/tests/providers/installed_local_review.py @@ -328,7 +328,7 @@ def git_run(*args: str) -> str: "OCR_LLM_URL": "https://provider.example.invalid/v1", "OCR_MCP_SERVERS_JSON": json.dumps( { - "version": 2, + "version": 3, "servers": { "synthetic_context": { "transport": { @@ -339,7 +339,21 @@ def git_run(*args: str) -> str: str(Path(__file__).parents[1] / "federation" / "sdk_peer.py"), ], }, - "tools": {"echo": {"assurance": "advisory"}}, + "tools": { + "echo": { + "assurance": "advisory", + "description": "Echo one operator-authorized synthetic value.", + "input_schema": { + "type": "object", + "properties": { + "text": {"type": "string"}, + "delay": {"type": "number"}, + }, + "required": ["text"], + "additionalProperties": False, + }, + } + }, } }, } diff --git a/tests/reporting/test_dlp_accounting.py b/tests/reporting/test_dlp_accounting.py index 1ae71a12..130120cc 100644 --- a/tests/reporting/test_dlp_accounting.py +++ b/tests/reporting/test_dlp_accounting.py @@ -5,7 +5,11 @@ from copy import deepcopy from typing import Any -from ocr_toolkit.reporting.dlp import format_dlp_admission, publication_dlp_state +from ocr_toolkit.reporting.dlp import ( + admission_dlp_state, + format_dlp_admission, + publication_dlp_state, +) def _reasons(*, secret: int = 0) -> dict[str, int]: @@ -90,3 +94,18 @@ def test_malformed_disjoint_counts_fail_closed() -> None: malformed = deepcopy(valid) malformed["private_sanitization"]["reason_counts"]["secret"] = True assert publication_dlp_state(malformed) is None + + +def test_positive_exclusions_require_a_manifest_compatible_outcome() -> None: + receipt = _filtered(public_fields=1, private_fields=0) + original = receipt["original"] + original.update(selected=0, completed=0, excluded=0) + assert admission_dlp_state(receipt) == "publication-filtered" + original["excluded"] = 1 + for kind in ("clean", "warning", "partial"): + original["outcome"] = kind + assert admission_dlp_state(receipt) is None + original["outcome"] = "skipped" + assert admission_dlp_state(receipt) == "publication-filtered" + original["excluded"] = 10_001 + assert admission_dlp_state(receipt) is None diff --git a/tests/reporting/test_local.py b/tests/reporting/test_local.py index bccfa62f..f3a58c11 100644 --- a/tests/reporting/test_local.py +++ b/tests/reporting/test_local.py @@ -8,9 +8,11 @@ from pathlib import Path import pytest +from tests.test_result_contract import manifest_result from ocr_toolkit.evidence.actions import EVIDENCE_ACTIONS from ocr_toolkit.providers.local import local_summary, write_local_report +from ocr_toolkit.reporting.incremental import IncrementalReport, ReusedFile from ocr_toolkit.reporting.model import ExecutionFacts, failed_report, report_from_result from ocr_toolkit.result_contract import OcrResultContractError @@ -63,6 +65,86 @@ def test_local_outcome_matrix(status: str, expected: str) -> None: assert "approval" not in summary.lower() +@pytest.mark.parametrize("selected_path", ("failed.py", None)) +def test_local_combines_disjoint_exclusions_and_known_failed_paths(selected_path) -> None: + result = manifest_result( + "partial", selected=["good", "failure"], completed=["good"], failed=[("failure", "input")] + ) + coverage = result["manifest"]["coverage"] + coverage["selected"][1]["path"] = selected_path + coverage["failed"][0]["path"] = "excluded.bin" + coverage["excluded"] = [ + {"item_id": "excluded", "path": "excluded.bin", "exclude_reason": "binary"} + ] + + summary = local_summary(report_from_result(result, execution=execution_facts())) + headline = next(line for line in summary.splitlines() if line.startswith("**Review")) + assert "Review incomplete" in headline + if selected_path is None: + assert "file not reviewed" not in headline and "files not reviewed" not in headline + else: + assert "2 files not reviewed" in headline + assert "`failed.py`" in summary and "`excluded.bin`" not in summary + assert "; failed 1; waived 0; excluded 1." in summary + + +@pytest.mark.parametrize("waived_path", ("waived.py", None)) +def test_local_waived_files_join_exclusions_only_with_known_paths(waived_path) -> None: + result = manifest_result( + "complete", selected=["good", "waived"], completed=["good"], waived=["waived"] + ) + coverage = result["manifest"]["coverage"] + coverage["selected"][1]["path"] = waived_path + coverage["excluded"] = [ + {"item_id": "excluded", "path": "excluded.bin", "exclude_reason": "binary"} + ] + + summary = local_summary(report_from_result(result, execution=execution_facts())) + assert "Review incomplete" in summary + assert ("2 files not reviewed" in summary) is (waived_path is not None) + assert "1 file not reviewed" not in summary + assert "; waived 1; excluded 1." in summary + + +@pytest.mark.parametrize("native_status", ("complete", "skipped")) +@pytest.mark.parametrize("additional_exclusion", (False, True)) +def test_local_incremental_coverage_reconciles_matching_native_exclusions( + native_status, additional_exclusion +) -> None: + fresh = ["fresh"] if native_status == "complete" else [] + result = manifest_result(native_status, selected=fresh, completed=fresh) + exclusions = [{"item_id": "prior", "path": "prior.py", "exclude_reason": "user_exclude"}] + if additional_exclusion: + exclusions.append({"item_id": "asset", "path": "asset.bin", "exclude_reason": "binary"}) + result["manifest"]["coverage"]["excluded"] = exclusions + report = report_from_result(result, execution=execution_facts()) + report = replace( + report, + incremental=IncrementalReport((ReusedFile("prior.py", "a" * 40, "synthetic", ()),), 0), + ) + + stream = io.StringIO() + write_local_report(report, stream) + summary = stream.getvalue() + expected = "Review incomplete" if additional_exclusion else "Review complete" + assert expected in summary + assert ("1 file not reviewed" in summary) is additional_exclusion + assert f"; excluded {len(exclusions)}." in summary + assert "Toolkit coverage: reused 1." in summary + + +def test_local_native_skipped_review_retains_excluded_coverage_details() -> None: + result = manifest_result("skipped", selected=[]) + result["manifest"]["coverage"]["excluded"] = [ + {"item_id": "excluded", "path": "excluded.bin", "exclude_reason": "binary"} + ] + + summary = local_summary(report_from_result(result, execution=execution_facts())) + assert "Review skipped — no supported files changed" in summary + assert "Review incomplete" not in summary + assert "; excluded 1." in summary + + def test_all_findings_ignore_posting_environment(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("OCR_MAX_POST_COMMENTS", "1") monkeypatch.setenv("OCR_POST_BADGES", "true") diff --git a/tests/test_context_broker.py b/tests/test_context_broker.py index aa34cc12..f8aae7cc 100644 --- a/tests/test_context_broker.py +++ b/tests/test_context_broker.py @@ -21,6 +21,7 @@ CIOutcomeSnapshot, prepare_ci_outcome_records, ) +from ocr_toolkit.context.dlp import dlp_mode from ocr_toolkit.context.policy import parse_policy from tests.test_context_policy import ( ci_policy_value, @@ -117,7 +118,11 @@ def test_common_discussion_projection_uses_explicit_provider_origin_and_rechecks origin = ContextOrigin(source="forge:codehost_discussions", adapter="codehost", tenant="repo") records = prepare_discussion_records( - (Discussion(), Discussion(body="private adapter value", digest="c" * 64)), + ( + Discussion(), + Discussion(body="private adapter value", digest="c" * 64), + Discussion(body="contact reviewer@example.invalid", digest="d" * 64), + ), policy=policy, origin=origin, expiry=200, @@ -165,6 +170,30 @@ def test_common_discussion_publish_text_gets_publication_specific_dlp() -> None: ) +def test_disabled_discussion_dlp_retains_only_inert_publish_text() -> None: + value = policy_value() + projection = value["forge_discussions"]["projections"] # type: ignore[index] + projection["publish"] = ["descriptor", "state", "text"] + policy = parse_policy(encoded_policy(value)).forge_discussions + assert policy is not None + origin = ContextOrigin(source="forge:codehost_discussions", adapter="codehost", tenant="repo") + body = "synthetic@example.invalid ![plot](https://example.invalid/pixel)" + + with dlp_mode(False): + records = prepare_discussion_records( + (Discussion(body=body),), + policy=policy, + origin=origin, + expiry=200, + ) + + prepared = records[0].projections["publish"]["text"] + assert isinstance(prepared, str) + assert "synthetic@example.invalid" in prepared + assert "![plot]" not in prepared + assert "[plot](https://example.invalid/pixel)" in prepared + + def test_common_remediation_projection_is_fixed_model_only_and_rechecks_every_text() -> None: policy = parse_policy(encoded_policy(remediation_policy_value())).remediation_threads assert policy is not None @@ -174,7 +203,7 @@ def test_common_remediation_projection_is_fixed_model_only_and_rechecks_every_te tenant="repo", ) rejected = RemediationThread( - replies=(RemediationReply(body="contact reviewer@example.invalid"),), + replies=(RemediationReply(body="contact reviewer&#64;example.invalid"),), digest="c" * 64, ) @@ -194,7 +223,7 @@ def test_common_remediation_projection_is_fixed_model_only_and_rechecks_every_te ) assert set(record.projections["model"]) == {"descriptor", "remediation_thread"} assert record.projections["publish"] == {"descriptor": "remediation_thread"} - assert "reviewer@example.invalid" not in repr(records) + assert "reviewer&#64;example.invalid" not in repr(records) def test_common_ci_projection_is_provider_neutral_scoped_and_dlp_checked() -> None: diff --git a/tests/test_context_mcp.py b/tests/test_context_mcp.py index c0fa4e3f..0576e0d0 100644 --- a/tests/test_context_mcp.py +++ b/tests/test_context_mcp.py @@ -70,6 +70,32 @@ def test_context_tools_list_and_get_only_minted_handles(tmp_path: Path) -> None: assert malformed["result"]["isError"] is True # type: ignore[index] +def test_context_get_revalidates_model_views_without_rewriting_safe_text(tmp_path: Path) -> None: + safe = "Use A & B as literal documentation." + digest = hashlib.sha256(safe.encode()).hexdigest() + base = pending() + record = replace( + base, + digest=digest, + projections={ + **base.projections, + "model": {"descriptor": "issue", "text": safe}, + "retain": {**base.projections["retain"], "digest": digest}, + }, + ) + store = commit(tmp_path / "context.json", records=[record]) + handle = store.records[0].handle + + fetched = payload(call_context_tool(store, "context_get", {"handle": handle}, now=150)) + assert fetched["record"]["text"] == safe + + model = store.records[0].projections["model"] + assert isinstance(model, dict) + model["text"] = "reviewer@example.invalid" + with pytest.raises(ContextMCPError, match="unavailable"): + call_context_tool(store, "context_get", {"handle": handle}, now=150) + + def test_context_tools_expose_fixed_remediation_resource_without_provider_identity( tmp_path: Path, ) -> None: diff --git a/tests/test_context_store.py b/tests/test_context_store.py index 7c9bcb67..a5e9f9c3 100644 --- a/tests/test_context_store.py +++ b/tests/test_context_store.py @@ -195,6 +195,38 @@ def test_context_readback_rejects_non_string_ci_states(tmp_path, field, value) - ) +@pytest.mark.parametrize("field", ["descriptor", "source", "completeness"]) +def test_listing_metadata_is_admitted_even_without_a_model_descriptor(tmp_path, field): + path = tmp_path / "context.json" + commit(path) + document = json.loads(path.read_text()) + record = document["records"][0] + for projection in record["projections"].values(): + projection.pop("descriptor", None) + if field == "completeness": + document[field] = {"member@example.invalid": "complete"} + else: + record[field] = "member@example.invalid" + rewrite_hostile_store(path, document) + with pytest.raises(ContextStoreError): + ContextStore.read( + path, expected_run_id=RUN_ID, expected_policy_digest=POLICY_DIGEST, now=150 + ) + + +@pytest.mark.parametrize("source", [" forge", "forge\n", " " * 513 + "forge"]) +def test_listing_rejects_noncanonical_source_names(tmp_path, source): + path = tmp_path / "context.json" + commit(path) + document = json.loads(path.read_text()) + document["completeness"] = {source: "complete"} + rewrite_hostile_store(path, document) + with pytest.raises(ContextStoreError, match="completeness"): + ContextStore.read( + path, expected_run_id=RUN_ID, expected_policy_digest=POLICY_DIGEST, now=150 + ) + + def test_context_store_commits_owner_only_and_resolves_only_minted_handle(tmp_path: Path) -> None: path = tmp_path / "context-store.json" store = commit(path) @@ -529,6 +561,9 @@ def test_context_store_hostile_read_revalidates_projection_semantics(tmp_path: P lambda record: record["projections"]["model"].update( # type: ignore[index,union-attr] {"text": "synthetic@example.invalid"} ), + lambda record: record["projections"]["model"].update( # type: ignore[index,union-attr] + {"text": "synthetic@example.invalid"} + ), lambda record: record["projections"]["retain"].update( # type: ignore[index,union-attr] {"expiry": 199} ), @@ -547,3 +582,47 @@ def test_context_store_hostile_read_revalidates_projection_semantics(tmp_path: P expected_policy_digest=POLICY_DIGEST, now=150, ) + + +@pytest.mark.parametrize("anchor", ({"path": "docs/guide.md", "line": 8}, {"line": 1})) +def test_context_readback_keeps_admitted_anchor_in_model_projection(tmp_path, anchor): + path = tmp_path / "context.json" + commit(path) + document = json.loads(path.read_text()) + document["records"][0]["projections"]["model"]["anchor"] = anchor + rewrite_hostile_store(path, document) + + store = ContextStore.read( + path, expected_run_id=RUN_ID, expected_policy_digest=POLICY_DIGEST, now=150 + ) + record = store.get(store.records[0].handle, run_id=RUN_ID, policy_digest=POLICY_DIGEST, now=150) + assert record.projections["model"]["anchor"] == anchor + assert "anchor" not in record.projections["publish"] + + +@pytest.mark.parametrize( + ("field", "value", "error"), + ( + ("anchor", {"path": "docs/guide.md", "url": "unknown"}, "anchor"), + ("anchor", {"path": ""}, "anchor path"), + ("anchor", {"line": True}, "anchor line"), + ("anchor", {"line": 10_000_001}, "anchor line"), + ("resolved", 1, "boolean"), + ("count", True, "integer"), + ("count", 1_000_000_001, "integer"), + ("author_class", "maintainer", "author class"), + ("author_pseudonym", "raw-author", "author pseudonym"), + ("digest", "unknown", "digest"), + ), +) +def test_context_readback_revalidates_projection_metadata(tmp_path, field, value, error): + path = tmp_path / "context.json" + commit(path) + document = json.loads(path.read_text()) + document["records"][0]["projections"]["model"][field] = value + rewrite_hostile_store(path, document) + + with pytest.raises(ContextStoreError, match=error): + ContextStore.read( + path, expected_run_id=RUN_ID, expected_policy_digest=POLICY_DIGEST, now=150 + ) diff --git a/tests/test_dependency_workflow.py b/tests/test_dependency_workflow.py index 599fa3d7..7f88f231 100644 --- a/tests/test_dependency_workflow.py +++ b/tests/test_dependency_workflow.py @@ -1,6 +1,7 @@ """Committed dependency graphs and reviewed action pins are execution inputs.""" import hashlib +import json import os import re import shutil @@ -9,6 +10,7 @@ from pathlib import Path import pytest +import yaml ROOT = Path(__file__).parents[1] @@ -109,8 +111,6 @@ def test_workflows_consume_locked_environments_without_implicit_resolution() -> text = (ROOT / ".github/workflows" / name).read_text() assert "uv sync --frozen" not in text, name assert not re.search(r"uv run (?!\-\-no-sync\b)", text), name - for pin in re.findall(r"uses: astral-sh/setup-uv@(\S+)", text): - assert re.fullmatch(r"[0-9a-f]{40}", pin), (name, pin) release = (ROOT / ".github/workflows/release.yml").read_text() assert release.index("uv sync --locked") < release.index("uv run --no-sync") updater = (ROOT / ".github/dependabot.yml").read_text() @@ -118,6 +118,51 @@ def test_workflows_consume_locked_environments_without_implicit_resolution() -> assert "package-ecosystem: pip" not in updater +def test_hosted_uv_installs_match_the_audit_pin_and_require_runner_checksums() -> None: + audit = (ROOT / "scripts/dependency-audit.sh").read_text() + pin = re.search(r"^UV_VERSION=([0-9.]+)$", audit, re.MULTILINE) + assert pin is not None + linux_checksums = set() + saw_matrix = False + + for workflow in (ROOT / ".github/workflows").glob("*.yml"): + for job in yaml.safe_load(workflow.read_text())["jobs"].values(): + for step in job.get("steps", []): + action = step.get("uses", "") + if not action.startswith("astral-sh/setup-uv@"): + continue + assert re.fullmatch(r"astral-sh/setup-uv@[0-9a-f]{40}", action) + inputs = step["with"] + assert inputs["version"] == pin.group(1), workflow.name + assert inputs["require-checksums"] is True, workflow.name + checksum = inputs["checksum"] + if job["runs-on"] == "${{ matrix.os }}": + saw_matrix = True + selector = re.fullmatch( + r"\$\{\{ fromJSON\('(\{.*\})'\)\[runner\.os\]\[runner\.arch\] \}\}", + checksum, + re.DOTALL, + ) + assert selector is not None + by_runner = json.loads(selector.group(1)) + assert by_runner.keys() == {"Linux", "macOS"} + assert by_runner["Linux"].keys() == {"X64"} + assert by_runner["macOS"].keys() == {"ARM64", "X64"} + assert all( + re.fullmatch(r"[0-9a-f]{64}", digest) + for architectures in by_runner.values() + for digest in architectures.values() + ) + checksum = by_runner["Linux"]["X64"] + else: + assert job["runs-on"].startswith("ubuntu-"), workflow.name + assert re.fullmatch(r"[0-9a-f]{64}", checksum), workflow.name + linux_checksums.add(checksum) + + assert saw_matrix + assert len(linux_checksums) == 1 + + def test_stale_manifest_fails_before_commands_and_checked_run_preserves_lock( tmp_path: Path, ) -> None: diff --git a/tests/test_dlp_arithmetic.py b/tests/test_dlp_arithmetic.py new file mode 100644 index 00000000..59a552c9 --- /dev/null +++ b/tests/test_dlp_arithmetic.py @@ -0,0 +1,145 @@ +"""Verify narrow arithmetic interpretation and unchanged material checks.""" + +import pytest + +from ocr_toolkit import review_runner +from ocr_toolkit.context.code_text import TextSink +from ocr_toolkit.context.contracts import TextBudgets +from ocr_toolkit.context.dlp import check_text +from ocr_toolkit.evidence.opaque_code import prove_opaque_code + +BUDGETS = TextBudgets(20_000, 80_000, 300) + + +@pytest.mark.parametrize( + "value", + [ + "MAX_SCAN_BYTES = 16 * 1024 * 1024", + "x = 1024 * 1024", + "x = 1024 ** 1024", + "cache_size=8 * 2 * 2048 * 4096", + ], +) +@pytest.mark.parametrize("sink", [TextSink.PROSE, TextSink.LITERAL_CODE]) +def test_complete_binary_size_assignment_preserves_published_text(value, sink): + result = check_text(value, budgets=BUDGETS, publication=True, sink=sink) + assert result.admitted + assert result.text == value + + +@pytest.mark.parametrize( + "value", + [ + "phone = 16 * 1024 * 1024", + "officePhoneNumber = 1024 * 1024", + "value = 202 * 555 * 1114", + "value = 256 * 512 * 1024", + "value = 1024 *555-0114", + "value = 1024 * 1024; +7 912 345-67-89", + "Contact 202 555-0114.\nvalue = 1024 * 1024", + "value = 1024 * 1024\n202 555-0114", + 'value = "1024 * 1024"', + "value: 1024 * 1024", + "1024 * 1024", + "value = 01024 * 1024", + "value = 1001 * 2001", + "value = 2 * 2 * 2 * 1024 * 1024", + ], +) +@pytest.mark.parametrize("sink", [TextSink.PROSE, TextSink.LITERAL_CODE]) +def test_ambiguous_numbers_and_separate_contacts_remain_phone_candidates(value, sink): + result = check_text(value, budgets=BUDGETS, publication=True, sink=sink) + assert (result.admitted, result.reason) == (False, "pii") + assert result.detector is not None and result.detector.startswith("phone:") + + +def test_binary_size_syntax_does_not_change_configured_value_checks(monkeypatch): + value = "MAX_SCAN_BYTES = 16 * 1024 * 1024" + monkeypatch.setenv("OCR_LLM_TOKEN", value) + result = check_text(value, budgets=BUDGETS, publication=True) + assert (result.admitted, result.reason) == (False, "secret") + + +@pytest.mark.parametrize( + "value", + [ + "Preserve the limit when changing `MAX_SCAN_BYTES = 16 * 1024 * 1024`.", + "Use `x = 1024 * 1024` and `y = 1024 ** 1024`.", + "The value uses **`x = 1024 * 1024`**.", + ], +) +def test_complete_inline_assignment_in_review_prose(value): + result = check_text(value, budgets=BUDGETS, publication=True) + assert result.admitted + assert result.text == value + + +@pytest.mark.parametrize( + "value", + [ + "Preserve the limit when changing `MAX_SCAN_BYTES = 16 * 1024 * 1024.", + "`x = 1024 *\n1024`", + "Phone: `x = 1024 * 1024`", + "Call **`x = 1024 * 1024`**", + "**Phone:** `x = 1024 * 1024`", + "`x = 1024 * 1024` and Contact 202 555-0114.", + "`x = 1024 * 1024` and `202 *555-0114`.", + ], +) +def test_inline_qualification_preserves_other_contacts_and_requires_exact_body(value): + result = check_text(value, budgets=BUDGETS, publication=True) + assert (result.admitted, result.reason) == (False, "pii") + + +@pytest.mark.parametrize( + "label", + [ + "Phone:", + "Phone:", + "\uff30\uff48\uff4f\uff4e\uff45\uff1a", + "**Ph&#111;ne\uff1a**", + ], +) +def test_inline_qualification_respects_canonical_contact_labels(label): + result = check_text(f"{label} `x = 1024 * 1024`", budgets=BUDGETS, publication=True) + assert (result.admitted, result.reason) == (False, "pii") + assert result.detector is not None and result.detector.startswith("phone:") + + +def test_canonical_noncontact_prose_keeps_exact_inline_assignment(): + value = "Size: `x = 1024 * 1024`" + result = check_text(value, budgets=BUDGETS, publication=True) + assert result.admitted + assert result.text == value + + +def test_finding_preserves_prose_and_separate_proven_multiline_code(): + excerpt = " size = 16 * 1024 * 1024\n return size + 8" + source = f"def scan():\n{excerpt}\n" + finding = { + "path": "example.py", + "start_line": 2, + "end_line": 3, + "content": "Preserve the limit when changing `size = 16 * 1024 * 1024`.", + "existing_code": excerpt, + } + proof = prove_opaque_code(finding, "example.py", lambda _path: source) + assert proof.existing_context is not None and proof.existing_context.operator_spans + result, publication, filtered = review_runner._publication_projection( + {"status": "success", "warnings": [], "comments": [finding]}, + forbidden=(), + allowed_tools=frozenset(), + code_proof=lambda _finding: proof, + ) + assert not filtered and publication["state"] == "passed" + assert result["comments"] == [finding] + + +def test_diagram_label_has_no_literal_assignment_role(): + result = check_text( + "value = 1024 * 1024", + budgets=BUDGETS, + publication=True, + sink=TextSink.DIAGRAM_LABEL, + ) + assert (result.admitted, result.reason) == (False, "pii") diff --git a/tests/test_dlp_attribution.py b/tests/test_dlp_attribution.py index 35d17393..679882b2 100644 --- a/tests/test_dlp_attribution.py +++ b/tests/test_dlp_attribution.py @@ -3,6 +3,7 @@ import json from collections import Counter +import mcp_types import pytest from ocr_toolkit import review_runner @@ -15,6 +16,7 @@ dlp_mode, resolve_dlp_enabled, ) +from ocr_toolkit.federation.admission import index_result, result from ocr_toolkit.posting.formatting import format_publication_dlp_details, publication_dlp_signal from ocr_toolkit.reporting.dlp import admission_dlp_state, admitted_outcome_for_summary from ocr_toolkit.result_contract import parse_result_outcome @@ -37,9 +39,15 @@ def test_dlp_switch_is_default_on_strict_and_content_only() -> None: def test_disabled_publication_dlp_preserves_result_and_emits_closed_state() -> None: + content = ( + "synthetic@example.invalid\n\n" + '\n\n' + "![plot](https://example.invalid/markdown-pixel)\n\n" + "```mermaid\ngraph TD\n```" + ) payload = { "status": "success", - "comments": [{"content": "synthetic@example.invalid"}], + "comments": [{"content": content}], "warnings": [], "tool_calls": {"total": 0, "by_tool": {}}, } @@ -49,7 +57,14 @@ def test_disabled_publication_dlp_preserves_result_and_emits_closed_state() -> N allowed_tools=frozenset(), dlp_enabled=False, ) - assert projected is payload + prepared = projected["comments"][0]["content"] + assert isinstance(prepared, str) + assert projected is not payload + assert payload["comments"][0]["content"] == content + assert "synthetic@example.invalid" in prepared + assert " N assert "Automatic approval is blocked" in details +def test_disabled_publication_rejects_an_unsafe_destination() -> None: + with pytest.raises(review_runner.ReviewRunnerError, match="mandatory safe presentation"): + review_runner._publication_projection( + { + "status": "success", + "comments": [{"content": "[guide](javascript:alert%281%29)"}], + "warnings": [], + }, + forbidden=(), + allowed_tools=frozenset(), + dlp_enabled=False, + ) + + def test_registration_merges_normalized_source_classes_without_rejected_content() -> None: matcher = ForbiddenMatcher.compile( ( @@ -82,6 +111,50 @@ def test_registration_merges_normalized_source_classes_without_rejected_content( ForbiddenValue("data", "operator-chosen-label") +def test_short_structural_keys_preserve_independent_secret_attribution() -> None: + matcher = ForbiddenMatcher.compile( + ( + ForbiddenValue("id", "external_context", structural_key=True), + ForbiddenValue("id", "operator_secret"), + ) + ) + + assert matcher.match_details("Valid record.") == ("forbidden", ("operator_secret",)) + assert matcher.match_details("Record `id`.") == ( + "forbidden", + ("external_context", "operator_secret"), + ) + + +def test_large_admitted_federation_keyset_preserves_unrelated_findings() -> None: + shared_excerpt = "Sample upstream key text" + external_result = mcp_types.CallToolResult( + content=[], + structured_content={ + f"{shared_excerpt} {'k' * 100} record {index}": True for index in range(800) + }, + ) + admitted = result(external_result, None, ForbiddenMatcher.compile(())) + forbidden = tuple(index_result(admitted).publication) + safe = { + "path": "src/sample.py", + "line": 1, + "content": "Explain why the selected options can differ. " * 14 + "Include examples.", + } + copied = {"path": "src/sample.py", "line": 2, "content": f"Keep: {shared_excerpt}."} + + projected, publication, filtered = review_runner._publication_projection( + {"status": "success", "comments": [safe, copied]}, + forbidden=forbidden, + allowed_tools=frozenset(), + ) + + assert filtered and projected["comments"] == [safe] + assert publication["reason_counts"]["forbidden"] == 1 + assert publication["reason_counts"]["limit"] == 0 + assert publication["source_attribution"]["counts"]["external_context"] == 1 + + def test_complete_ocr_is_not_partial_coverage_after_publication_filtering() -> None: text = "Validate the synthetic configuration value before rendering" payload = { diff --git a/tests/test_dlp_audit.py b/tests/test_dlp_audit.py index 33607735..ed6215f5 100644 --- a/tests/test_dlp_audit.py +++ b/tests/test_dlp_audit.py @@ -222,6 +222,46 @@ def test_real_worker_proof_projection_and_no_source_in_report(state) -> None: assert "parts" not in json.dumps(result) +def test_publication_literal_corpus_preserves_independent_protection(state) -> None: + """Track false positives and inverse controls through the offline audit worker.""" + technical = ( + "MAX_SCAN_BYTES = 16 * 1024 * 1024", + "x = 1024 * 1024", + "2026-11-03…2026-11-30", + "2026-11-03..2026-11-30", + "2026-11-03 \u2013 2026-11-30", + "[Budget](../../BUDGET.md#8-замер-2026-11-30)", + "[Budget](../../BUDGET.md#8-measured-2026-11-30)", + ) + phone = "+1 202 555 0114" + secret = "synthetic-private-value" + cases = ( + *((item, None) for item in technical), + *((f"{item}; contact {phone}", "pii") for item in technical), + *((f'password="{secret}"; {item}', "secret") for item in technical), + ("8-2026-11-30", "pii"), + ("[Budget](../../BUDGET.md#8-2026-11-30)", "pii"), + ("Contact 202 **555** 0114", "pii"), + ) + identity = captured(state, "\n".join(text for text, _reason in cases)) + result = scanner.supervised(request(state, identity), 30) + + assert result["units"] == len(cases) + 1 + text_rejections = { + hit["unit"]: hit["reason"] + for hit in result["hits"] + if hit["role"] == "text" and hit["unit"] > 0 + } + expected_rejections = { + number: reason for number, (_text, reason) in enumerate(cases, 1) if reason is not None + } + assert text_rejections == expected_rejections + assert not any( + hit["unit"] in (1, 2) and hit["role"] == "existing_code" for hit in result["hits"] + ) + assert all(value not in json.dumps(result) for value in (technical[0], phone, secret)) + + @pytest.mark.parametrize("secret", ["source", "Inspect", "excerpt"]) def test_real_worker_wrapper_text_cannot_turn_benign_input_into_failure(state, monkeypatch, secret): monkeypatch.setenv("OCR_LLM_TOKEN", secret) diff --git a/tests/test_dlp_composition.py b/tests/test_dlp_composition.py index 1e619785..0a0559eb 100644 --- a/tests/test_dlp_composition.py +++ b/tests/test_dlp_composition.py @@ -69,15 +69,18 @@ def rendered_bodies(comments, warnings=()): ["`", "`![plot](https://example.invalid/pixel)`"], ), ) -def test_prepared_prose_stays_image_free_after_real_consumer_composition(contents, tmp_path): +@pytest.mark.parametrize("dlp_enabled", (True, False)) +def test_prepared_prose_stays_image_free_after_real_consumer_composition( + contents, tmp_path, dlp_enabled +): payload = { "status": "success", "comments": [{"path": "sample", "line": 1, "content": text} for text in contents], } projected, state, filtered = review_runner._publication_projection( - payload, forbidden=(), allowed_tools=frozenset() + payload, forbidden=(), allowed_tools=frozenset(), dlp_enabled=dlp_enabled ) - assert state["state"] == "passed" and not filtered + assert state["state"] == ("passed" if dlp_enabled else "disabled") and not filtered result = tmp_path / "result.json" result.write_text(json.dumps({**projected, TOOLKIT_RESULT_KEY: _receipt_v13()})) reloaded = load_ocr_result(result) @@ -311,6 +314,52 @@ def test_decoding_and_compatibility_normalization_compose_without_delimiter_auth assert filtered and not projected["comments"] +@pytest.mark.parametrize( + "value", + ( + "reviewer@example.invalid", + "reviewer@example.invalid", + "reviewer&#64;example.invalid", + "reviewer@example.invalid", + "[review](mailto:reviewer%40example.invalid)", + "[review](mailto:reviewer%40example.invalid)", + "<!-- reviewer%40example.invalid -->", + "\uff3breview\uff3d\uff08/reviewer%40example.invalid\uff09", + "\uff1c\uff01\uff0d\uff0d reviewer%40example.invalid \uff0d\uff0d\uff1e", + "Open https://guide.example.invalid/reviewer%40example.invalid for details.", + "Open https://guide.example.invalid/editor's/reviewer%40example.invalid for details.", + "Open 'https://guide.example.invalid/editor's/reviewer%40example.invalid', please.", + "Open https://guide.example.invalid/?owner=editor's&to=reviewer%40example.invalid.", + "Contact mailto:reviewer%40example.invalid for details.", + ), +) +def test_model_egress_checks_decoded_views_without_rewriting(value): + checked = check_text(value, budgets=BUDGETS, model_egress=True) + + assert not checked.admitted + assert checked.reason == "pii" + + harmless = "Use A & B at https://guide.example.invalid/path%20name." + admitted = check_text(harmless, budgets=BUDGETS, model_egress=True) + assert admitted.admitted + assert admitted.text == harmless + + +def test_model_egress_accepts_stable_quoted_uri_at_decoding_limit(): + value = "Open 'https://guide.example.invalid/editor's/path%252520name', please." + admitted = check_text(value, budgets=BUDGETS, model_egress=True) + assert admitted.admitted and admitted.text == value + + deeper = value.replace("%252520", "%25252520") + rejected = check_text(deeper, budgets=BUDGETS, model_egress=True) + assert (rejected.admitted, rejected.reason, rejected.detector, rejected.text) == ( + False, + "limit", + "representation", + None, + ) + + def test_removed_publication_ancestor_preserves_prepared_quarantine_content(tmp_path): projected, _, _ = review_runner._publication_projection( { diff --git a/tests/test_dlp_date_ranges.py b/tests/test_dlp_date_ranges.py new file mode 100644 index 00000000..704da4c2 --- /dev/null +++ b/tests/test_dlp_date_ranges.py @@ -0,0 +1,136 @@ +"""Verify date ranges and dated destinations through publication admission.""" + +import pytest + +from ocr_toolkit.context.code_text import TextSink +from ocr_toolkit.context.contracts import TextBudgets +from ocr_toolkit.context.dlp import check_text +from ocr_toolkit.context.dlp.datetimes import dated_anchor_phone_view + +_BUDGETS = TextBudgets(20_000, 80_000, 300) +_SINKS = (TextSink.PROSE, TextSink.LITERAL_CODE) + + +@pytest.mark.parametrize("sink", _SINKS) +@pytest.mark.parametrize( + "value", + ( + "| Period | 2026-11-03…2026-11-30 |", + "2026-11-03..2026-11-30", + "(2026-11-03 ... 2026-11-30).", + "2026-11-03 \u2013 2026-11-30", + "2024-02-29 … 2024-03-01", + "\uff12\uff10\uff12\uff16-\uff11\uff11-\uff10\uff13.." + "\uff12\uff10\uff12\uff16-\uff11\uff11-\uff13\uff10", + "\u0662\u0660\u0662\u0666-\u0661\u0661-\u0660\u0663.." + "\u0662\u0660\u0662\u0666-\u0661\u0661-\u0663\u0660", + ), +) +def test_complete_iso_date_ranges_survive_publication(value, sink): + assert check_text(value, budgets=_BUDGETS, publication=True, sink=sink).admitted + + +@pytest.mark.parametrize("sink", _SINKS) +@pytest.mark.parametrize( + "value", + ( + "2026-02-29..2026-11-30", + "2026-11-03…2026-13-30", + "2026-11-03....2026-11-30", + "2026-11-03..2026-11-30-555", + "2026-11-03..2026-11-30.555", + "12026-11-03..2026-11-30", + "phone: 2026-11-03..2026-11-30", + "telephone number 2026-11-03…2026-11-30", + "contact = '2026-11-03 ... 2026-11-30'", + "2026-11-03..2026-11-30, +7 912 345-67-89", + "2026-11-03..2026-11-30 912-345-6789", + "8-2026-11-30", + ), +) +def test_date_range_proof_preserves_ambiguous_values_and_contact_intent(value, sink): + result = check_text(value, budgets=_BUDGETS, publication=True, sink=sink) + assert (result.admitted, result.reason) == (False, "pii") + + +@pytest.mark.parametrize( + "value", + ( + "[§8](../../BUDGET.md#8-замер-2026-11-30)", + "[§8](../../BUDGET.md#8-measured-2026-11-30)", + "[Section](#замер-2024-02-29)", + "[Section][measurement]\n\n[measurement]: ./guide.markdown#8-замер-2026-11-30", + ), +) +def test_local_markdown_dates_survive_phone_views(value): + assert check_text(value, budgets=_BUDGETS, publication=True).admitted + + +@pytest.mark.parametrize( + ("value", "sink"), + ( + ("2026-11-03…2026-11-30", TextSink.PROSE), + ("2026-11-03..2026-11-30", TextSink.LITERAL_CODE), + ("[§8](../../BUDGET.md#8-замер-2026-11-30)", TextSink.PROSE), + ( + "[Section][measurement]\n\n[measurement]: ./guide.markdown#8-замер-2026-11-30", + TextSink.PROSE, + ), + ("[measurement]: ./guide.markdown#8-замер-2026-11-30", TextSink.PROSE), + ), +) +def test_new_date_interpretation_applies_only_to_publication(value, sink): + context = check_text(value, budgets=_BUDGETS, publication=False, sink=sink) + assert (context.admitted, context.reason) == (False, "pii") + assert check_text(value, budgets=_BUDGETS, publication=True, sink=sink).admitted + + +@pytest.mark.parametrize( + "value", + ( + "[§8](../../BUDGET.md#8-замер-2026-11-30) Details", + "[Section][measurement] Details\n\n" + "[measurement]: ./guide.markdown#8-замер-2026-11-30", + ), +) +def test_dated_destinations_survive_rewritten_prose_and_its_material_recheck(value): + result = check_text(value, budgets=_BUDGETS, publication=True) + assert result.admitted and result.text is not None + assert "" not in result.text + assert "#8-замер-2026-11-30" in result.text + + +@pytest.mark.parametrize( + "value", + ( + "[§8](#8-2026-11-30)", + "[§8](#8-замер-2026-13-30)", + "[Section](https://example.invalid/guide.md#8-замер-2026-11-30)", + '[Section](#8-замер-2026-11-30 "+7 912 345-67-89")', + "[Section](#8-замер-2026-11-30); phone: 8-2026-11-30", + "[Section](#8-%D0%B7%D0%B0%D0%BC%D0%B5%D1%80-2026-11-30)", + "[Section](#8-%D0%B7%D0%B0%D0%BC%D0%B5%D1%80-%31-812-555-0114)", + ), +) +def test_markdown_dates_do_not_admit_other_contact_material(value): + result = check_text(value, budgets=_BUDGETS, publication=True) + assert (result.admitted, result.reason) == (False, "pii") + + +@pytest.mark.parametrize( + "value", + ( + "//example.invalid/guide.md#%D1%80-2026-11-30", + "guide.txt#%D1%80-2026-11-30", + "guide.md?q=lookup#%D1%80-2026-11-30", + "guide.md#%D1%80-%32%30%32%36-11-30", + "guide.md#%D1%80-2026-02-29", + "guide.md#%D1%80-2026-11-30-1", + "guide.md#%D1%80-phone-2026-11-30", + "guide.md#%FF-2026-11-30", + "guide.md#%E2%80%8B-2026-11-30", + "guide.md#%D1%80-555-2026-11-30", + ), +) +def test_date_anchor_phone_view_requires_a_closed_local_destination(value): + assert dated_anchor_phone_view(value) == value diff --git a/tests/test_dlp_publication_edges.py b/tests/test_dlp_publication_edges.py new file mode 100644 index 00000000..3e1f78e1 --- /dev/null +++ b/tests/test_dlp_publication_edges.py @@ -0,0 +1,226 @@ +"""Protect publication boundaries when input changes after decoding.""" + +from urllib.parse import quote + +import pytest + +from ocr_toolkit.context.contracts import TextBudgets +from ocr_toolkit.context.dlp import ForbiddenValue, admission, check_text +from ocr_toolkit.context.dlp.projection import decoded_markup_material + +_BUDGETS = TextBudgets(10_000, 40_000, 100) + + +@pytest.mark.parametrize( + ("value", "max_lines", "context", "publication"), + ( + ("first second", 1, ("admitted", None), ("limit", "lines")), + ("first#10;second", 1, ("limit", "lines"), ("limit", "lines")), + ("first#0;second", 2, ("invalid_text", "mermaid"), ("invalid_text", "mermaid")), + ("phase#65039;", 2, ("admitted", None), ("laundering", "display_control")), + ("flight \u2708#65039; ready", 2, ("admitted", None), ("admitted", None)), + ), +) +def test_decoded_controls_and_line_budgets_are_checked_at_their_sink( + value, max_lines, context, publication +): + budgets = TextBudgets(100, 400, max_lines) + for publishing, expected in ((False, context), (True, publication)): + result = check_text(value, budgets=budgets, publication=publishing, enabled=True) + assert (result.reason, result.detector) == expected + assert result.text == (value if result.admitted else None) + + +def test_forbidden_attribution_includes_independently_decoded_destinations(): + value = "[Guide](./covered%20private%20details) and #79;perator blind reference" + forbidden = ( + ForbiddenValue("covered private details", "forge_discussions"), + ForbiddenValue("Operator blind reference", "external_context"), + ) + for publication, sources in ( + (False, ("external_context",)), + (True, ("external_context", "forge_discussions")), + ): + result = check_text( + value, budgets=_BUDGETS, publication=publication, forbidden=forbidden, enabled=True + ) + assert (result.admitted, result.reason, result.detector, result.text) == ( + False, + "forbidden", + "forbidden_matcher", + None, + ) + assert result.source_classes == sources + + +def test_percent_decoding_and_unicode_compatibility_cannot_hide_a_credential(): + encoded = quote( + "\uff50\uff41\uff53\uff53\uff57\uff4f\uff52\uff44\uff1dmeridian-synthetic-value" + ) + value = f"[Guide](./{encoded})" + result = check_text(value, budgets=_BUDGETS, publication=True, enabled=True) + assert (result.admitted, result.reason, result.detector, result.text) == ( + False, + "secret", + "compatible_markup", + None, + ) + + +@pytest.mark.parametrize("sink", ("publication", "model_egress")) +@pytest.mark.parametrize( + "value", + ( + "('https://one.invalid/?%70assword=','https://two.invalid/?%74oken=')", + "['https://one.invalid/?%70assword=','https://two.invalid/?%74oken=']", + "'https://one.invalid/?%70assword=';'mailto:guide%252520name'", + ), +) +def test_adjacent_quoted_urls_are_decoded_independently(value, sink): + checked = check_text(value, budgets=_BUDGETS, enabled=True, **{sink: True}) + assert checked.admitted and checked.text == value + + +def test_adjacent_quoted_url_material_retains_apostrophes_inside_each_destination(): + value = "('https://one.invalid/reader's%20guide','https://two.invalid/editor's%20guide')" + individual, joined = decoded_markup_material(value, value) + assert individual == ( + "https://one.invalid/reader's guide", + "https://two.invalid/editor's guide", + ) + assert joined == ("https://one.invalid/reader's guide','https://two.invalid/editor's guide",) + + +def test_adjacent_quoted_urls_keep_whole_view_for_forbidden_attribution(): + value = "('https://one.invalid/sample-%65nd','https://two.invalid/guide%20name')" + checked = check_text( + value, + budgets=_BUDGETS, + publication=True, + forbidden=( + ForbiddenValue("end','https://two", "external_context"), + ForbiddenValue("guide name", "forge_discussions"), + ), + enabled=True, + ) + assert (checked.admitted, checked.reason, checked.detector, checked.source_classes) == ( + False, + "forbidden", + "forbidden_matcher", + ("external_context", "forge_discussions"), + ) + + +@pytest.mark.parametrize( + ("encoded", "detector"), (("%65nd", "decoded_markup"), ("%EF%BD%85nd", "compatible_markup")) +) +def test_adjacent_quoted_urls_keep_whole_view_for_known_secrets(monkeypatch, encoded, detector): + monkeypatch.setenv("OCR_LLM_TOKEN", "end','https://two") + value = f"('https://one.invalid/sample-{encoded}','https://two.invalid/guide%20name')" + checked = check_text(value, budgets=_BUDGETS, model_egress=True, enabled=True) + assert (checked.admitted, checked.reason, checked.detector, checked.text) == ( + False, + "secret", + detector, + None, + ) + harmless = "('https://one.invalid/?%70assword=','https://two.invalid/?%74oken=')" + admitted = check_text(harmless, budgets=_BUDGETS, model_egress=True, enabled=True) + assert admitted.admitted and admitted.text == harmless + + +@pytest.mark.parametrize( + ("first", "second", "reason", "detector"), + ( + ("contact%40example.invalid", "guide%20name", "pii", "email:decoded_markup"), + ("guide%20name", "contact%40example.invalid", "pii", "email:decoded_markup"), + ("guide%20name", "guide%25252520name", "limit", "representation"), + ), +) +def test_adjacent_quoted_urls_keep_each_decoded_material_check(first, second, reason, detector): + value = f"('https://one.invalid/{first}','https://two.invalid/{second}')" + checked = check_text(value, budgets=_BUDGETS, publication=True, enabled=True) + assert (checked.admitted, checked.reason, checked.detector, checked.text) == ( + False, + reason, + detector, + None, + ) + + +@pytest.mark.parametrize( + "value", + ( + "('https://one.invalid/?%70assword=','not-a-url')", + "('https://one.invalid/?%70assword=','https://two.invalid/guide%20name','not-a-url')", + "('https://one.invalid/?%70assword=\\','https://two.invalid/guide%20name')", + "('https://one.invalid/?%70assword=''https://two.invalid/guide%20name')", + "('https://one.invalid/?%70assword=','https://two.invalid/guide%20name)[0]", + "('https://one.invalid/?%70assword=','https://two.invalid/guide%20name' + tail)", + ), +) +def test_ambiguous_adjacent_url_material_remains_conservatively_checked(value): + checked = check_text(value, budgets=_BUDGETS, publication=True, enabled=True) + assert (checked.admitted, checked.reason, checked.text) == (False, "secret", None) + + +def test_forbidden_comparison_budget_fails_closed_before_publication(monkeypatch): + candidate = "a" * 8000 + forbidden = ("b" * 8000,) + admitted = check_text( + candidate, budgets=_BUDGETS, publication=True, forbidden=forbidden, enabled=True + ) + assert admitted.admitted and admitted.text == candidate + + monkeypatch.setattr(admission, "MAX_FORBIDDEN_MATCH_WORK", 100) + result = check_text( + candidate, budgets=_BUDGETS, publication=True, forbidden=forbidden, enabled=True + ) + assert (result.admitted, result.reason, result.detector, result.text) == ( + False, + "limit", + "forbidden_matcher", + None, + ) + + +def test_malformed_url_escape_does_not_inherit_the_literal_percent_exception(): + malformed = "[Guide](reference%ZZ.md)" + literal = "[Guide](reference%25.md)" + result = check_text(malformed, budgets=_BUDGETS, publication=True, enabled=True) + assert (result.admitted, result.reason, result.detector) == ( + False, + "laundering", + "markdown_destination", + ) + assert check_text(literal, budgets=_BUDGETS, publication=True, enabled=True).text == literal + + +def test_dated_link_projection_still_budgets_the_escaped_html_token(): + url = "#8-замер-2026-11-30" + value = f"[Guide]({url}) " + tight = TextBudgets(len(value), _BUDGETS.max_bytes, _BUDGETS.max_lines) + rejected = check_text(value, budgets=tight, publication=True, enabled=True) + assert (rejected.admitted, rejected.reason, rejected.detector, rejected.text) == ( + False, + "limit", + "representation", + None, + ) + admitted = check_text(value, budgets=_BUDGETS, publication=True, enabled=True) + assert admitted.admitted and admitted.text is not None + assert url in admitted.text and "" - prepared = check_text(raw, budgets=BUDGETS, publication=True).text + prepared = check_text(raw, budgets=BUDGETS, publication=True, enabled=enabled).text + receipt = publishable_receipt_current() + if version == 14: + del receipt["review_coverage"] + receipt.update(schema_version=14, repository_coverage=_coverage()) + receipt["dlp"]["enabled"] = enabled + if not enabled: + receipt["publication"]["state"] = "disabled" payload = { "status": "success", "comments": [{"path": "sample", "line": 1, "content": prepared}], - TOOLKIT_RESULT_KEY: _receipt_v13(), + TOOLKIT_RESULT_KEY: receipt, } result = tmp_path / "result.json" result.write_text(json.dumps(payload)) assert load_ocr_result(result)["comments"][0]["content"] == prepared - for hostile in ( - raw, - "[guide](javascript:hello)", - "author@example.invalid", - "password=synthetic-value", - ): + hostile_values = (raw, "[guide](javascript:hello)") + if enabled: + hostile_values += ("author@example.invalid", "password=synthetic-value") + for hostile in hostile_values: payload["comments"][0]["content"] = hostile result.write_text(json.dumps(payload)) with pytest.raises(OcrResultMalformed, match="prose is not prepared"): load_ocr_result(result) + if not enabled: + payload["comments"][0]["content"] = "author@example.invalid" + result.write_text(json.dumps(payload)) + assert load_ocr_result(result)["comments"][0]["content"] == "author@example.invalid" + payload["comments"][0]["content"] = "x\n" * 100_001 + result.write_text(json.dumps(payload)) + with pytest.raises(OcrResultMalformed, match="prose exceeds its bounds"): + load_ocr_result(result) def test_filtered_sibling_does_not_reindex_prepared_content_or_warnings(): @@ -433,14 +461,11 @@ def test_real_finalizer_transfers_prose_authority_to_local_report(tmp_path, enab report_consumer=reports.append, ) report = reports[0] - assert report.prepared_prose is enabled + assert report.prepared_prose body = "".join(local_report_parts(report)) saved = json.loads(result.read_text()) assert saved["comments"][0]["content"] in body - if enabled: - assert "" not in body and "```" not in body - else: - assert "" in body and "```" in body + assert "" not in body and "```" not in body def test_explicit_publication_mode_owns_prepared_prose_authority(): diff --git a/tests/test_docs_only_ci.py b/tests/test_docs_only_ci.py index 224ee626..4ed733c0 100644 --- a/tests/test_docs_only_ci.py +++ b/tests/test_docs_only_ci.py @@ -1,7 +1,11 @@ """The documentation shortcut is narrow and keeps protected check identities.""" +import base64 +import hashlib import importlib.util +import json import os +import shutil import subprocess import sys from pathlib import Path @@ -197,14 +201,21 @@ def test_documentation_rename_is_not_exempt( def test_required_job_names_and_full_fallback() -> None: expected = { - "ci.yml": {"test-ubuntu-latest-py3.12", "quality"}, - "build.yml": {"build-distributions"}, - "security.yml": {"sast-bandit", "dependency-audit", "secrets"}, + "ci.yml": {"test-python312": "test-ubuntu-latest-py3.12", "quality": "quality"}, + "build.yml": {"build": "build-distributions"}, + "security.yml": { + "sast-bandit": "sast-bandit", + "dependency-audit": "dependency-audit", + "secrets": "secrets", + }, } for name, required in expected.items(): source = (ROOT / ".github/workflows" / name).read_text() jobs = yaml.safe_load(source)["jobs"] - assert required <= {job["name"] for job in jobs.values()} + for job, context in required.items(): + assert jobs[job]["name"].endswith("|| '" + context + "' }}") + if jobs[job].get("needs") == "classify": + assert "!cancelled()" in jobs[job]["if"] assert "github.event_name == 'pull_request'" in source assert "needs.classify.outputs.docs_only != 'true'" in source assert jobs["classify"]["timeout-minutes"] == 5 @@ -221,6 +232,340 @@ def test_required_job_names_and_full_fallback() -> None: assert yaml.safe_load(preview)["jobs"]["classify"]["timeout-minutes"] == 5 +@pytest.mark.parametrize( + "filename", ["ci.yml", "build.yml", "security.yml", "codeql.yml", "dependency-review.yml"] +) +def test_required_pull_request_workflows_cover_intake_retargeting(filename: str) -> None: + workflow = yaml.safe_load((ROOT / ".github/workflows" / filename).read_text()) + trigger = workflow[True]["pull_request"] # PyYAML reads YAML 1.1's unquoted "on" as true. + assert set(trigger["branches"]) == {"main", "dev"} + assert set(trigger["types"]) == { + "opened", + "synchronize", + "reopened", + "edited", + "ready_for_review", + "converted_to_draft", + } + trusted_repo = "github.event.pull_request.head.repo.full_name == github.repository" + for job in workflow["jobs"].values(): + for step in job["steps"]: + action = step.get("uses", "") + if action.startswith("astral-sh/setup-uv@"): + assert step["with"]["save-cache"] is False + assert trusted_repo in step["with"]["enable-cache"] + elif action.startswith("actions/upload-artifact@"): + assert trusted_repo in step["if"] + elif action.startswith("github/codeql-action/analyze@"): + assert step["with"]["upload"] == "always" + assert trusted_repo in step["with"]["upload-database"] + + +@pytest.mark.parametrize( + ("filename", "deferred", "quick"), + [ + ("ci.yml", ("test-python312", "test-matrix"), ("quality",)), + ("build.yml", ("build",), ()), + ("security.yml", ("sast-bandit", "dependency-audit"), ("secrets",)), + ("codeql.yml", ("analyze",), ()), + ("dependency-review.yml", (), ("review",)), + ], +) +def test_draft_check_contexts_cannot_supply_ready_check_results( + filename: str, deferred: tuple[str, ...], quick: tuple[str, ...] +) -> None: + jobs = yaml.safe_load((ROOT / ".github/workflows" / filename).read_text())["jobs"] + for name in deferred: + assert "'draft-deferred-" in jobs[name]["name"] + assert "!github.event.pull_request.draft" in jobs[name]["if"] + for name in quick: + assert "'draft-" in jobs[name]["name"] + assert "pull_request.draft" not in jobs[name].get("if", "") + for dependency in jobs[name].get("needs", "").split(): + assert "pull_request.draft" not in jobs[dependency].get("if", "") + + +@pytest.mark.parametrize( + ("event", "pin_change", "valid_download"), + [ + ("pull_request", "version", True), + ("pull_request", "digest", True), + ("workflow_dispatch", "version", True), + ("workflow_dispatch", "version", False), + ], +) +def test_native_coverage_install_checks_the_committed_pin_and_download( + tmp_path: Path, event: str, pin_change: str, valid_download: bool +) -> None: + _git(tmp_path, "init", "-q") + _git(tmp_path, "config", "user.email", "test@example.invalid") + _git(tmp_path, "config", "user.name", "Test") + manifest_path = tmp_path / "compatibility/ocr-support.json" + manifest_path.parent.mkdir() + versions = {"1.14.5": b"old verified asset", "1.14.6": b"new verified asset"} + assets = [ + { + "version": version, + "status": "tested", + "assets": [ + { + "name": "opencodereview-linux-amd64", + "size": len(payload), + "sha256": hashlib.sha256(payload).hexdigest(), + } + ], + } + for version, payload in versions.items() + ] + manifest = {"recommended_version": "1.14.5", "releases": assets} + manifest_path.write_text(json.dumps(manifest)) + _git(tmp_path, "add", "compatibility") + _git(tmp_path, "commit", "-qm", "base pin") + base = _git(tmp_path, "rev-parse", "HEAD") + version = "1.14.6" if pin_change == "version" else "1.14.5" + if pin_change == "digest": + assets[0]["assets"][0]["sha256"] = "0" * 64 + manifest_path.write_text(json.dumps({**manifest, "recommended_version": version})) + _git(tmp_path, "add", "compatibility") + _git(tmp_path, "commit", "--allow-empty", "-qm", "candidate pin") + head = _git(tmp_path, "rev-parse", "HEAD") + manifest_path.write_text("{}") # The mutable worktree does not select the binary. + + runner_temp = tmp_path / "runner" + runner_temp.mkdir() + downloader = runner_temp / "curl" + downloader.write_text( + "#!/bin/sh\n" + "set -eu\n" + 'while [ "$#" -gt 1 ]; do\n' + ' if [ "$1" = --output ]; then out=$2; shift; fi\n' + " shift\n" + "done\n" + 'test "$1" = "$EXPECTED_URL"\n' + 'printf "%s" "$ASSET_BYTES" > "$out"\n' + 'printf "%s" "$1"\n' + ) + downloader.chmod(0o700) + workflow = yaml.safe_load((ROOT / ".github/workflows/ci.yml").read_text()) + steps = workflow["jobs"]["test-matrix"]["steps"] + install = next(step for step in steps if step.get("id") == "native-ocr") + test = next(step for step in steps if step.get("name") == "Test with boundary coverage gates") + assert install["if"] == test["if"] + assert test["env"] == { + "OCR_FEDERATION_QUALIFY_BINARY": "${{ steps.native-ocr.outputs.binary }}", + "OCR_GITLINK_QUALIFY_BINARY": "${{ steps.native-ocr.outputs.binary }}", + } + + output = runner_temp / "output" + selected_version = "1.14.5" if event == "pull_request" else version + payload = versions[selected_version].decode() + result = subprocess.run( + ["bash", "-e", "-o", "pipefail", "-c", install["run"]], + cwd=tmp_path, + env={ + **os.environ, + "PATH": f"{runner_temp}{os.pathsep}{os.environ['PATH']}", + "GITHUB_EVENT_NAME": event, + "PR_BASE": base, + "GITHUB_SHA": head, + "RUNNER_TEMP": str(runner_temp), + "GITHUB_OUTPUT": str(output), + "EXPECTED_URL": ( + "https://github.com/alibaba/open-code-review/releases/download/" + f"v{selected_version}/opencodereview-linux-amd64" + ), + "ASSET_BYTES": payload if valid_download else payload.replace("verified", "modified"), + }, + capture_output=True, + text=True, + timeout=10, + check=False, + ) + assert (result.returncode == 0) is valid_download, result.stderr + assert output.exists() is valid_download + if valid_download: + binary = Path(output.read_text().strip().removeprefix("binary=")) + assert binary.is_relative_to(runner_temp) and binary.read_text() == payload + assert binary.stat().st_mode & 0o777 == 0o500 + else: + assert "digest does not match" in result.stderr + + +@pytest.mark.parametrize("real_scanner", [False, True]) +def test_hosted_secrets_scan_fetches_the_exact_pr_without_checking_it_out( + tmp_path: Path, real_scanner: bool +) -> None: + scanner_binary = None + if real_scanner: + scanner_binary = shutil.which("gitleaks") + version = subprocess.check_output([ROOT / "scripts/gitleaks.sh", "--version"], text=True) + if scanner_binary is None or ( + subprocess.check_output([scanner_binary, "version"], text=True).strip() + != version.strip() + ): + pytest.skip("the pinned Gitleaks CLI is unavailable") + _git(tmp_path, "init", "-q") + _git(tmp_path, "config", "user.email", "test@example.invalid") + _git(tmp_path, "config", "user.name", "Test") + _git(tmp_path, "commit", "--allow-empty", "-qm", "base policy") + base = _git(tmp_path, "rev-parse", "HEAD") + # Keep the synthetic positive control stable across runs of the pinned detector. + synthetic_value = base64.b64encode(hashlib.sha384(b"public PR scan fixture").digest()).decode() + if real_scanner: + (tmp_path / "example.py").write_text(f'api_key = "{synthetic_value}" # gitleaks:allow\n') + _git(tmp_path, "add", "example.py") + _git(tmp_path, "commit", "-qm", "add synthetic finding") + _git(tmp_path, "rm", "example.py") + (tmp_path / ".gitleaksignore").write_text("candidate suppression\n") + _git(tmp_path, "add", ".") + _git(tmp_path, "commit", "-qm", "candidate policy") + head = _git(tmp_path, "rev-parse", "HEAD") + _git(tmp_path, "update-ref", "refs/pull/42/head", head) + _git(tmp_path, "remote", "add", "origin", ".") + _git(tmp_path, "checkout", "--detach", base) + + workflow = yaml.safe_load((ROOT / ".github/workflows/security.yml").read_text()) + steps = workflow["jobs"]["secrets"]["steps"] + assert steps[0]["with"]["ref"] == "${{ github.event.pull_request.base.sha || github.sha }}" + runner_temp = tmp_path / "runner" + runner_temp.mkdir() + scanner = runner_temp / "gitleaks" + if scanner_binary is not None: + shutil.copyfile(scanner_binary, scanner) + else: + scanner.write_text( + "#!/bin/sh\n" + "set -eu\n" + 'test "$(git rev-parse HEAD)" = "$PR_BASE"\n' + 'test "$(git rev-parse FETCH_HEAD)" = "$PR_HEAD"\n' + "test ! -e .gitleaksignore\n" + 'test "$5" = --ignore-gitleaks-allow\n' + 'test "$6" = "--log-opts=--no-ext-diff --no-textconv --diff-merges=first-parent ' + '$PR_BASE..$PR_HEAD"\n' + 'touch "$RUNNER_TEMP/scanned"\n' + ) + scanner.chmod(0o700) + environment = { + **os.environ, + "GITHUB_EVENT_NAME": "pull_request", + "PR_BASE": base, + "PR_HEAD": head, + "PR_NUMBER": "42", + "RUNNER_TEMP": str(runner_temp), + } + command = ["bash", "-e", "-o", "pipefail", "-c", steps[-1]["run"]] + if real_scanner: + environment.pop("GITLEAKS_CONFIG", None) + environment.pop("GITLEAKS_CONFIG_TOML", None) + run = subprocess.run( + command, cwd=tmp_path, env=environment, timeout=30, capture_output=True, text=True + ) + assert run.returncode == 1 + assert "leaks found: 1" in run.stderr + assert synthetic_value not in run.stdout + run.stderr + assert _git(tmp_path, "rev-parse", "HEAD") == base + assert not (tmp_path / ".gitleaksignore").exists() + return + subprocess.run(command, cwd=tmp_path, env=environment, timeout=10, check=True) + scanned = runner_temp / "scanned" + assert scanned.exists() + + scanned.unlink() + environment["PR_HEAD"] = base + rejected = subprocess.run( + command, cwd=tmp_path, env=environment, timeout=10, capture_output=True, text=True + ) + assert rejected.returncode != 0 + assert "PR head moved after this event" in rejected.stderr + assert not scanned.exists() + + +def test_gitleaks_upgrade_retains_the_protected_base_download(tmp_path: Path) -> None: + _git(tmp_path, "init", "-q") + _git(tmp_path, "config", "user.email", "test@example.invalid") + _git(tmp_path, "config", "user.name", "Test") + version = subprocess.check_output( + [ROOT / "scripts/gitleaks.sh", "--version"], text=True + ).strip() + wrapper = tmp_path / "scripts/gitleaks.sh" + wrapper.parent.mkdir() + wrapper.write_text(f"GITLEAKS_VERSION={version}\n") + _git(tmp_path, "add", "scripts") + _git(tmp_path, "commit", "-qm", "protected base") + base = _git(tmp_path, "rev-parse", "HEAD") + next_version = "999.0.0" + wrapper.write_text(f"GITLEAKS_VERSION={next_version}\n") + _git(tmp_path, "commit", "-qam", "upgrade wrapper") + _git(tmp_path, "checkout", "--detach", base) + + workflow = yaml.safe_load((ROOT / ".github/workflows/security.yml").read_text()) + steps = workflow["jobs"]["secrets"]["steps"] + assert steps[0]["with"]["ref"] == "${{ github.event.pull_request.base.sha || github.sha }}" + install = next( + step["run"] + for step in steps + if step.get("name") == "Install checksum-pinned Gitleaks without a cache" + ) + old_entry = next(line for line in install.splitlines() if f"{version}) digest=" in line) + new_entry = old_entry.replace(version, next_version, 1) + + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + curl = bin_dir / "curl" + curl.write_text('#!/bin/sh\nfor url do :; done\nprintf "%s\\n" "$url"\nexit 23\n') + curl.chmod(0o700) + env = { + **os.environ, + "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}", + "RUNNER_TEMP": str(tmp_path), + } + + def run_install(code: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + ["bash", "-e", "-o", "pipefail", "-c", code], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + timeout=10, + ) + + retained = run_install(install.replace(old_entry, f"{old_entry}\n{new_entry}", 1)) + assert retained.returncode == 23 + assert retained.stdout.strip().endswith(f"/v{version}/gitleaks_{version}_linux_x64.tar.gz") + missing = run_install(install.replace(old_entry, new_entry, 1)) + assert missing.returncode == 1 + assert missing.stdout == "" + assert "has no reviewed Linux x64 checksum" in missing.stderr + + +@pytest.mark.parametrize( + ("ref", "allowed"), + [ + ("refs/heads/main", True), + ("refs/heads/Main", False), + ("refs/heads/dev", False), + ("refs/tags/main", False), + ], +) +def test_ocr_compatibility_checks_the_exact_main_ref_before_checkout( + ref: str, allowed: bool +) -> None: + workflow = yaml.safe_load((ROOT / ".github/workflows/ocr-compatibility.yml").read_text()) + guard, checkout = workflow["jobs"]["discover"]["steps"][:2] + assert checkout["uses"].startswith("actions/checkout@") + result = subprocess.run( + ["bash", "-e", "-c", guard["run"]], + env={**os.environ, "GITHUB_REF": ref}, + capture_output=True, + text=True, + timeout=10, + ) + assert (result.returncode == 0) is allowed, result.stderr + if not allowed: + assert "Run OCR compatibility from the main branch." in result.stderr + + def test_pr_cannot_replace_trusted_classifier(tmp_path: Path) -> None: _git(tmp_path, "init", "-q") _git(tmp_path, "config", "user.email", "test@example.invalid") diff --git a/tests/test_environment_contract.py b/tests/test_environment_contract.py index 553a7c0d..33233652 100644 --- a/tests/test_environment_contract.py +++ b/tests/test_environment_contract.py @@ -48,7 +48,7 @@ "OCR_TELEMETRY_OTLP_ENDPOINT": "Unset", "OCR_REVIEW_CONTEXT_MODE": "off", "OCR_REVIEW_CONTEXT_ADAPTERS_JSON": "Removed; setting it is an error", - "OCR_MCP_SERVERS_JSON": "Empty version 2 registry", + "OCR_MCP_SERVERS_JSON": "Unset or blank", "OCR_MCP_REPLACE": "Removed; setting it is an error", "OCR_DLP_ENABLED": "true", "OCR_POST_MODE": "draft", @@ -356,6 +356,8 @@ def test_example_manual_self_test_inherits_install_without_model_call() -> None: encoding="utf-8" ) ) + image = workflow["default"]["image"] + assert re.fullmatch(r"docker\.io/library/python:3\.12-slim@sha256:[0-9a-f]{64}", image) install = workflow[".ocr_install"] assert set(install) == {"before_script"} install_commands = install["before_script"] @@ -371,6 +373,8 @@ def test_example_manual_self_test_inherits_install_without_model_call() -> None: assert job["extends"] == ".ocr_install" assert "before_script" not in job composed = {**install, **job} + assert "image" not in composed + assert job.get("inherit", {}).get("default", True) is True assert composed["before_script"] == install_commands assert composed["script"][:2] == ["ocr-ci preflight", "ocr-ci configure"] diff --git a/tests/test_evidence_repository.py b/tests/test_evidence_repository.py index 4ae084e9..8ac5197f 100644 --- a/tests/test_evidence_repository.py +++ b/tests/test_evidence_repository.py @@ -38,6 +38,7 @@ ) from ocr_toolkit.evidence.repository import ( GitRepositoryReader, + RepositoryEvidenceBudgetError, RepositoryEvidenceError, RepositoryObject, build_file_snapshot, @@ -130,6 +131,33 @@ def test_reader_preserves_utf8_paths_and_rejects_control_paths(tmp_path: Path) - assert reader.read_blob(head, added_path) == b"added\n" +@pytest.mark.parametrize("scope", ["tree", "diff"]) +def test_reader_rejects_bad_path_before_reporting_entry_overflow( + tmp_path: Path, scope: str +) -> None: + git(tmp_path, "init", "-q") + (tmp_path / "first.txt").write_text("First\n", encoding="utf-8") + (tmp_path / "renamed-from.txt").write_text("Rename me\n", encoding="utf-8") + git(tmp_path, "add", ".") + git(tmp_path, "commit", "-qm", "base") + base = git(tmp_path, "rev-parse", "HEAD") + (tmp_path / "first.txt").write_text("Changed\n", encoding="utf-8") + git(tmp_path, "mv", "--", "renamed-from.txt", "renamed\tto.txt") + git(tmp_path, "commit", "-qam", "head") + head = git(tmp_path, "rev-parse", "HEAD") + + if scope == "diff": + status = git(tmp_path, "diff", "--name-status", "--find-renames", base, head) + assert [line.split("\t")[0] for line in status.splitlines()] == ["M", "R100"] + reader = GitRepositoryReader(tmp_path) + with pytest.raises(RepositoryEvidenceError, match="control syntax") as error: + if scope == "tree": + reader.list_objects(head, max_entries=1) + else: + reader.changed_paths(base, head, max_paths=1) + assert type(error.value) is RepositoryEvidenceError + + @pytest.mark.parametrize( "path", [ @@ -197,6 +225,30 @@ def test_reader_refuses_symlink_content_and_reads_old_regular_blob(tmp_path: Pat reader.read_blob(head_sha, "outside-link") +def test_list_objects_pins_one_local_only_resolution(tmp_path: Path, monkeypatch) -> None: + root, base, head = synthetic_repository(tmp_path) + ref = "refs/heads/scope" + git(root, "update-ref", ref, base) + reader = GitRepositoryReader(root) + run = reader._run + calls = [] + + def move_ref_after_resolution(args, **kwargs): + calls.append((args, kwargs["local_only"])) + result = run(args, **kwargs) + if args[0] == "rev-parse": + git(root, "update-ref", ref, head) + return result + + monkeypatch.setattr(reader, "_run", move_ref_after_resolution) + objects = reader.list_objects(ref, local_only=True) + assert calls == [ + (["rev-parse", "--verify", f"{ref}^{{commit}}"], True), + (["ls-tree", "-z", "-r", "--full-tree", base], True), + ] + assert {entry.path for entry in objects} == {"changed.txt", "removed.txt", "renamed.txt"} + + def test_reader_reports_missing_objects_without_fetching(tmp_path: Path) -> None: """Treat unavailable shallow-clone objects as explicit local errors.""" @@ -716,9 +768,7 @@ def counting_run(*args: object, **kwargs: object) -> object: assert blobs == {"changed.txt": b"after\n", "moved.txt": b"renamed\n"} -@pytest.mark.parametrize( - "stage,limit", [("text", 15), ("sizes", 30), ("contents", 30), ("fetch", 60)] -) +@pytest.mark.parametrize("stage,limit", [("sizes", 30), ("contents", 30), ("fetch", 60)]) @pytest.mark.parametrize("bounded", [False, True]) def test_reader_deadline_covers_all_process_paths( tmp_path, monkeypatch, stage, limit, bounded @@ -737,9 +787,7 @@ def timeout(command, **kwargs): with monkeypatch.context() as patch: patch.setattr(evidence_repository.subprocess, "run", timeout) with pytest.raises((RepositoryEvidenceError, subprocess.TimeoutExpired)): - if stage == "text": - reader._run(["cat-file", "-t", head]) - elif stage == "sizes": + if stage == "sizes": reader._batch_sizes(entries) elif stage == "contents": reader._batch_contents(entries, (6,)) @@ -1128,22 +1176,103 @@ def recording(*args, **kwargs): reader.read_candidate_blobs(regular, max_total_bytes=value) -def test_audit_metadata_is_capped_during_real_git_acquisition(tmp_path, monkeypatch) -> None: +def test_default_reader_reaps_git_on_metadata_byte_overflow(tmp_path, monkeypatch) -> None: + """Stop and reap default-reader metadata processes at the stdout byte ceiling.""" + root, _base, head = synthetic_repository(tmp_path) - reader = GitRepositoryReader(root, command_timeout=10) + reader = GitRepositoryReader(root) + native_popen = evidence_repository.subprocess.Popen + processes = [] + + def peer(command, **kwargs): + """Keep producing after the byte ceiling unless the default reader stops the peer.""" + + if "ls-tree" not in command: + return native_popen(command, **kwargs) + process = native_popen( + [ + sys.executable, + "-c", + "import sys,time; sys.stdout.write('x' * 101); sys.stdout.flush(); time.sleep(60)", + ], + **kwargs, + ) + processes.append(process) + return process + monkeypatch.setattr(evidence_repository, "MAX_GIT_TEXT_BYTES", 100) + monkeypatch.setattr(evidence_repository.subprocess, "Popen", peer) with pytest.raises(RepositoryEvidenceError, match="byte limit"): reader.list_objects(head) + assert len(processes) == 1 and processes[0].poll() is not None assert git(root, "status", "--porcelain") == "" -def test_streamed_git_metadata_timeout_stderr_and_cleanup(tmp_path, monkeypatch) -> None: +@pytest.mark.parametrize( + "scope,payload,message", + [ + ( + "tree", + b"100644 blob " + + b"0" * 40 + + b"\tfirst\0" + + b"100644 blob " + + b"1" * 40 + + b"\tsecond\0", + "entry limit", + ), + ("diff", b"A\0first\0A\0second\0", "changed path count"), + ], +) +def test_default_reader_reaps_git_on_metadata_record_overflow( + tmp_path, monkeypatch, scope, payload, message +) -> None: + """Stop and reap default-reader Git processes at tree-entry or changed-path overflow.""" + + root, base, head = synthetic_repository(tmp_path) + reader = GitRepositoryReader(root) + native_popen = evidence_repository.subprocess.Popen + processes = [] + + def peer(command, **kwargs): + """Replace only the repository-sized command with a slow streaming peer.""" + + target = "ls-tree" if scope == "tree" else "diff" + if target not in command: + return native_popen(command, **kwargs) + process = native_popen( + [ + sys.executable, + "-c", + "import sys,time; " + "sys.stdout.buffer.write(bytes.fromhex(sys.argv[1])); " + "sys.stdout.flush(); time.sleep(60)", + payload.hex(), + ], + **kwargs, + ) + processes.append(process) + return process + + monkeypatch.setattr(evidence_repository.subprocess, "Popen", peer) + with pytest.raises(RepositoryEvidenceBudgetError, match=message) as error: + if scope == "tree": + reader.list_objects(head, max_entries=1) + else: + reader.changed_paths(base, head, max_paths=1) + assert (error.value.actual, error.value.limit, error.value.unit) == (2, 1, "entries") + assert len(processes) == 1 and processes[0].poll() is not None + + +def test_default_streamed_git_metadata_timeout_stderr_and_cleanup(tmp_path, monkeypatch) -> None: root, _base, _head = synthetic_repository(tmp_path) - reader = GitRepositoryReader(root, command_timeout=10) + reader = GitRepositoryReader(root) native_popen = evidence_repository.subprocess.Popen processes = [] def peer(_command, **kwargs): + """Emit stderr and remain alive until the default reader enforces its deadline.""" + process = native_popen( [ sys.executable, @@ -1157,5 +1286,5 @@ def peer(_command, **kwargs): monkeypatch.setattr(evidence_repository.subprocess, "Popen", peer) with pytest.raises(RepositoryEvidenceError, match="deadline"): - reader._run_streamed(["ls-tree"], timeout=0.1, text=False) + reader._run(["ls-tree"], timeout=0.1, text=False) assert len(processes) == 1 and processes[0].poll() is not None diff --git a/tests/test_gitlab_discussions.py b/tests/test_gitlab_discussions.py index 7be9e0bd..24da3857 100644 --- a/tests/test_gitlab_discussions.py +++ b/tests/test_gitlab_discussions.py @@ -770,6 +770,39 @@ def test_generic_projection_rejects_hostile_shapes_before_store_admission() -> N assert "blocked-adapter-secret" not in serialized +@pytest.mark.parametrize( + "body", + ( + "Contact reviewer@example.invalid", + "Contact reviewer@example.invalid", + "Contact reviewer&#64;example.invalid", + ), +) +def test_generic_projection_rejects_html_decoded_model_contacts(body: str) -> None: + """Reject reversible contact encodings before discussion model admission.""" + + raw = RawGitLabSnapshot( + identity=GitLabUserIdentity(user_id=99, username="OCR_Bot"), + threads=({"notes": [note(1, body)]},), + pagination_omitted=0, + digest="d" * 64, + ) + + snapshot = _project_discussions( + raw, + source_sha=SOURCE_SHA, + run_id="bounded_run_0001", + policy=discussion_policy(), + now=1_787_209_200, + forbidden=(), + ) + + assert snapshot.records == () + assert snapshot.state == "partial" + assert snapshot.omitted == 1 + assert snapshot.dlp_rejected == 1 + + def test_remediation_projection_keeps_only_valid_noncommand_replies() -> None: """Admit safe remediation replies while excluding lifecycle commands.""" @@ -794,7 +827,7 @@ def test_remediation_projection_keeps_only_valid_noncommand_replies() -> None: "author": {"id": 41, "state": "unknown"}, }, note(4, "@OCR_Bot resolve"), - note(5, "Contact reviewer@example.invalid"), + note(5, "Contact reviewer@example.invalid"), invalid_timestamp, note(8, "The current code still needs verification."), ], @@ -845,7 +878,7 @@ def test_remediation_projection_keeps_only_valid_noncommand_replies() -> None: serialized = repr((snapshot, verified)) for rejected in ( "raw-thread-private", - "reviewer@example.invalid", + "reviewer@example.invalid", "@OCR_Bot resolve", "@OCR_Bot suppress", "Forged human root", diff --git a/tests/test_gitlab_provider.py b/tests/test_gitlab_provider.py index 677034cd..c682f4a8 100644 --- a/tests/test_gitlab_provider.py +++ b/tests/test_gitlab_provider.py @@ -20,9 +20,11 @@ from ocr_toolkit.evidence.artifacts import prepare_artifact_directory, repository_artifacts from ocr_toolkit.evidence.repository import GitRepositoryReader, RepositoryEvidenceError from ocr_toolkit.evidence.review_context import normalize_merge_request_context +from ocr_toolkit.posting.workflow import verified_review_coverage from ocr_toolkit.pre_execution import read_pre_execution_status from ocr_toolkit.preflight import RECOMMENDED_OCR_VERSION from ocr_toolkit.providers import gitlab +from ocr_toolkit.review_receipt import validated_review_identity from ocr_toolkit.review_runner import ( ReviewIdentity, ReviewRefs, @@ -1425,6 +1427,51 @@ def test_evidence_review_crosses_provider_git_store_mcp_and_subprocess_boundarie != 0 ) refs_before = _git(checkout, "for-each-ref", "--format=%(refname) %(objectname)") + from ocr_toolkit.evidence.gitlink_projection import ( + gitlink_selection_proof, + make_gitlink_projection, + ) + from ocr_toolkit.evidence.gitlinks import plan_review_input + from ocr_toolkit.evidence.repository import GitRepositoryReader + + projection = make_gitlink_projection( + GitRepositoryReader(checkout), + plan_review_input(GitRepositoryReader(checkout), base, head), + ) + line_counts = { + path: (insertions, deletions) for path, insertions, deletions in projection.line_counts + } + preview_payload = { + "files": [ + { + "path": entry.path, + "status": entry.preview_status, + "insertions": line_counts[entry.path][0], + "deletions": line_counts[entry.path][1], + "will_review": True, + } + for entry in projection.ordinary_diff + ], + "total_insertions": sum(counts[0] for counts in line_counts.values()), + "total_deletions": sum(counts[1] for counts in line_counts.values()), + "total_files": len(projection.ordinary_diff), + "reviewable_count": len(projection.ordinary_diff), + "excluded_count": 0, + } + fingerprints = dict(projection.fingerprints) + selected_records = [ + { + "item_id": item_id, + "path": entry.path, + "fingerprint": fingerprints[item_id], + } + for entry, (item_id, _fingerprint) in zip( + projection.ordinary_diff, projection.fingerprints, strict=True + ) + ] + source_artifact_sha256 = gitlink_selection_proof(projection, projection.ordinary_diff)[ + "source_artifact_sha256" + ] binary_directory = tmp_path / "bin" binary_directory.mkdir() @@ -1451,7 +1498,7 @@ def test_evidence_review_crosses_provider_git_store_mcp_and_subprocess_boundarie "assert config['llm']['model'] == 'synthetic-model'\n" "assert config['llm']['auth_token'] == 'synthetic-runtime-token'\n" "if '--preview' in args:\n" - " print(json.dumps({'files': []}, sort_keys=True))\n" + f" print(json.dumps({preview_payload!r}, sort_keys=True))\n" " raise SystemExit(0)\n" "server = config['mcp_servers']['ocr_toolkit_evidence']\n" "requests = [\n" @@ -1485,12 +1532,14 @@ def test_evidence_review_crosses_provider_git_store_mcp_and_subprocess_boundarie "assert context[0]['value']['fields']['description']['value'] == " "'The broad rollout is intentional.'\n" "native_input = {'mode':'range','requested_from':base,'requested_head':head," - "'resolved_base':base,'resolved_head':head,'exact_range':base+'..'+head}\n" - "coverage = {'selected':[{'item_id':'app.py'}], 'completed':[{'item_id':'app.py'}]," - "'reused':[], 'failed':[], 'waived':[]}\n" + "'resolved_base':base,'resolved_head':head,'exact_range':base+'..'+head," + f"'source_artifact_sha256':{source_artifact_sha256!r}}}\n" + f"coverage = {{'selected':{selected_records!r}, 'excluded':[], " + f"'completed':{selected_records!r}, 'reused':[], 'failed':[], 'waived':[]}}\n" "print(json.dumps({'status':'complete','comments':[]," "'manifest':{'schema_version':'ocr.run-manifest/v1','operation':'review'," - "'terminal_state':'complete','input':native_input,'coverage':coverage}," + "'terminal_state':'complete','input':native_input,'coverage':coverage," + f"'execution':{{'ocr_version':'v{RECOMMENDED_OCR_VERSION}'}}}}," "'tool_calls':{'total':3,'by_tool':{'ocr_toolkit_evidence':3}}}, " "sort_keys=True))\n", encoding="utf-8", @@ -1556,8 +1605,35 @@ def test_evidence_review_crosses_provider_git_store_mcp_and_subprocess_boundarie assert _git(checkout, "cat-file", "-t", policy) == "commit" assert _git(checkout, "status", "--short") == "" payload = json.loads(result.read_text(encoding="utf-8")) - assert payload["_ocr_toolkit"] == { - "schema_version": 13, + metadata = payload["_ocr_toolkit"] + receipt_identity = validated_review_identity(metadata) + assert receipt_identity is not None + coverage = verified_review_coverage(payload, receipt_identity) + assert coverage.state == "complete" and coverage.selected == 2 + review_coverage = metadata.pop("review_coverage") + assert coverage.payload() == review_coverage + assert review_coverage == { + "schema_version": "ocr.review-coverage/v1", + "state": "complete", + "changed": 2, + "selected": 2, + "excluded": 0, + "exclusion_reasons": { + "binary": 0, + "default_path": 0, + "deleted": 0, + "gitignore": 0, + "provider_directory": 0, + "secret_exclude": 0, + "too_large": 0, + "unsupported_ext": 0, + "user_exclude": 0, + }, + "selection_sha256": review_coverage["selection_sha256"], + } + assert len(review_coverage["selection_sha256"]) == 64 + assert metadata == { + "schema_version": 15, "range": { "schema": "ocr.review-range/v1", "state": "verified", diff --git a/tests/test_gitlinks.py b/tests/test_gitlinks.py index 345730a8..ceb8c1ef 100644 --- a/tests/test_gitlinks.py +++ b/tests/test_gitlinks.py @@ -16,13 +16,21 @@ from ocr_toolkit.evidence import gitlink_projection from ocr_toolkit.evidence.artifacts import prepare_artifact_directory, repository_artifacts from ocr_toolkit.evidence.gitlink_projection import ( + PreviewExclusion, + ReviewSelection, + gitlink_selection_proof, make_gitlink_projection, qualify_gitlink_manifest, qualify_gitlink_preview, + qualify_review_manifest, + qualify_review_preview, + review_selection_proof, + selection_from_review_proof, verify_gitlink_projection, ) -from ocr_toolkit.evidence.gitlinks import changed_gitlinks, plan_gitlink_input +from ocr_toolkit.evidence.gitlinks import changed_gitlinks, plan_gitlink_input, plan_review_input from ocr_toolkit.evidence.repository import GitRepositoryReader, RepositoryEvidenceError +from ocr_toolkit.ocr_result import TOOLKIT_RESULT_KEY, TOOLKIT_REVIEW_SELECTION_KEY from ocr_toolkit.pre_execution import ( GITLINK_PROJECTION_UNQUALIFIED, GITLINK_STATUS_SCHEMA, @@ -65,6 +73,21 @@ def _fixture(root: Path, kind: str) -> tuple[str, str]: return base, _git(root, "rev-parse", "HEAD") +def _gitignore_fixture(root: Path) -> tuple[str, str]: + base, _ = _fixture(root, "updated") + (root / ".gitignore").write_text( + "nested/\n!nested/\nnested/ignored.php\nlocked/\n!locked/ignored.php\n", encoding="utf-8" + ) + for folder in ("nested", "locked"): + (root / folder).mkdir() + paths = ("nested/kept.php", "nested/ignored.php", "locked/ignored.php") + for path in paths: + (root / path).write_text(" tuple[str, str]: _git(root, "init", "-q") _git(root, "config", "user.name", "Synthetic Reviewer") @@ -98,6 +121,26 @@ def _gitlink_only_fixture(root: Path) -> tuple[str, str]: return base, _git(root, "rev-parse", "HEAD") +def _ordinary_exclusion_fixture(root: Path) -> tuple[str, str]: + """Create an immutable range where a tracked ignored file changes.""" + + _git(root, "init", "-q") + _git(root, "config", "user.name", "Synthetic Reviewer") + _git(root, "config", "user.email", "reviewer@example.invalid") + (root / ".gitignore").write_text("hidden.py\n", encoding="utf-8") + (root / "selected.py").write_text("value = 1\n", encoding="utf-8") + (root / "hidden.py").write_text("hidden = 1\n", encoding="utf-8") + _git(root, "add", ".gitignore", "selected.py") + _git(root, "add", "-f", "hidden.py") + _git(root, "commit", "-qm", "base") + base = _git(root, "rev-parse", "HEAD") + (root / "selected.py").write_text("value = 2\n", encoding="utf-8") + (root / "hidden.py").write_text("hidden = 2\n", encoding="utf-8") + _git(root, "add", "selected.py", "hidden.py") + _git(root, "commit", "-qm", "head") + return base, _git(root, "rev-parse", "HEAD") + + @pytest.mark.parametrize("kind", ["added", "updated", "deleted"]) def test_changed_gitlinks_use_immutable_tree_modes_with_ordinary_file( tmp_path: Path, kind: str @@ -158,7 +201,122 @@ def test_projection_preserves_original_ordinary_diff(tmp_path: Path, kind: str) verify_gitlink_projection(reader, projection) -def _preview(path: str = "main.php", *, selected: bool = True) -> bytes: +def _ordinary_nested_base(root: Path) -> tuple[Path, str]: + _ordinary_exclusion_fixture(root) + directory = root / "source" / "nested" + directory.mkdir(parents=True) + (directory / "old.py").write_text("value = 1\n", encoding="utf-8") + _git(root, "add", "source") + _git(root, "commit", "--amend", "--no-edit", "-q") + return directory, _git(root, "rev-parse", "HEAD") + + +def test_ordinary_projection_accepts_directory_replaced_by_file(tmp_path: Path) -> None: + directory, base = _ordinary_nested_base(tmp_path) + _git(tmp_path, "rm", "source/nested/old.py") + directory.parent.mkdir(exist_ok=True) + directory.write_text("replacement\n", encoding="utf-8") + _git(tmp_path, "add", "source") + _git(tmp_path, "commit", "-qm", "Replace directory with file") + head = _git(tmp_path, "rev-parse", "HEAD") + + reader = GitRepositoryReader(tmp_path) + projection = make_gitlink_projection(reader, plan_review_input(reader, base, head)) + assert not projection.gitlink_diff + assert [(entry.path, entry.status) for entry in projection.ordinary_diff] == [ + ("source/nested", "A"), + ("source/nested/old.py", "D"), + ] + verify_gitlink_projection(reader, projection) + + +def test_ordinary_projection_rejects_symlinked_input_ancestor(tmp_path: Path) -> None: + repo = tmp_path / "repo" + repo.mkdir() + directory, base = _ordinary_nested_base(repo) + (directory / "old.py").write_text("value = 2\n", encoding="utf-8") + _git(repo, "commit", "-qam", "Edit nested file") + head = _git(repo, "rev-parse", "HEAD") + + reader = GitRepositoryReader(repo) + plan = plan_review_input(reader, base, head) + projection = make_gitlink_projection(reader, plan) + directory.rename(tmp_path / "saved-directory") + empty_directory = tmp_path / "empty-directory" + empty_directory.mkdir() + directory.symlink_to(empty_directory, target_is_directory=True) + with pytest.raises(RepositoryEvidenceError, match="Git input is unavailable or unsafe"): + verify_gitlink_projection(reader, projection) + with pytest.raises(RepositoryEvidenceError, match="Git input is unavailable or unsafe"): + make_gitlink_projection(reader, plan) + + +def _ordinary_quoted_fixture(root: Path) -> tuple[str, str]: + _ordinary_exclusion_fixture(root) + quoted_path = 'notes/"draft" café.py' + renamed_from = 'notes/"archive".md' + renamed_to = "notes b/archive.md" + (root / "notes").mkdir() + (root / "notes b").mkdir() + (root / quoted_path).write_text("value = 1\n", encoding="utf-8") + (root / renamed_from).write_text("Archive\n", encoding="utf-8") + _git(root, "add", "notes") + _git(root, "commit", "--amend", "--no-edit", "-q") + base = _git(root, "rev-parse", "HEAD") + + (root / quoted_path).write_text("value = 2\n", encoding="utf-8") + _git(root, "mv", "--", renamed_from, renamed_to) + _git(root, "commit", "-qam", "Update ordinary filenames") + return base, _git(root, "rev-parse", "HEAD") + + +def test_ordinary_projection_preserves_quoted_and_mixed_patch_paths(tmp_path: Path) -> None: + base, head = _ordinary_quoted_fixture(tmp_path) + reader = GitRepositoryReader(tmp_path) + projection = make_gitlink_projection(reader, plan_review_input(reader, base, head)) + assert not projection.gitlink_diff + assert { + (entry.old_path, entry.new_path, entry.status) for entry in projection.ordinary_diff + } == { + ('notes/"archive".md', "notes b/archive.md", "R"), + ('notes/"draft" café.py', 'notes/"draft" café.py', "M"), + } + assert set(projection.line_counts) == { + ('notes/"draft" café.py', 1, 1), + ("notes b/archive.md", 0, 0), + } + assert len(projection.fingerprints) == 2 + verify_gitlink_projection(reader, projection) + + +def _ordinary_non_utf8_fixture(root: Path) -> tuple[str, str]: + _git(root, "init", "-q") + _git(root, "config", "user.name", "Synthetic Reviewer") + _git(root, "config", "user.email", "reviewer@example.invalid") + legacy = root / "legacy.py" + selected = root / "selected.py" + legacy.write_bytes(b"# coding: cp1252\nkind = 'caf\xe9'\n") + selected.write_text("value = 1\n", encoding="utf-8") + _git(root, "add", ".") + _git(root, "commit", "-qm", "base") + base = _git(root, "rev-parse", "HEAD") + legacy.write_bytes(b"# coding: cp1252\nkind = 'cr\xe8me'\n") + selected.write_text("value = 2\n", encoding="utf-8") + _git(root, "commit", "-qam", "head") + return base, _git(root, "rev-parse", "HEAD") + + +def test_ordinary_projection_keeps_non_utf8_hunks_in_the_inventory(tmp_path: Path) -> None: + base, head = _ordinary_non_utf8_fixture(tmp_path) + reader = GitRepositoryReader(tmp_path) + projection = make_gitlink_projection(reader, plan_review_input(reader, base, head)) + assert projection.line_counts == (("legacy.py", 1, 1), ("selected.py", 1, 1)) + assert len(projection.fingerprints) == 2 + verify_gitlink_projection(reader, projection) + + +def _preview(path: str = "main.php", *, reason: str = "") -> bytes: + selected = not reason item: dict[str, object] = { "path": path, "status": "modified", @@ -167,7 +325,7 @@ def _preview(path: str = "main.php", *, selected: bool = True) -> bytes: "will_review": selected, } if not selected: - item["exclude_reason"] = "user_exclude" + item["exclude_reason"] = reason return json.dumps( { "files": [item], @@ -187,7 +345,144 @@ def test_projection_qualifies_exact_preview_and_zero_selection(tmp_path: Path) - assert plan is not None projection = make_gitlink_projection(reader, plan) assert qualify_gitlink_preview(projection, _preview()) == projection.ordinary_diff - assert qualify_gitlink_preview(projection, _preview(selected=False)) == () + assert qualify_gitlink_preview(projection, _preview(reason="user_exclude")) == () + assert qualify_gitlink_preview(projection, _preview(reason="gitignore")) == () + + +def test_ordinary_projection_binds_exclusion_to_manifest(tmp_path: Path) -> None: + """A tracked ignored path remains in the immutable partition and native manifest.""" + + base, head = _ordinary_exclusion_fixture(tmp_path) + reader = GitRepositoryReader(tmp_path) + plan = plan_review_input(reader, base, head) + assert not plan.changes + projection = make_gitlink_projection(reader, plan) + preview = { + "files": [ + { + "path": "hidden.py", + "status": "modified", + "insertions": 1, + "deletions": 1, + "will_review": False, + "exclude_reason": "default_path", + }, + { + "path": "selected.py", + "status": "modified", + "insertions": 1, + "deletions": 1, + "will_review": True, + }, + ], + "total_insertions": 2, + "total_deletions": 2, + "total_files": 2, + "reviewable_count": 1, + "excluded_count": 1, + } + selection = qualify_review_preview(projection, json.dumps(preview).encode()) + assert [entry.path for entry in selection.selected] == ["selected.py"] + assert [(item.entry.path, item.reason) for item in selection.excluded] == [ + ("hidden.py", "default_path") + ] + fingerprints = dict(projection.fingerprints) + selected_id = next( + item_id + for item_id, entry in zip(fingerprints, projection.ordinary_diff, strict=True) + if entry.path == "selected.py" + ) + excluded_id = next( + item_id + for item_id, entry in zip(fingerprints, projection.ordinary_diff, strict=True) + if entry.path == "hidden.py" + ) + selected_record = { + "item_id": selected_id, + "path": "selected.py", + "fingerprint": fingerprints[selected_id], + } + payload: dict[str, object] = { + "status": "complete", + "comments": [], + "manifest": { + "schema_version": "ocr.run-manifest/v1", + "operation": "review", + "terminal_state": "complete", + "input": { + "mode": "range", + "requested_from": base, + "requested_head": head, + "resolved_base": base, + "resolved_head": head, + "exact_range": f"{base}..{head}", + "source_artifact_sha256": gitlink_selection_proof(projection, selection.selected)[ + "source_artifact_sha256" + ], + }, + "execution": {"ocr_version": f"v{RECOMMENDED_OCR_VERSION}"}, + "coverage": { + "selected": [selected_record], + "excluded": [ + { + "item_id": excluded_id, + "path": "hidden.py", + "exclude_reason": "default_path", + } + ], + "completed": [selected_record], + "reused": [], + "failed": [], + "waived": [], + }, + }, + } + qualify_review_manifest(projection, selection, payload) + manifest = payload["manifest"] + assert isinstance(manifest, dict) + manifest["coverage"]["excluded"] = [] + with pytest.raises(RepositoryEvidenceError, match="omitted excluded"): + qualify_review_manifest(projection, selection, payload) + gitignored = ReviewSelection( + selection.selected, (PreviewExclusion(selection.excluded[0].entry, "gitignore"),) + ) + assert qualify_review_manifest(projection, gitignored, payload) is True + manifest["execution"]["ocr_version"] = "v1.14.5" + with pytest.raises(RepositoryEvidenceError, match="omitted excluded"): + qualify_review_manifest(projection, gitignored, payload) + manifest["execution"]["ocr_version"] = "v99.99.99" + with pytest.raises(RepositoryEvidenceError, match="unsupported binary"): + qualify_review_manifest(projection, gitignored, payload) + manifest["execution"]["ocr_version"] = f"v{RECOMMENDED_OCR_VERSION}" + payload["status"] = manifest["terminal_state"] = "skipped" + manifest["coverage"].update(selected=[], completed=[]) + with pytest.raises(RepositoryEvidenceError, match="omitted selected"): + qualify_review_manifest(projection, gitignored, payload) + + +def test_filtered_ordinary_proof_rejects_non_string_exclusion_reason(tmp_path: Path) -> None: + base, head = _ordinary_exclusion_fixture(tmp_path) + reader = GitRepositoryReader(tmp_path) + projection = make_gitlink_projection(reader, plan_review_input(reader, base, head)) + hidden, reviewed = projection.ordinary_diff + selection = ReviewSelection((reviewed,), (PreviewExclusion(hidden, "gitignore"),)) + proof = review_selection_proof(projection, selection) + result = { + "status": "completed_with_errors", + "comments": [], + TOOLKIT_REVIEW_SELECTION_KEY: proof, + TOOLKIT_RESULT_KEY: { + "publication": { + "state": "publication-filtered", + "original": {"selected": 1, "excluded": 1}, + }, + }, + } + assert selection_from_review_proof(projection, result) == selection + for reason in ([], {}, None): + proof["excluded"][0]["exclude_reason"] = reason # type: ignore[index] + with pytest.raises(RepositoryEvidenceError, match="excluded identities are invalid"): + selection_from_review_proof(projection, result) @pytest.mark.parametrize( @@ -214,6 +509,55 @@ def test_projection_rejects_wrong_preview(tmp_path: Path, mutate: object) -> Non qualify_gitlink_preview(projection, json.dumps(payload).encode()) +@pytest.mark.parametrize( + ("damage", "message"), + ( + ( + lambda view: view.replace( + b'"will_review": true', b'"will_review": false, "will_review": true' + ), + "is not valid JSON", + ), + ( + lambda view: view.replace( + b'"excluded_count": 0', b'"excluded_count": 1, "excluded_count": 0' + ), + "is not valid JSON", + ), + ( + lambda _: b"[" * 5000 + b"0" + b"]" * 5000, + r"(?:is not valid JSON|has an unsupported schema)", + ), + (lambda _: b"9" * 10_000, r"(?:is not valid JSON|has an unsupported schema)"), + (lambda _: b"\xff", "is not valid JSON"), + ), + ids=("duplicate-decision", "duplicate-total", "nesting", "integer", "encoding"), +) +def test_preview_rejects_duplicate_fields_and_decoder_failures( + tmp_path: Path, damage, message +) -> None: + base, head = _fixture(tmp_path, "updated") + reader = GitRepositoryReader(tmp_path) + projection = make_gitlink_projection(reader, plan_review_input(reader, base, head)) + raw = _preview() + assert qualify_review_preview(projection, raw).selected + with pytest.raises(RepositoryEvidenceError, match=f"preview {message}"): + qualify_review_preview(projection, damage(raw)) + + +def test_ordinary_projection_limits_combined_entries_before_preview( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + base, head = _ordinary_exclusion_fixture(tmp_path) + reader = GitRepositoryReader(tmp_path) + plan = plan_review_input(reader, base, head) + monkeypatch.setattr(gitlink_projection, "MAX_COVERAGE_RECORDS", 2) + assert len(make_gitlink_projection(reader, plan).ordinary_diff) == 2 + monkeypatch.setattr(gitlink_projection, "MAX_COVERAGE_RECORDS", 1) + with pytest.raises(RepositoryEvidenceError, match="ordinary diff exceeds the review coverage"): + make_gitlink_projection(reader, plan) + + def test_projection_detects_local_git_input_drift(tmp_path: Path) -> None: base, head = _fixture(tmp_path, "updated") reader = GitRepositoryReader(tmp_path) @@ -500,7 +844,7 @@ def drift(*_args: object) -> None: monkeypatch.setattr(review_runner, "verify_gitlink_projection", drift) with pytest.raises(review_runner.ReviewRunnerError, match="drifted during"): - review_runner._verify_gitlink_after_execution(result, projection) + review_runner._verify_projection_after_execution(result, projection) assert not result.exists() @@ -655,6 +999,7 @@ def test_projection_rejects_wrong_manifest_identity_or_reuse(tmp_path: Path) -> "execution": {"ocr_version": f"v{RECOMMENDED_OCR_VERSION}"}, "coverage": { "selected": [item], + "excluded": [], "completed": [item], "reused": [], "failed": [], @@ -692,7 +1037,7 @@ def test_projection_rejects_wrong_manifest_identity_or_reuse(tmp_path: Path) -> qualify_gitlink_manifest(projection, projection.ordinary_diff, payload) coverage["completed"] = [item] coverage["reused"] = [item] - with pytest.raises(RepositoryEvidenceError, match="unreviewed"): + with pytest.raises(RepositoryEvidenceError, match="invalid contract"): qualify_gitlink_manifest(projection, projection.ordinary_diff, payload) coverage["reused"] = [] payload["comments"] = [{"path": []}] @@ -984,28 +1329,42 @@ def test_installed_ocr_gitlink_preview_qualification( assert changed_gitlinks(GitRepositoryReader(repo), base, head)[0].kind == kind -@pytest.mark.parametrize("kind", ["added", "updated", "deleted", "mixed", "move"]) +@pytest.mark.parametrize( + "kind", + [ + "added", + "updated", + "deleted", + "mixed", + "excluded-rename", + "move", + "ordinary", + "ordinary-quoted", + "ordinary-non-utf8", + ], +) def test_installed_ocr_projected_review_matches_native_manifest( tmp_path: Path, kind: str, monkeypatch: pytest.MonkeyPatch, qualified_native_ocr ) -> None: """Opt-in production proof against the official binary and local fake provider.""" - binary, _version = qualified_native_ocr("OCR_GITLINK_QUALIFY_BINARY") + binary, version = qualified_native_ocr("OCR_GITLINK_QUALIFY_BINARY") monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[1] / "scripts")) from ocr_qualification.peer import _stub_gateway repo = tmp_path / "repo" repo.mkdir() - base, head = ( - _mixed_fixture(repo) - if kind == "mixed" - else _move_fixture(repo) - if kind == "move" - else _fixture(repo, kind) - ) + fixtures = { + "mixed": _mixed_fixture, + "excluded-rename": _mixed_fixture, + "move": _move_fixture, + "ordinary": _ordinary_exclusion_fixture, + "ordinary-quoted": _ordinary_quoted_fixture, + "ordinary-non-utf8": _ordinary_non_utf8_fixture, + } + base, head = fixtures[kind](repo) if kind in fixtures else _fixture(repo, kind) reader = GitRepositoryReader(repo) - plan = plan_gitlink_input(reader, base, head) - assert plan is not None + plan = plan_review_input(reader, base, head) projection = make_gitlink_projection(reader, plan) home = tmp_path / "ocr-home" home.mkdir(mode=0o700) @@ -1025,6 +1384,10 @@ def test_installed_ocr_projected_review_matches_native_manifest( "--concurrency", "1", ] + if kind == "excluded-rename": + args.extend(["--exclude", "renamed.py"]) + elif kind == "ordinary-non-utf8": + args.extend(["--exclude", "legacy.py"]) preview = subprocess.run( [*args, "--preview"], cwd=repo, @@ -1034,12 +1397,36 @@ def test_installed_ocr_projected_review_matches_native_manifest( timeout=30, ) assert preview.returncode == 0 and preview.stderr == b"" - selected = qualify_gitlink_preview(projection, preview.stdout) + if kind == "ordinary" and version == "1.14.5": + # This qualified binary omits tracked gitignored files from preview. + assert {entry.path for entry in projection.ordinary_diff} == {"hidden.py", "selected.py"} + assert [item["path"] for item in json.loads(preview.stdout)["files"]] == ["selected.py"] + with pytest.raises(RepositoryEvidenceError, match="omitted or added diff records"): + qualify_review_preview(projection, preview.stdout) + return + selection = qualify_review_preview(projection, preview.stdout) + selected = selection.selected assert selected assert all(entry.status != "D" for entry in selected) if kind in {"added", "updated", "deleted"}: assert selected == projection.ordinary_diff - with _stub_gateway() as gateway: + elif kind == "ordinary": + assert [entry.path for entry in selected] == ["selected.py"] + assert [(item.entry.path, item.reason) for item in selection.excluded] == [ + ("hidden.py", "gitignore") + ] + elif kind == "ordinary-non-utf8": + assert [entry.path for entry in selected] == ["selected.py"] + assert [(item.entry.path, item.reason) for item in selection.excluded] == [ + ("legacy.py", "user_exclude") + ] + + def finish_review(_request): + return {"name": "task_done", "arguments": "{}"}, "call-done" + + # The default stub extracts an XML-attribute path to generate a finding. + # A clean response here tests native coverage without that fixture parser. + with _stub_gateway(tool_script=finish_review if kind == "ordinary-quoted" else None) as gateway: env.update( { "OCR_LLM_URL": gateway, @@ -1058,7 +1445,20 @@ def test_installed_ocr_projected_review_matches_native_manifest( timeout=90, ) assert production.returncode == 0 and production.stderr == b"" - qualify_gitlink_manifest(projection, selected, json.loads(production.stdout)) + payload = json.loads(production.stdout) + qualify_review_manifest( + projection, selection, payload, require_fresh_complete=kind != "ordinary" + ) + if kind == "excluded-rename": + (renamed,) = ( + record + for record in payload["manifest"]["coverage"]["excluded"] + if record["path"] == "renamed.py" + ) + assert renamed["old_path"] == "old.py" + renamed["old_path"] = "wrong.py" + with pytest.raises(RepositoryEvidenceError, match="excluded item disagrees"): + qualify_review_manifest(projection, selection, payload, require_fresh_complete=True) verify_gitlink_projection(reader, projection) @@ -1068,7 +1468,7 @@ def test_installed_ocr_toolkit_local_gitlink_route( ) -> None: """Exercise the toolkit and real OCR together without a paid model or forge.""" - binary, _version = qualified_native_ocr("OCR_GITLINK_QUALIFY_BINARY") + binary, version = qualified_native_ocr("OCR_GITLINK_QUALIFY_BINARY") monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[1] / "scripts")) import http.server import threading @@ -1144,7 +1544,13 @@ def do_POST(self) -> None: repo = tmp_path / "repo" repo.mkdir() - base, head = _gitlink_only_fixture(repo) if kind == "only" else _fixture(repo, kind) + reports_gitignore = kind == "updated" and tuple(map(int, version.split("."))) >= (1, 14, 6) + if reports_gitignore: + base, head = _gitignore_fixture(repo) + elif kind == "only": + base, head = _gitlink_only_fixture(repo) + else: + base, head = _fixture(repo, kind) home = tmp_path / "home" home.mkdir(mode=0o700) bin_dir = tmp_path / "bin" @@ -1211,6 +1617,15 @@ def local_url_parser(value: str, name: str): # type: ignore[no-untyped-def] assert code == 0, stderr.read_text(encoding="utf-8")[:2000] assert EvidenceStub.issued_evidence assert "evidence" in EvidenceStub.request_stages - assert "partial" in report.read_text(encoding="utf-8").lower() + markdown = report.read_text(encoding="utf-8") + assert "partial" in markdown.lower() payload = json.loads(result.read_text(encoding="utf-8")) assert payload["status"] == "complete" + if reports_gitignore: + coverage = payload["manifest"]["coverage"] + assert {item["path"] for item in coverage["completed"]} == { + ".gitignore", + "main.php", + "nested/kept.php", + } + assert "3 of 5 ordinary diff record(s) completed" in markdown diff --git a/tests/test_installed_policy_e2e.py b/tests/test_installed_policy_e2e.py index 298ffdd1..11380e0e 100644 --- a/tests/test_installed_policy_e2e.py +++ b/tests/test_installed_policy_e2e.py @@ -11,11 +11,13 @@ import sys import tarfile from datetime import UTC, datetime +from hashlib import sha256 from pathlib import Path from urllib.parse import parse_qs, urlsplit import pytest +from ocr_toolkit.preflight import RECOMMENDED_OCR_VERSION from tests.support import PROJECT_ROOT, native_range_input from tests.test_context_policy import policy_value from tests.test_gitlab_discussions import note @@ -67,6 +69,43 @@ def git(*args: str) -> str: {"path": "src/sample.py", "line": 1, "content": message} for message in (safe_finding, discussion_text) ] + # Native peer records for the one known committed patch. The installed + # toolkit independently calculates and verifies each identity with Git. + path = "src/sample.py" + diff = "\n".join( + ( + f"diff --git a/{path} b/{path}", + f"--- a/{path}", + f"+++ b/{path}", + "@@ -1 +1 @@", + "-VALUE = 1", + "+VALUE = 2", + ) + ) + item_id = sha256("\0".join(("review", "range", path, path)).encode()).hexdigest() + fingerprint = sha256("\0".join(("range", path, path, diff)).encode()).hexdigest() + source_digest = sha256() + for value in (item_id, fingerprint): + encoded = value.encode() + source_digest.update(len(encoded).to_bytes(8, "big")) + source_digest.update(encoded) + item = {"item_id": item_id, "path": path, "fingerprint": fingerprint} + preview = { + "files": [ + { + "path": path, + "status": "modified", + "insertions": 1, + "deletions": 1, + "will_review": True, + } + ], + "total_insertions": 1, + "total_deletions": 1, + "total_files": 1, + "reviewable_count": 1, + "excluded_count": 0, + } model_result = root / "model-result.json" payload = { "status": "complete", @@ -77,10 +116,15 @@ def git(*args: str) -> str: "schema_version": "ocr.run-manifest/v1", "operation": "review", "terminal_state": "complete", - "input": native_range_input(base, head), + "input": { + **native_range_input(base, head), + "source_artifact_sha256": source_digest.hexdigest(), + }, + "execution": {"ocr_version": f"v{RECOMMENDED_OCR_VERSION}"}, "coverage": { - "selected": [{"item_id": "src/sample.py"}], - "completed": [{"item_id": "src/sample.py"}], + "selected": [item], + "completed": [item], + "excluded": [], "reused": [], "failed": [], "waived": [], @@ -96,7 +140,12 @@ def git(*args: str) -> str: import sys from pathlib import Path +fixture = json.loads(Path(sys.argv[1]).read_text()) +payload = fixture["payload"] +for option, key in (("--from", "resolved_base"), ("--to", "resolved_head")): + assert sys.argv[sys.argv.index(option) + 1] == payload["manifest"]["input"][key] if "--preview" in sys.argv: + print(json.dumps(fixture["preview"])) raise SystemExit(0) from ocr_toolkit import __version__ @@ -121,7 +170,6 @@ def exchange(calls): assert len(outputs) == len(calls) and all(not item.get("isError") for item in outputs) return [json.loads(item["content"][0]["text"]) for item in outputs] -fixture = json.loads(Path(sys.argv[1]).read_text()) summary, listed = exchange([ ("ocr_toolkit_evidence", {"action":"summary"}), ("context_list", {"resource_class":"ci_outcome"}), @@ -136,7 +184,6 @@ def exchange(calls): assert ci["scope"] == {"mode":"declared", "path_prefixes":["src/"]} else: assert records == [] -payload = fixture["payload"] tools = {"ocr_toolkit_evidence": 1, "context_list": 1} if records: tools["context_get"] = 1 @@ -263,7 +310,8 @@ def post(peer: _GitLabHandler) -> None: else "openai/another-model" } model_result.write_text( - json.dumps({"payload": payload, "expected_ci": with_ci}), encoding="utf-8" + json.dumps({"payload": payload, "preview": preview, "expected_ci": with_ci}), + encoding="utf-8", ) delivered.clear() result = root / f"{scenario}.json" @@ -294,6 +342,13 @@ def post(peer: _GitLabHandler) -> None: ) assert metadata["review"]["diff_base_sha"] == base assert metadata["review"]["source_sha"] == head + assert metadata["schema_version"] == 15 + coverage = metadata["review_coverage"] + assert (coverage["state"], coverage["changed"], coverage["excluded"]) == ( + "complete", + 1, + 0, + ) assert metadata["context"]["per_source"]["forge:ci_outcomes"] == ( "complete" if with_ci else "partial" ) @@ -597,6 +652,12 @@ def catalog(handler: _GitLabHandler) -> None: calls.clear() +def test_installed_wheel_passes_release_federation_smoke(installed_wheel, tmp_path): + python, _ = installed_wheel + result = _run([str(python), "-I", str(RUNTIME_SMOKE)], cwd=tmp_path) + assert json.loads(result) == {"installed_runtime_smoke": "ok"} + + def test_installed_ci_selectors_preserve_gitlab_findings_and_private_result( installed_wheel: tuple[Path, Path], tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tests/test_integration_contracts.py b/tests/test_integration_contracts.py index 10129d6d..7b5df3b0 100644 --- a/tests/test_integration_contracts.py +++ b/tests/test_integration_contracts.py @@ -11,6 +11,7 @@ from datetime import date import pytest +import yaml from ocr_toolkit.context.policy import parse_policy from ocr_toolkit.evidence.policy import parse_accepted_decisions @@ -355,10 +356,19 @@ def test_public_bounded_context_recipes_match_runtime_schemas( "package", ] mode_root = PROJECT_ROOT / "examples" / "gitlab" / "modes" - direct_recipe = (mode_root / "direct-mcp.gitlab-ci.yml").read_text(encoding="utf-8") - direct_json = direct_recipe.split("OCR_MCP_SERVERS_JSON: >-\n", 1)[1].splitlines()[0] - monkeypatch.setenv("REVIEW_EVIDENCE_MCP_AUTHORIZATION", "example-test-secret") - direct_config = parse_mcp_servers(direct_json.strip(), profile="gitlab_mr") + for name in ("identity-only", "metadata", "enriched-discussions"): + recipe = yaml.safe_load((mode_root / f"{name}.gitlab-ci.yml").read_text(encoding="utf-8")) + assert ( + parse_mcp_servers(recipe["variables"]["OCR_MCP_SERVERS_JSON"], profile="gitlab_mr") + == [] + ) + + direct_recipe = yaml.safe_load( + (mode_root / "direct-mcp.gitlab-ci.yml").read_text(encoding="utf-8") + ) + direct_config = parse_mcp_servers( + direct_recipe["variables"]["OCR_MCP_SERVERS_JSON"], profile="gitlab_mr" + ) assert direct_config[0].name == "review_evidence" assert direct_config[0].transport == "https" assert [tool.alias for tool in direct_config[0].tools] == [ @@ -402,13 +412,13 @@ def test_public_docs_describe_current_context_and_federation_boundaries() -> Non "ocr.context-store/v2", "context_list", "context_get", - "receipt v13", + "ordinary receipt", "no migration path", "semantic paraphrase", ): assert contract in normalized_bounded for document in (configuration, gitlab, operations, security): - assert "receipt v13" in document + assert "ordinary receipt" in document assert "review-context.md" in document for document in (configuration, operations, security): assert "OCR_DLP_ENABLED" in document @@ -439,10 +449,10 @@ def test_security_workflow_pins_the_local_gitleaks_version() -> None: workflow = (PROJECT_ROOT / ".github" / "workflows" / "security.yml").read_text(encoding="utf-8") wrapper = (PROJECT_ROOT / "scripts" / "gitleaks.sh").read_text(encoding="utf-8") - assert "Load pinned Gitleaks version" in workflow - assert "./scripts/gitleaks.sh --version" in workflow - assert "GITLEAKS_VERSION:" not in workflow - assert wrapper.count("GITLEAKS_VERSION=") == 1 + version = re.findall(r"^GITLEAKS_VERSION=([0-9.]+)$", wrapper, re.MULTILINE) + assert len(version) == 1 + assert re.search(rf"\b{re.escape(version[0])}\) digest=[0-9a-f]{{64}} ;;", workflow) + assert "gitleaks-action" not in workflow def test_release_workflows_do_not_duplicate_the_security_gitleaks_job() -> None: diff --git a/tests/test_local_incremental.py b/tests/test_local_incremental.py index 6a53ce99..99cf5166 100644 --- a/tests/test_local_incremental.py +++ b/tests/test_local_incremental.py @@ -20,12 +20,15 @@ from ocr_toolkit.evidence.repository import GitRepositoryReader from ocr_toolkit.local_incremental_dependencies import dependency_path from ocr_toolkit.local_incremental_imports import StaticImport, import_dependencies +from ocr_toolkit.local_incremental_replay import observed_replay from ocr_toolkit.local_incremental_state import ( CachedFile, DependencyScope, IncrementalError, ReviewCache, + ToolReplay, cache_path_for, + canonical_json, read_cache, write_cache, ) @@ -59,6 +62,33 @@ def _fixture(tmp_path, environment): return root, base, head, paths, changed +def _mixed_fixture(tmp_path, environment): + compat = load_script() + paths = [f"file_{index:02}.{'md' if index % 2 else 'json'}" for index in range(23)] + texts = { + path: ( + "# Release notes\n\nExample state is ready.\n" + if path.endswith(".md") + else f'{{\n "{Path(path).stem}_state": "ready"\n}}\n' + ) + for path in paths + } + texts[paths[7]] += f"See [configuration]({paths[6]}).\n" + texts[paths[9]] += f"The setting is `{Path(paths[6]).stem}_state`.\n" + initial = {path: text.replace("ready", "waiting") for path, text in texts.items()} + first, *others = paths + root, base, _ = compat.execution._synthetic_repo( + tmp_path, + environment, + source_path=first, + baseline=initial[first], + changed=texts[first], + context_files={path: initial[path] for path in others}, + ) + head = _edit(root, environment, {path: texts[path] for path in others}) + return root, base, head, paths, texts + + def _edit(root, environment, files): compat = load_script() for path, content in files.items(): @@ -120,6 +150,41 @@ def test_private_cache_rejects_injected_shape_and_link(tmp_path): assert json.loads(target.read_text()) == raw +def test_private_cache_keeps_one_bounded_scope_and_rejects_invalid_replay_controls(tmp_path): + path = tmp_path / "incremental.json" + members = tuple(f"source_{index:03}.md" for index in range(64)) + replays = tuple( + ToolReplay( + "code_search", + canonical_json( + {"search_text": f"example {index} " + "x" * 480, "file_patterns": ["x" * 250] * 4} + ).decode(), + "1" * 64, + ) + for index in range(32) + ) + scope = DependencyScope(members, (), replays) + cache = ReviewCache( + ReviewRange("a" * 40, "b" * 40), + "c" * 64, + "d" * 64, + {name: CachedFile("100644", "e" * 40, "b" * 40, _RUN, (), scope) for name in members}, + "f" * 64, + ) + write_cache(path, cache) + raw = json.loads(path.read_text()) + assert read_cache(path) == cache + assert len(raw["scopes"]) == 1 + assert {file["scope"] for file in raw["files"].values()} == {members[0]} + assert path.stat().st_size < 100_000 + raw["scopes"][members[0]]["replays"][0]["arguments"] = ( + '{"file_patterns":[":(attr:unsupported)*"],"search_text":"example"}' + ) + path.write_text(json.dumps(raw)) + with pytest.raises(IncrementalError, match="unsupported"): + read_cache(path) + + def test_checkout_slot_tracks_branch_detached_worktree_and_credential(tmp_path, monkeypatch): compat = load_script() operator_home = tmp_path / "home" @@ -133,7 +198,9 @@ def test_checkout_slot_tracks_branch_detached_worktree_and_credential(tmp_path, monkeypatch.delenv(key) def prepare(checkout, token="synthetic-first-token"): - write_ocr_config({"llm": {"auth_token": token}}) + write_ocr_config( + {"llm": {"auth_token": token, "extra_headers": {"X-Review": "Bearer headerRover"}}} + ) session = local_incremental.prepare( repository_artifacts(checkout), ReviewRange(base, head), @@ -159,6 +226,10 @@ def save_sample(session): session.save() first = prepare(root) + assert not local_incremental._replay_text_admitted("headerRover", first.matcher) + assert not local_incremental._replay_text_admitted("Bearer headerRover", first.matcher) + assert not local_incremental._replay_text_admitted("synthetic-first-token", first.matcher) + assert local_incremental._replay_text_admitted("unrelated_literal", first.matcher) changed_credential = prepare(root, "synthetic-other-token") assert changed_credential.cache_path == first.cache_path assert changed_credential.digest != first.digest @@ -192,6 +263,67 @@ def save_sample(session): cache_path_for(root, linked) +def _prepare_session(root, base, head, operator_home): + write_ocr_config({"llm": {"auth_token": "synthetic-first-token"}}) + return local_incremental.prepare( + repository_artifacts(root), + ReviewRange(base, head), + operator_home=operator_home, + args=["--from", base, "--to", head], + native_version=RECOMMENDED_OCR_VERSION, + bootstrap=f"- head: `{head}`\n", + external_tools=False, + diagram=False, + dlp_enabled=True, + ) + + +def _incremental_fixture(tmp_path, monkeypatch): + compat = load_script() + operator_home = tmp_path / "home" + environment = compat.execution._isolated_probe_environment(operator_home) + root, base, head, _paths, _ = _fixture(tmp_path, environment) + isolated_home = tmp_path / "isolated" + isolated_home.mkdir(mode=0o700) + monkeypatch.setenv("HOME", str(isolated_home)) + for key in list(os.environ): + if key.startswith("GIT_"): + monkeypatch.delenv(key) + return root, base, head, operator_home + + +def test_editor_selection_variables_do_not_disqualify_incremental_review(tmp_path, monkeypatch): + root, base, head, operator_home = _incremental_fixture(tmp_path, monkeypatch) + monkeypatch.setenv("GIT_EDITOR", "true") + monkeypatch.setenv("GIT_SEQUENCE_EDITOR", "true") + session = _prepare_session(root, base, head, operator_home) + assert session is not None + assert "GIT_EDITOR" not in session.child_environment + assert "GIT_SEQUENCE_EDITOR" not in session.child_environment + + +def test_unsupported_git_setting_is_named_in_fallback_message(tmp_path, monkeypatch, capsys): + root, base, head, operator_home = _incremental_fixture(tmp_path, monkeypatch) + monkeypatch.setenv("GIT_CEILING_DIRECTORIES", "/nonexistent") + assert _prepare_session(root, base, head, operator_home) is None + assert "GIT_CEILING_DIRECTORIES" in capsys.readouterr().err + + +def test_unknown_git_setting_name_and_value_stay_out_of_fallback_message( + tmp_path, monkeypatch, capsys +): + root, base, head, operator_home = _incremental_fixture(tmp_path, monkeypatch) + monkeypatch.setenv("GIT_X\nINJECTED_NAME", "secret-value") + monkeypatch.setenv("GIT_CEILING_DIRECTORIES", "/nonexistent") + assert _prepare_session(root, base, head, operator_home) is None + err = capsys.readouterr().err + assert "GIT_CEILING_DIRECTORIES" in err + assert "INJECTED_NAME" not in err + assert "secret-value" not in err + assert "/nonexistent" not in err + assert len(err.strip().splitlines()) == 1 + + @pytest.mark.parametrize("narrowed", (False, True)) def test_native_handoff_at_limit_keeps_local_marker_when_narrowed(tmp_path, monkeypatch, narrowed): result = tmp_path / "result.json" @@ -202,7 +334,7 @@ def test_native_handoff_at_limit_keeps_local_marker_when_narrowed(tmp_path, monk files = (ReusedFile("module.py", "b" * 40, _RUN, ()),) if narrowed else () report = IncrementalReport(files, 0, "Full review" if not narrowed else "") finalized = transform_ocr_result( - result, lambda value: local_incremental._bounded_incremental_result(value, report) + result, lambda value: local_incremental.bounded_incremental_result(value, report) ) assert stat.S_IMODE(result.stat().st_mode) == 0o600 assert result.stat().st_size <= len(raw) @@ -226,7 +358,7 @@ def test_compact_native_handoff_cannot_claim_success_without_fresh_findings(tmp_ monkeypatch.setenv("OCR_MAX_RESULT_BYTES", str(len(raw))) incremental = IncrementalReport((ReusedFile("module.py", "b" * 40, _RUN, ()),), 0) result = transform_ocr_result( - path, lambda value: local_incremental._bounded_incremental_result(value, incremental) + path, lambda value: local_incremental.bounded_incremental_result(value, incremental) ) assert set(result) == {RESULT_KEY} assert result[RESULT_KEY]["native_findings_omitted"] == 1 @@ -632,6 +764,138 @@ def test_static_dependency_qualification_follows_content_under_arbitrary_names(t ) +def test_changed_unknown_code_requires_full_dependency_qualification(tmp_path): + compat = load_script() + environment = compat.execution._isolated_probe_environment(tmp_path / "home") + root, _, prior = compat.execution._synthetic_repo( + tmp_path, + environment, + source_path="export.js", + baseline="export const limit = 1;\n", + changed="export const limit = 2;\n", + context_files={"use.js": 'import {limit} from "./export.js";\n'}, + ) + head = _edit(root, environment, {"export.js": "export const limit = 3;\n"}) + with pytest.raises(IncrementalError, match="unsupported shared source semantics"): + local_incremental._independent_paths( + GitRepositoryReader(root), prior, head, {"export.js", "use.js"}, {"export.js"} + ) + + +def test_json_edit_rechecks_executable_consumers_and_dot_prefixed_file_references(tmp_path): + compat = load_script() + environment = compat.execution._isolated_probe_environment(tmp_path / "home") + root, _, prior = compat.execution._synthetic_repo( + tmp_path, + environment, + source_path=".settings.json", + baseline='{"featureEnabled": false}\n', + changed='{"featureEnabled": true}\n', + context_files={ + "guide.md": "See [settings](./.settings.json).\n", + "other.md": "Unrelated document.\n", + "program.sh": 'printf "%s" "$runtime_flag"\n', + }, + ) + head = _edit(root, environment, {".settings.json": '{"featureEnabled": false}\n'}) + reader = GitRepositoryReader(root) + selected = {".settings.json", "guide.md", "other.md", "program.sh"} + assert local_incremental._independent_paths( + reader, prior, head, selected, {".settings.json"} + ) == {"other.md"} + changed_interface = _edit(root, environment, {".settings.json": '{"newOption": false}\n'}) + with pytest.raises(IncrementalError, match="new data interface"): + local_incremental._independent_paths( + reader, head, changed_interface, selected, {".settings.json"} + ) + + +@pytest.mark.parametrize( + ("mode", "prefix"), + ((0o755, ""), (0o644, "#!/bin/sh\n")), +) +def test_executable_content_cannot_qualify_as_markdown_data(tmp_path, mode, prefix): + compat = load_script() + environment = compat.execution._isolated_probe_environment(tmp_path / "home") + root, _, _ = compat.execution._synthetic_repo( + tmp_path, + environment, + source_path="settings.json", + baseline='{"featureEnabled": false}\n', + changed='{"featureEnabled": true}\n', + context_files={"unrelated.md": "Unrelated document.\n"}, + ) + script = root / "check.md" + script.touch(mode=mode) + prior = _edit(root, environment, {"check.md": prefix + 'printf "%s" "$runtime_flag"\n'}) + head = _edit(root, environment, {"settings.json": '{"featureEnabled": false}\n'}) + reader = GitRepositoryReader(root) + selected = {"settings.json", "unrelated.md", "check.md"} + assert local_incremental._independent_paths( + reader, prior, head, selected, {"settings.json"} + ) == {"unrelated.md"} + changed_script = _edit(root, environment, {"check.md": prefix + 'printf "%s" "$other_flag"\n'}) + with pytest.raises(IncrementalError, match="unsupported shared source semantics"): + local_incremental._independent_paths(reader, head, changed_script, selected, {"check.md"}) + + +@pytest.mark.parametrize( + "link", + ( + "[Setup](../guide%2Dsetup.md#configure)\n", + r"[Setup](../guide\-setup.md)" + "\n", + "[Setup][guide]\n\n[guide]: ../guide%2Dsetup.md\n", + "[Unavailable](../unknown%2Dsetup.md)\n", + 'Setup\n', + ), +) +def test_markdown_rechecks_resolved_or_ambiguous_link_dependencies(tmp_path, link): + compat = load_script() + environment = compat.execution._isolated_probe_environment(tmp_path / "home") + root, _, prior = compat.execution._synthetic_repo( + tmp_path, + environment, + source_path="guide-setup.md", + baseline="Previous setup.\n", + changed="Reviewed setup.\n", + context_files={"notes/link.md": link, "unrelated.md": "Unrelated document.\n"}, + ) + head = _edit(root, environment, {"guide-setup.md": "Current setup.\n"}) + assert local_incremental._independent_paths( + GitRepositoryReader(root), + prior, + head, + {"guide-setup.md", "notes/link.md", "unrelated.md"}, + {"guide-setup.md"}, + ) == {"unrelated.md"} + + +def test_unselected_markdown_link_makes_its_selected_chain_uncertain(tmp_path): + compat = load_script() + environment = compat.execution._isolated_probe_environment(tmp_path / "home") + root, _, prior = compat.execution._synthetic_repo( + tmp_path, + environment, + source_path="details.md", + baseline="Previous setup.\n", + changed="Reviewed setup.\n", + context_files={ + "guide.md": "[Index](catalog/index.md) and [Setup](linked%2Dsetup.md)\n", + "catalog/index.md": "[Details](../details.md)\n", + "cover.md": "[Guide](guide.md)\n", + "linked-setup.md": "More guidance.\n", + "unrelated.md": "Unrelated document.\n", + }, + ) + head = _edit(root, environment, {"details.md": "Current setup.\n"}) + reader = GitRepositoryReader(root) + selected = {"details.md", "guide.md", "unrelated.md"} + for selection in (selected, selected | {"cover.md", "linked-setup.md"}): + assert local_incremental._independent_paths( + reader, prior, head, selection, {"details.md"} + ) == {"unrelated.md"} + + @pytest.mark.parametrize("rule", ("manual.TXT", "guidance/intro.markdown", ".md")) def test_native_file_rule_references_fail_incremental_qualification(tmp_path, rule): path = tmp_path / "rule.json" @@ -696,6 +960,90 @@ def test_native_incomplete_carried_finding_returns_partial_after_delivery( ) +def test_native_incremental_reuses_21_markdown_and_json_files_after_unchanged_search( + tmp_path, monkeypatch, qualified_native_ocr, capsys +): + _native_incremental_case( + tmp_path, monkeypatch, qualified_native_ocr, capsys, "flag", True, mixed=True + ) + + +@pytest.mark.parametrize( + ("tool", "arguments", "result"), + ( + ( + "ocr_toolkit_evidence", + {"action": "list"}, + { + "records": [], + "next_cursor": "continued", + "returned": 0, + }, + ), + ( + "ocr_toolkit_evidence", + {"action": "list", "cursor": "later"}, + { + "records": [], + "next_cursor": None, + "returned": 0, + }, + ), + ( + "ocr_toolkit_evidence_search", + {"query": "example"}, + { + "schema_version": "ocr.evidence-search/v1", + "matches": [], + "truncated": False, + "returned": 0, + "total_matches": 3, + }, + ), + ( + "ocr_toolkit_evidence_search", + {"query": "example"}, + { + "schema_version": "ocr.evidence-search/v1", + "matches": [], + "truncated": True, + "returned": 0, + "total_matches": 3, + }, + ), + ( + "ocr_toolkit_evidence_coverage", + {"kind": "repository.file"}, + { + "schema_version": "ocr.evidence-coverage-query/v1", + "state": "unknown", + "coverage_records": 1, + "truncated": False, + }, + ), + ), +) +def test_incomplete_evidence_results_cannot_qualify_for_replay(tool, arguments, result): + with pytest.raises(IncrementalError, match="incomplete"): + observed_replay(tool, arguments, json.dumps(result)) + + +def test_native_incremental_names_why_every_group_is_unqualified( + tmp_path, monkeypatch, qualified_native_ocr, capsys +): + _native_incremental_case( + tmp_path, monkeypatch, qualified_native_ocr, capsys, "flag", False, diagnostics_only=True + ) + + +def test_native_incremental_replays_diff_search_evidence_and_deterministic_read_failure( + tmp_path, monkeypatch, qualified_native_ocr, capsys +): + _native_incremental_case( + tmp_path, monkeypatch, qualified_native_ocr, capsys, "flag", False, advanced=True + ) + + def _native_incremental_case( tmp_path, monkeypatch, @@ -706,6 +1054,9 @@ def _native_incremental_case( *, diagram=False, drop=False, + mixed=False, + diagnostics_only=False, + advanced=False, ): qualifying_candidate = bool(os.environ.get("OCR_QUALIFY_CANDIDATE")) binary, _ = qualified_native_ocr( @@ -725,17 +1076,54 @@ def _native_incremental_case( monkeypatch.setenv("GIT_ALLOW_PROTOCOL", "") monkeypatch.setenv("GIT_NO_LAZY_FETCH", "1") - root, base, first, paths, previous_text = _fixture(tmp_path, environment) + if mixed: + root, base, first, paths, texts = _mixed_fixture(tmp_path, environment) + rule = root / ".opencodereview" / "rule.json" + rule.parent.mkdir(exist_ok=True) + rule.write_text('{"include":["*.md"]}') + else: + root, base, first, paths, previous_text = _fixture(tmp_path, environment) + texts = dict.fromkeys(paths, previous_text) monkeypatch.chdir(root) seen: Counter[str] = Counter() lock = threading.Lock() direct_affected, direct_unchanged, broad = paths[2:5] - direct_targets = {direct_affected: paths[0], direct_unchanged: paths[5]} + direct_targets = {direct_unchanged: paths[5]} + if not mixed: + direct_targets[direct_affected] = paths[0] confirmed_reads: set[str] = set() - confirmed_negative_search: set[str] = set() + confirmed_search: set[str] = set() + search_text = "Release notes" if mixed else "missing_synthetic_symbol" + operator_token = "roverJune" + evidence_path = paths[10] + advanced_calls = { + paths[6]: ("file_find", {"query_name": paths[10]}), + paths[7]: ("file_read_diff", {"path_array": [paths[8], paths[-1]]}), + paths[8]: ("file_read", {"file_path": paths[11], "start_line": 999, "end_line": 999}), + paths[9]: ("ocr_toolkit_evidence_search", {"query": "missing example evidence"}), + evidence_path: ( + "ocr_toolkit_evidence", + {"action": "list", "kind": "repository.file", "ref": "base", "page_size": 50}, + ), + } diagram_on = False diagram_owner = paths[0] confirmed_diagram: set[str] = set() + changed_now = set() + if mixed: + edited_texts = {path: text.replace("ready", "active") for path, text in texts.items()} + comment_anchors = { + path: texts[path].splitlines()[2 if path.endswith(".md") else 1] for path in paths + } + updated_anchors = { + path: text.replace("ready", "active") for path, text in comment_anchors.items() + } + else: + edited_texts = { + path: text.replace("return 2 +", "return 3 +") for path, text in texts.items() + } + comment_anchors = dict.fromkeys(paths, " return 2 + 0") + updated_anchors = dict.fromkeys(paths, " return 3 + 0") def tool_script(request): messages = request["messages"] @@ -809,7 +1197,30 @@ def tool_script(request): }, ) elif source_reads and len(names) == 1 and path == broad: - name, arguments = "code_search", {"search_text": "missing_synthetic_symbol"} + name, arguments = "code_search", {"search_text": search_text} + elif diagnostics_only and len(names) == 1: + if path == paths[0]: + name, arguments = "code_search", {"search_text": operator_token} + elif path == paths[1]: + name, arguments = "unregistered_review_tool", {} + else: + # Native accepts this pathspec syntax. The replay grammar is narrower. + name, arguments = ( + "code_search", + {"search_text": "private_synthetic_probe", "file_patterns": [":(glob)**/*.py"]}, + ) + elif advanced and len(names) == 1 and path in advanced_calls: + name, arguments = advanced_calls[path] + elif advanced and len(names) == 2 and path == evidence_path: + page = next( + json.loads(message["content"]) + for message in reversed(messages) + if message.get("role") == "tool" + ) + name, arguments = ( + "ocr_toolkit_evidence", + {"action": "get", "id": page["records"][0]["id"]}, + ) elif "code_comment" not in names: rendered = [ message.get("content", "") for message in messages if message.get("role") == "tool" @@ -819,25 +1230,31 @@ def tool_script(request): ): with lock: confirmed_diagram.add(path) - if "file_read" in names and any( - f"File: {direct_targets[path]} (Total lines:" in response for response in rendered + if ( + path in direct_targets + and "file_read" in names + and any( + f"File: {direct_targets[path]} (Total lines:" in response + for response in rendered + ) ): with lock: confirmed_reads.add(path) - if "code_search" in names and any( - "No matches found" in response for response in rendered - ): + search_marker = "Match lines:" if mixed else "No matches found" + if "code_search" in names and any(search_marker in response for response in rendered): with lock: - confirmed_negative_search.add(path) + confirmed_search.add(path) name, arguments = ( "code_comment", { "comments": [ { "path": path, - "existing_code": " return 2 + 0" - if path not in changed_now - else " return 3 + 0", + "existing_code": ( + updated_anchors[path] + if path in changed_now + else comment_anchors[path] + ), "thinking": "Synthetic private reasoning.", "content": "Review the return value.", "category": "maintainability", @@ -850,7 +1267,6 @@ def tool_script(request): name, arguments = "task_done", {} return {"name": name, "arguments": json.dumps(arguments)}, f"incremental-{len(names)}" - changed_now = set() with compat.peer._stub_gateway(tool_script=tool_script) as url: original_url_parser = provider_config._parse_https_url monkeypatch.setattr( @@ -863,7 +1279,7 @@ def tool_script(request): for key, value in { "OCR_LLM_URL": url, "OCR_LLM_MODEL": "synthetic-model", - "OCR_LLM_TOKEN": "synthetic-token", + "OCR_LLM_TOKEN": operator_token if diagnostics_only else "synthetic-token", "OCR_LLM_PROTOCOL": "openai", "OCR_REVIEW_EFFORT": "low", "OCR_TELEMETRY_ENABLED": "false", @@ -916,23 +1332,56 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): payload = json.loads(result.read_text()) if incremental: assert "toolkit_incremental" in payload, captured.err + if diagnostics_only: + assert "Incremental baseline: 17 groups, 0 qualified." in captured.err + assert ( + "Unqualified groups by reason: search_tool 16, unsupported_tool 1." + in captured.err + ) + assert all( + value not in captured.err + for value in ( + operator_token, + "private_synthetic_probe", + "unregistered_review_tool", + ) + ) return payload, report.read_text() diagram_on = diagram - baseline, baseline_report = run("baseline", first, analysis=True) + include_analysis = not (diagnostics_only or mixed or advanced) + baseline, baseline_report = run("baseline", first, analysis=include_analysis) diagram_on = False assert seen == Counter(dict.fromkeys(paths, 1)) assert baseline["toolkit_incremental"]["reused_count"] == 0 - assert ( - "A change diagram requires a full review." - if diagram - else "Behavior/Impact Analysis requires a full review." - ) in baseline_report - assert "toolkit_analysis" in baseline + if include_analysis: + assert ( + "A change diagram requires a full review." + if diagram + else "Behavior/Impact Analysis requires a full review." + ) in baseline_report + assert "toolkit_analysis" in baseline baseline_path = cache_path_for(Path(environment["HOME"]), root) cache = read_cache(baseline_path) assert cache is not None and cache.review_range.head == first assert not (root / ".review-context" / "incremental.json").exists() + if diagnostics_only: + assert cache.baseline_groups is not None + assert ( + cache.baseline_groups.payload() + == baseline["toolkit_incremental"]["baseline_groups"] + ) + assert not any(file.scope for file in cache.files.values()) + assert ( + "Unqualified groups by reason: search_tool 16, unsupported_tool 1." + in baseline_report + ) + private_state = baseline_path.read_text() + assert all( + value not in private_state + baseline_report + for value in (operator_token, "private_synthetic_probe", "unregistered_review_tool") + ) + return if diagram: assert confirmed_diagram == {diagram_owner} assert baseline["tool_calls"]["by_tool"][DIAGRAM_TOOL_NAME] == 1 @@ -941,13 +1390,26 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): assert all(cache.files[path].scope is not None for path in paths[1:]) if source_reads: assert confirmed_reads == set(direct_targets) - assert confirmed_negative_search == {broad} + assert confirmed_search == {broad} assert baseline["tool_calls"]["by_tool"]["code_search"] == 1 - assert cache.files[broad].scope is None - assert "missing_synthetic_symbol" not in baseline_path.read_text() + scope = cache.files[broad].scope + assert scope is not None and {item.tool for item in scope.replays} == {"code_search"} + assert "No matches found" not in baseline_path.read_text() + assert search_text not in baseline_report for source, target in direct_targets.items(): scope = cache.files[source].scope assert scope is not None and scope.head_paths == (dependency_path(target),) + if advanced: + assert cache.baseline_groups is not None + assert not cache.baseline_groups.reasons, (cache.baseline_groups, baseline_report) + for path, (tool, _) in advanced_calls.items(): + scope = cache.files[path].scope + assert scope is not None + if tool == "file_read": + assert scope.head_paths == (dependency_path(paths[11]),) + else: + assert {item.tool for item in scope.replays} == {tool} + assert len(scope.replays) == (2 if path == evidence_path else 1) old_run = baseline["manifest"]["run_id"] changed_now.update(paths[1:3] if diagram else paths[:2]) corrupted_path = paths[-1] @@ -957,8 +1419,8 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): corrupted_file, findings=({**corrupted_file.findings[0], "end_line": 9_999},) ) write_cache(baseline_path, cache) - edits = dict.fromkeys(changed_now, previous_text.replace("return 2 +", "return 3 +")) - if source_reads: + edits = {path: edited_texts[path] for path in changed_now} + if source_reads and not mixed: edits[paths[0]] = edits[paths[0]].replace( "return 3 + 19", "return 3 + 19 # missing_synthetic_symbol" ) @@ -972,7 +1434,9 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): with monkeypatch.context() as override: override.setenv("GIT_DIR", str(alternate)) narrowed, markdown = run("narrowed", second, expected_exit=1 if drop else 0) - expected_fresh = changed_now | ({direct_affected, broad} if source_reads else set()) + expected_fresh = changed_now | ( + {direct_affected, broad} if source_reads and not mixed else set() + ) if diagram: expected_fresh.add(diagram_owner) if ( @@ -1015,15 +1479,32 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): if diagram: assert "```mermaid" not in markdown return + if mixed: + assert carry["reused_count"] == 21 + groups = {cache.files[item["path"]].scope.members for item in carry["reused"]} + fresh_groups = len(narrowed["groups"]) + assert carry["baseline_groups"] == { + "total": fresh_groups + len(groups), + "qualified": len(groups), + "reasons": {"narrowed_context": fresh_groups}, + } + # The prior narrowed run never showed the first two groups all selected files. + # The unchanged Markdown link is also affected by the new JSON edit. + changed_now.add(paths[6]) + third = _edit(root, environment, {paths[6]: edited_texts[paths[6]]}) + followup, _ = run("linked", third) + assert seen == Counter(dict.fromkeys((*paths[:2], *paths[6:8], paths[9]), 1)) + assert followup["toolkit_incremental"]["reused_count"] == 18 + return + if advanced: + return # The project layer comes from the working directory and need not change the Git diff. rule = root / ".opencodereview" / "rule.json" rule.parent.mkdir(exist_ok=True) rule.write_text('{"rules":[{"path":"**/*.py","rule":"Review scalar assignments."}]}') changed_now.add(paths[2]) - third = _edit( - root, environment, {paths[2]: previous_text.replace("return 2 +", "return 3 +")} - ) + third = _edit(root, environment, {paths[2]: edited_texts[paths[2]]}) result, _ = run("invalidated", third) assert seen == Counter(dict.fromkeys(paths, 1)) assert result["toolkit_incremental"]["reused_count"] == 0 diff --git a/tests/test_local_incremental_replay.py b/tests/test_local_incremental_replay.py new file mode 100644 index 00000000..ad61701a --- /dev/null +++ b/tests/test_local_incremental_replay.py @@ -0,0 +1,539 @@ +"""Verify local dependency observations against immutable Git and evidence.""" + +import json +from collections import Counter + +import pytest + +from ocr_toolkit import local_incremental_replay +from ocr_toolkit.evidence import CoverageRecord, CoverageState, EvidenceStore, RefRole +from ocr_toolkit.evidence.actions import ACTION_RECEIPT_BUCKETS, EVIDENCE_ACTIONS +from ocr_toolkit.evidence.mcp import ( + COVERAGE_TOOL_NAME, + SEARCH_TOOL_NAME, + TOOL_NAME, + call_named_tool, + evidence_summary, +) +from ocr_toolkit.evidence.repository import GitRepositoryReader +from ocr_toolkit.local_incremental_dependencies import NativeDependencies, dependency_path +from ocr_toolkit.local_incremental_replay import ReplayVerifier, observed_replay +from ocr_toolkit.local_incremental_state import IncrementalError, ToolReplay +from ocr_toolkit.review_range import ReviewRange +from tests.test_evidence_repository import git + + +@pytest.fixture(scope="module") +def review_revisions(tmp_path_factory): + root = tmp_path_factory.mktemp("dependency-replay") + git(root, "init", "-q") + (root / "notes").mkdir() + (root / "notes" / "release.md").write_text("A steady detail\n") + (root / "notes" / "README.md").write_text("An independent document\n") + status = root / "status.md" + status.write_text("Original status\n") + git(root, "add", ".") + git(root, "commit", "-qm", "base") + base = git(root, "rev-parse", "HEAD") + status.write_text("Ready status\n") + git(root, "commit", "-qam", "reviewed") + reviewed = git(root, "rev-parse", "HEAD") + status.write_text("Active status\n") + git(root, "commit", "-qam", "follow-up") + return root, base, reviewed, git(root, "rev-parse", "HEAD") + + +@pytest.mark.parametrize( + ("tool", "arguments", "output", "remains_valid"), + ( + ( + "code_search", + {"search_text": "READY", "file_patterns": ["*.md"]}, + "File: status.md\nMatch lines: 1\n1|Ready status\n\n", + False, + ), + ( + "code_search", + {"search_text": "READY", "case_sensitive": True}, + "No matches found", + True, + ), + ( + "code_search", + {"search_text": "steady", "file_patterns": ["notes/*.md"]}, + "File: notes/release.md\nMatch lines: 1\n1|A steady detail\n\n", + True, + ), + ( + "code_search", + {"search_text": "Original", "side": "old"}, + "File: status.md\nMatch lines: 1\n1|Original status\n\n", + True, + ), + ("file_find", {"query_name": "readme"}, "notes/README.md", True), + ("file_find", {"query_name": r"notes\release"}, "notes/release.md", True), + ( + "file_find", + {"query_name": "README", "case_sensitive": True, "side": "old"}, + "notes/README.md", + True, + ), + ("file_find", {"query_name": "nonexistent"}, "// The file was not found", True), + ( + "file_read_diff", + {"path_array": ["status.md"]}, + "==== FILE: status.md ====\n" + "diff --git a/status.md b/status.md\n" + "--- a/status.md\n+++ b/status.md\n@@ -1 +1 @@\n-Original status\n" + "+Ready status\n\n", + False, + ), + ), +) +def test_replay_reproduces_immutable_native_output_and_detects_changes( + review_revisions, tool, arguments, output, remains_valid +): + root, base, reviewed, head = review_revisions + reader = GitRepositoryReader(root) + if arguments.get("side") == "old": + output = f"SIDE: old\nREVISION: {base}\n{output}" + observed = observed_replay(tool, arguments, output) + prior = ReplayVerifier(reader, ReviewRange(base, reviewed), None, lambda _: True) + current = ReplayVerifier(reader, ReviewRange(base, head), None, lambda _: True) + assert prior.verifies(observed) + assert current.verifies(observed) is remains_valid + + +def test_excess_search_matches_do_not_confirm_a_partial_observation(tmp_path): + git(tmp_path, "init", "-q") + (tmp_path / "status.md").write_text("ordinary text\n") + git(tmp_path, "add", ".") + git(tmp_path, "commit", "-qm", "base") + base = git(tmp_path, "rev-parse", "HEAD") + (tmp_path / "status.md").write_text("searchable line\n" * 101) + git(tmp_path, "commit", "-qam", "head") + head = git(tmp_path, "rev-parse", "HEAD") + verifier = ReplayVerifier( + GitRepositoryReader(tmp_path), ReviewRange(base, head), None, lambda _: True + ) + arguments = {"search_text": "searchable"} + partial_output = ( + "File: status.md\nMatch lines: 100\n" + + "".join(f"{line}|searchable line\n" for line in range(1, 101)) + + "\n" + ) + with pytest.raises(IncrementalError, match="complete match limit"): + verifier._execute("code_search", arguments) + assert not verifier.verifies(observed_replay("code_search", arguments, partial_output)) + + +def test_duplicate_diff_paths_are_counted_against_the_aggregate_budget( + review_revisions, monkeypatch +): + root, base, _, head = review_revisions + verifier = ReplayVerifier( + GitRepositoryReader(root), ReviewRange(base, head), None, lambda _: True + ) + one_path = {"path_array": ["status.md"]} + two_paths = {"path_array": ["status.md", "status.md"]} + rendered = verifier._execute("file_read_diff", one_path) + assert verifier._execute("file_read_diff", two_paths) == rendered * 2 + monkeypatch.setattr(local_incremental_replay, "_MAX_RESULT_BYTES", len(rendered.encode())) + assert verifier._execute("file_read_diff", one_path) == rendered + with pytest.raises(IncrementalError, match="native diff exceeds the replay result budget"): + verifier._execute("file_read_diff", two_paths) + + +def test_search_cannot_prove_absence_when_gitlinks_are_present(tmp_path): + git(tmp_path, "init", "-q") + (tmp_path / "status.md").write_text("ordinary text\n") + git(tmp_path, "add", ".") + git(tmp_path, "commit", "-qm", "base") + base = git(tmp_path, "rev-parse", "HEAD") + git(tmp_path, "update-index", "--add", "--cacheinfo", f"160000,{base},vendor") + git(tmp_path, "commit", "-qm", "add immutable pointer") + head = git(tmp_path, "rev-parse", "HEAD") + verifier = ReplayVerifier( + GitRepositoryReader(tmp_path), ReviewRange(base, head), None, lambda _: True + ) + arguments = {"search_text": "missing"} + with pytest.raises(IncrementalError, match="Git submodules"): + verifier._execute("code_search", arguments) + assert not verifier.verifies(observed_replay("code_search", arguments, "No matches found")) + assert not (tmp_path / "vendor").exists() + + +def test_replay_budget_counts_distinct_queries_and_keeps_verified_results(review_revisions): + root, base, _, head = review_revisions + verifier = ReplayVerifier( + GitRepositoryReader(root), ReviewRange(base, head), None, lambda _: True + ) + queries = [ + observed_replay( + "file_find", {"query_name": f"missing-{index}"}, "// The file was not found" + ) + for index in range(65) + ] + assert all(verifier.verifies(query) for query in queries[:-1]) + assert not verifier.verifies(queries[-1]) + assert verifier.verifies(queries[0]) + + +@pytest.mark.parametrize( + ("tool", "arguments"), + ( + ("tracker__echo", '{"text":"external"}'), + ("future_native_tool", "{}"), + ("code_search", '{"search_text":"[a-z]","use_perl_regexp":true}'), + ("code_search", '{"search_text":"text","case_sensitive":"true"}'), + ("code_search", '{"search_text":"text","file_patterns":["../outside"]}'), + ("code_search", '{"search_text":"text","search_text":"other"}'), + ("file_find", '{"query_name":"private word"}'), + ("file_read_diff", '{"path_array":["notes/release.md","status.md"]}'), + ("file_read_diff", '{"path_array":["../outside"]}'), + (TOOL_NAME, '{"action":"summary"}'), + ), +) +def test_replay_revalidates_saved_interactions_before_access( + review_revisions, tool, arguments, monkeypatch +): + def unexpected_call(*_args): + pytest.fail("unvalidated interaction reached replay dispatch") + + monkeypatch.setattr(ReplayVerifier, "_execute", unexpected_call) + root, base, _, head = review_revisions + verifier = ReplayVerifier( + GitRepositoryReader(root), + ReviewRange(base, head), + EvidenceStore(), + lambda value: value not in {"status.md", "private word"}, + ) + saved = ToolReplay(tool, arguments, "a" * 64) + assert not verifier.verifies(saved) + + +def test_evidence_replay_requires_complete_query_results_and_the_same_current_store( + review_revisions, +): + root, base, _, head = review_revisions + store = EvidenceStore() + coverage = CoverageRecord( + component="python", + domain="dependency.declared", + scope="requirements.txt", + state=CoverageState.COMPLETE, + reasons=("bounded-source-complete",), + ref=RefRole.HEAD, + commit_sha=head, + ) + assert store.add_coverage(coverage) + reader = GitRepositoryReader(root) + review_range = ReviewRange(base, head) + previous = ReplayVerifier(reader, review_range, store, lambda _: True) + empty = ReplayVerifier(reader, review_range, EvidenceStore(), lambda _: True) + missing = ReplayVerifier(reader, review_range, None, lambda _: True) + arguments = ( + (TOOL_NAME, {"action": "get", "id": coverage.id}), + (TOOL_NAME, {"action": "list", "kind": "repository.evidence_coverage"}), + (SEARCH_TOOL_NAME, {"query": "unrecorded dependency"}), + ( + COVERAGE_TOOL_NAME, + { + "kind": "dependency.declared", + "component": "python", + "path": "requirements.txt", + "ref": "head", + }, + ), + ) + for tool, args in arguments: + response = call_named_tool(store, tool, args)["content"][0]["text"] + replay = observed_replay(tool, args, json.dumps(json.loads(response), indent=2)) + assert previous.verifies(replay) + assert not missing.verifies(replay) + assert empty.verifies(replay) is (tool == SEARCH_TOOL_NAME) + incomplete = call_named_tool(EvidenceStore(), COVERAGE_TOOL_NAME, arguments[-1][1]) + with pytest.raises(IncrementalError, match="incomplete"): + observed_replay(COVERAGE_TOOL_NAME, arguments[-1][1], incomplete["content"][0]["text"]) + + +@pytest.mark.parametrize( + ("tool", "arguments", "response"), + ( + ("code_search", {"search_text": "synthetic"}, ""), + ("code_search", {"search_text": "synthetic"}, "x" * (256 * 1024 + 1)), + (TOOL_NAME, {"action": "get", "id": "expected"}, '{"record":{"id":"different"}}'), + (TOOL_NAME, {"action": "list"}, '{"records":[],"returned":0,"next_cursor":"pending"}'), + ( + SEARCH_TOOL_NAME, + {"query": "missing"}, + '{"schema_version":"ocr.evidence-search/v1","matches":[],"returned":0,' + '"total_matches":1,"truncated":true}', + ), + ( + SEARCH_TOOL_NAME, + {"query": "missing"}, + '{"schema_version":"ocr.evidence-search/v1","matches":[],"returned":false,' + '"total_matches":0,"truncated":false}', + ), + ), +) +def test_incomplete_or_unbound_observation_cannot_create_replay(tool, arguments, response): + with pytest.raises(IncrementalError, match=r"budget|incomplete"): + observed_replay(tool, arguments, response) + + +@pytest.mark.parametrize( + ("observation", "rejection"), + ( + ("new_read", None), + ("old_read", None), + ("past_end", None), + ("bad_read", "read_verification"), + ("truncated_read", "read_verification"), + ("path_denied", "read_verification"), + ("search", None), + ("changed_search", "search_tool"), + ("unexecuted_call", "unsupported_tool"), + ("unknown_call", "unsupported_tool"), + ("failed_tool", "failed_tool_call"), + ("model_failure", "llm_error"), + ("invalid_args", "invalid_arguments"), + ("foreign_comment", "comment_attribution"), + ("manifest_drift", "native_trace"), + ("missing_counter", "native_counters"), + ("counter_conflict", "evidence_counters"), + ("partition_conflict", "group_partition"), + ("no_main_request", "missing_main_request"), + ("summary_drift", "evidence_action"), + ), +) +def test_group_scope_uses_only_bound_and_reproducible_observations( + review_revisions, observation, rejection +): + root, base, _, head = review_revisions + store = EvidenceStore() + summary = evidence_summary(store) + dependencies = NativeDependencies(ReviewRange(base, head)) + run = "00000000-0000-4000-8000-000000000001" + manifest = {"run_id": run, "terminal_state": "complete"} + dependencies.observe({"type": "session_start", "sessionId": run}) + tool_counts = Counter() + path = "status.md" + + def observe(kind, **fields): + dependencies.observe({"type": kind, "taskType": "main_task", "filePath": path, **fields}) + + def tool_call(tool, args, result, *, ok=True): + tool_counts[tool] += 1 + observe("tool_call", tool_name=tool, arguments=json.dumps(args), result=result, ok=ok) + + observe( + "llm_request", taskType="plan_task" if observation == "no_main_request" else "main_task" + ) + tool_call(TOOL_NAME, {"action": "summary"}, json.dumps(summary)) + match observation: + case "new_read" | "old_read" | "bad_read" | "truncated_read" | "path_denied": + args = {"file_path": path, "start_line": 1, "end_line": 1} + status = "Changed" if observation == "bad_read" else "Active" + prefix = "" + if observation == "old_read": + args["side"] = "old" + prefix = f"SIDE: old\nREVISION: {base}\n" + status = "Original" + truncated = "true" if observation == "truncated_read" else "false" + tool_call( + "file_read", + args, + f"{prefix}File: status.md (Total lines: 2)\nIS_TRUNCATED: {truncated}\n" + f"LINE_RANGE: 1-1\n1|{status} status\n", + ) + case "past_end": + tool_call( + "file_read", + {"file_path": path, "start_line": 999, "end_line": 999}, + 'file "status.md" has only 2 lines, requested range 999-999', + ok=False, + ) + case "search" | "changed_search": + status = "Ready" if observation == "changed_search" else "Active" + tool_call( + "code_search", + {"search_text": "status"}, + f"File: status.md\nMatch lines: 1\n1|{status} status\n\n", + ) + case "unexecuted_call": + observe("llm_response", tool_calls=[{"name": "future_native_tool"}]) + case "unknown_call": + tool_call("future_native_tool", {}, "Native returned an observation") + case "failed_tool": + tool_call("file_find", {"query_name": "readme"}, "Tool failed", ok=False) + case "invalid_args": + observe("llm_response", tool_calls=[{"name": 1}]) + case "model_failure": + observe("llm_error") + case "foreign_comment": + tool_call("code_comment", {"comments": [{"path": "notes/release.md"}]}, "Accepted") + dependencies.observe({"type": "session_end", "run_manifest": manifest}) + if observation == "manifest_drift": + manifest = {**manifest, "terminal_state": "partial"} + if observation == "missing_counter": + tool_counts.clear() + actions = { + "attempted": dict.fromkeys(ACTION_RECEIPT_BUCKETS, 0) | {"summary": 1}, + "completed": dict.fromkeys(EVIDENCE_ACTIONS, 0) | {"summary": 1}, + } + if observation == "counter_conflict": + actions["attempted"]["summary"] = 2 + assessment = dependencies.scopes( + root, + { + "manifest": manifest, + "groups": [ + {"files": ["notes/release.md" if observation == "partition_conflict" else path]} + ], + "tool_calls": {"by_tool": dict(tool_counts), "total": tool_counts.total()}, + }, + {path}, + actions, + path_admitted=lambda _: observation != "path_denied", + argument_admitted=lambda _: True, + store=store, + file_summary={} if observation == "summary_drift" else summary, + ) + assert assessment.groups is not None + assert assessment.groups.payload() == { + "total": 1, + "qualified": 0 if rejection else 1, + "reasons": {rejection: 1} if rejection is not None else {}, + } + if rejection: + assert not assessment.scopes + else: + (scope,) = assessment.scopes.values() + assert scope.members == (path,) + expected_paths = (dependency_path(path),) if observation in {"new_read", "past_end"} else () + assert scope.head_paths == expected_paths + assert [replay.tool for replay in scope.replays] == ( + ["code_search"] if observation == "search" else [] + ) + + +def _assess_observed_groups(root, review_range, groups, warnings=()): + store = EvidenceStore() + summary = evidence_summary(store) + run = "00000000-0000-4000-8000-000000000001" + manifest = {"run_id": run, "terminal_state": "complete"} + deps = NativeDependencies(review_range) + deps.observe({"type": "session_start", "sessionId": run}) + for path, records in groups.items(): + common = {"taskType": "main_task", "filePath": path} + deps.observe({**common, "type": "llm_request"}) + deps.observe( + { + **common, + "type": "tool_call", + "tool_name": TOOL_NAME, + "arguments": '{"action":"summary"}', + "result": json.dumps(summary), + "ok": True, + } + ) + for record in records: + deps.observe({**common, **record}) + deps.observe({"type": "session_end", "run_manifest": manifest}) + return deps.scopes( + root, + { + "manifest": manifest, + "groups": [{"files": [path]} for path in groups], + "tool_calls": {"by_tool": dict(deps.tools), "total": deps.tools.total()}, + "warnings": list(warnings), + }, + set(groups), + { + "attempted": dict.fromkeys(ACTION_RECEIPT_BUCKETS, 0) | {"summary": len(groups)}, + "completed": dict.fromkeys(EVIDENCE_ACTIONS, 0) | {"summary": len(groups)}, + }, + path_admitted=lambda _: True, + argument_admitted=lambda _: True, + store=store, + file_summary=summary, + ) + + +@pytest.mark.parametrize("outcome", ("confirmed", "failed", "interrupted", "repaired")) +def test_unproven_comment_submission_disqualifies_every_group(review_revisions, outcome): + root, base, _, head = review_revisions + records = [{"type": "llm_response", "tool_calls": [{"name": "code_comment"}]}] + if outcome != "interrupted": + records.append( + { + "type": "tool_call", + "tool_name": "code_comment", + "arguments": '{"comments":[{"path":"status.md"}]}', + "result": "Accepted" if outcome != "failed" else "Native comment submission halted", + "ok": outcome != "failed", + } + ) + groups = {"status.md": records, "notes/release.md": []} + warnings = ({"type": "comment_args_repaired"},) if outcome == "repaired" else () + result = _assess_observed_groups(root, ReviewRange(base, head), groups, warnings) + assert result.groups is not None + if outcome == "confirmed": + assert result.scopes.keys() == groups.keys() + assert result.groups.qualified == 2 + else: + assert not result.scopes + assert result.groups.qualified == 0 + assert result.groups.reasons == (("comment_attribution", 2),) + + +def test_direct_read_leaves_missing_promisor_blob_unverified(tmp_path, monkeypatch): + remote = tmp_path / "promisor" + remote.mkdir() + git(remote, "init", "-q") + git(remote, "config", "uploadpack.allowFilter", "true") + git(remote, "config", "uploadpack.allowAnySHA1InWant", "true") + source = remote / "source.md" + source.write_text("Original\n") + git(remote, "add", ".") + git(remote, "commit", "-qm", "base") + base = git(remote, "rev-parse", "HEAD") + source.write_text("Changed\n") + git(remote, "commit", "-qam", "head") + head = git(remote, "rev-parse", "HEAD") + blob = git(remote, "rev-parse", f"{head}:source.md") + partial = tmp_path / "partial" + git( + tmp_path, + "clone", + "-q", + "--no-checkout", + "--filter=blob:none", + remote.as_uri(), + str(partial), + ) + missing = git(partial, "rev-list", "--all", "--objects", "--missing=print") + assert f"?{blob}" in missing.splitlines() + monkeypatch.setenv("GIT_ALLOW_PROTOCOL", "file") + monkeypatch.delenv("GIT_NO_LAZY_FETCH", raising=False) + result = _assess_observed_groups( + partial, + ReviewRange(base, head), + { + "source.md": [ + { + "type": "tool_call", + "tool_name": "file_read", + "arguments": '{"file_path":"source.md","start_line":1,"end_line":1}', + "result": "File: source.md (Total lines: 2)\nIS_TRUNCATED: false\nLINE_RANGE: 1-1\n1|Changed\n", + "ok": True, + } + ] + }, + ) + assert not result.scopes + assert result.groups is not None and result.groups.reasons == (("read_verification", 1),) + assert git(partial, "rev-list", "--all", "--objects", "--missing=print") == missing + assert GitRepositoryReader(partial).read_blob(head, "source.md") == b"Changed\n" diff --git a/tests/test_mcp_config_v2.py b/tests/test_mcp_config_v3.py similarity index 92% rename from tests/test_mcp_config_v2.py rename to tests/test_mcp_config_v3.py index 1efeee09..c8b852b6 100644 --- a/tests/test_mcp_config_v2.py +++ b/tests/test_mcp_config_v3.py @@ -1,4 +1,4 @@ -"""Shared composition checks for governed federation registry v2.""" +"""Shared composition checks for governed federation registry v3.""" from types import SimpleNamespace from urllib.parse import quote @@ -8,11 +8,20 @@ from ocr_toolkit import mcp_config REGISTRY = """{ - "version": 2, + "version": 3, "servers": { "docs": { "transport": {"type": "https", "url": "https://docs.example.invalid/mcp"}, - "tools": {"read": {"assurance": "review_read"}} + "tools": {"read": { + "assurance": "review_read", + "description": "Read operator-authorized documentation by exact identifier.", + "input_schema": { + "type": "object", + "properties": {"id": {"type": "string", "maxLength": 128}}, + "required": ["id"], + "additionalProperties": false + } + }} } } }""" diff --git a/tests/test_ocr_compat.py b/tests/test_ocr_compat.py index 7cdf3f03..d3521ec6 100644 --- a/tests/test_ocr_compat.py +++ b/tests/test_ocr_compat.py @@ -20,6 +20,7 @@ from typing import Any import pytest +import yaml from ocr_toolkit import preflight from tests.support import PROJECT_ROOT, patched_attr, patched_env @@ -909,6 +910,76 @@ def test_issue_body_uses_stable_marker_and_safe_release_changes() -> None: assert "/compare/v1.7.17...v1.7.18" in body assert "current tested baseline: `v1.7.16`" in body + run_url = "https://github.com/example/toolkit/actions/runs/42" + assert "dispatch **OCR compatibility**" not in module.delivery.render_workflow_issue( + evidence, run_url + ) + evidence["classification"] = "automatic-safe" + workflow_body = module.delivery.render_workflow_issue(evidence, run_url) + assert "`ocr-chain-assessment.json`" in workflow_body + assert ( + "`assess-complete-chain` job summary records the aggregate classification" in workflow_body + ) + assert "candidate jobs succeed, the complete observed chain is automatic-safe" in workflow_body + assert "and `qualification_only` is off" in workflow_body + assert workflow_body.index( + "still unseen above the current `monitoring_floor`" + ) < workflow_body.index("dispatch **OCR compatibility**") + assert "Set `through_tag` to the final release" in workflow_body + + +@pytest.mark.parametrize( + ("classification", "candidate_status", "qualification_only", "patch", "artifact"), + [ + ("automatic-safe", "success", "false", "success", "success"), + ("automatic-safe", "success", "true", "skipped", "success"), + ("incomplete", "failure", "false", "skipped", "success"), + ("", "failure", "false", "skipped", "failure"), + ], +) +def test_chain_summary_reports_patch_preparation_and_upload_independently( + tmp_path: Path, + classification: str, + candidate_status: str, + qualification_only: str, + patch: str, + artifact: str, +) -> None: + workflow = PROJECT_ROOT / ".github/workflows/ocr-compatibility.yml" + steps = yaml.safe_load(workflow.read_text())["jobs"]["aggregate"]["steps"] + summary = steps[-1] + assert summary["if"] == "${{ !cancelled() }}" + assert summary["env"]["CHAIN_OUTCOME"] == "${{ steps.chain.outcome }}" + chain = "success" if classification else "skipped" + assert summary["env"]["CHAIN_CLASSIFICATION"] == "${{ steps.chain.outputs.classification }}" + assert summary["env"]["PATCH_OUTCOME"] == "${{ steps.patch.outcome }}" + assert summary["env"]["ARTIFACT_OUTCOME"] == "${{ steps.upload_chain.outcome }}" + output = tmp_path / "summary.md" + subprocess.run( + ["bash", "-eu", "-c", summary["run"]], + env={ + **os.environ, + "GITHUB_STEP_SUMMARY": str(output), + "CHAIN_CLASSIFICATION": classification, + "CHAIN_OUTCOME": chain, + "CANDIDATE_OUTCOME": candidate_status, + "QUALIFICATION_ONLY": qualification_only, + "PATCH_OUTCOME": patch, + "ARTIFACT_OUTCOME": artifact, + }, + cwd=tmp_path, + check=True, + timeout=10, + ) + assert output.read_text().splitlines()[-6:] == [ + f"- Chain assessment: `{chain}`", + f"- Aggregate classification: `{classification or 'unavailable'}`", + f"- Candidate jobs: `{candidate_status}`", + f"- Qualification only: `{qualification_only}`", + f"- Patch generation: `{patch}`", + f"- Chain artifact upload: `{artifact}`", + ] + def test_failed_qualification_status_is_closed_and_consistent() -> None: """Public failure status accepts only reviewed enum values and exact keys.""" @@ -1201,7 +1272,13 @@ def request( assert calls[0][1] == "PATCH" assert calls[0][2] is not None assert calls[0][2]["state"] == "open" - assert "fix: synthetic parser correction" in calls[0][2]["body"] + body = calls[0][2]["body"] + assert "fix: synthetic parser correction" in body + assert "`ocr-compatibility-chain`" in body + assert "`ocr-chain-update.patch`" in body + assert "dispatch **OCR compatibility** from `main`" in body + assert "Leave `tag` and `after_tag` empty" in body + assert "update bot credential" not in body def test_failed_qualification_upsert_updates_the_canonical_issue() -> None: diff --git a/tests/test_ocr_qualification_recovery.py b/tests/test_ocr_qualification_recovery.py index 5189c479..49cef17f 100644 --- a/tests/test_ocr_qualification_recovery.py +++ b/tests/test_ocr_qualification_recovery.py @@ -125,7 +125,8 @@ def test_fresh_unsupported_reuse_conflicts_only_with_the_same_platform( module = load_script() manifest = module.core.load_json(module.settings.DEFAULT_MANIFEST) root = module.settings.ROOT - version = manifest["recommended_version"] + # This frozen release keeps both platform proofs in its local supplement. + version = "1.14.5" entry = next(item for item in manifest["releases"] if item["version"] == version) evidence = module.core.load_json(root / entry["evidence"]) observations = evidence["contracts"]["observations"] diff --git a/tests/test_ocr_result_contract.py b/tests/test_ocr_result_contract.py index eaa18a8c..056bf064 100644 --- a/tests/test_ocr_result_contract.py +++ b/tests/test_ocr_result_contract.py @@ -3,9 +3,15 @@ from __future__ import annotations import json +import sys from pathlib import Path from typing import Any +import pytest + +from ocr_toolkit.ocr_result import TOOLKIT_RESULT_KEY, OcrResultMalformed, load_ocr_result +from tests.test_posting_approval import publishable_receipt_current + FIXTURE_DIR = Path(__file__).parent / "fixtures" / "ocr-1.8.0" SEVERITIES = {"critical", "high", "medium", "low"} CATEGORIES = { @@ -62,3 +68,59 @@ def test_finding_metadata_uses_the_upstream_closed_sets() -> None: comments = load_fixture("findings.json")["comments"] assert {item["severity"] for item in comments} <= SEVERITIES assert {item["category"] for item in comments} <= CATEGORIES + + +@pytest.mark.parametrize("field", ("comments", "selected", "toolkit_analysis")) +@pytest.mark.parametrize("replacement_count", (0, 1)) +def test_result_readback_rejects_ambiguous_keys_at_any_depth( + tmp_path: Path, field: str, replacement_count: int +) -> None: + """Reject ambiguous required keys, including the root key of optional Analysis.""" + + receipt = publishable_receipt_current() + receipt["dlp"]["enabled"] = False + receipt["publication"]["state"] = "disabled" + coverage = {"selected": [{"item_id": "record", "path": "src/app.py"}]} + payload = { + TOOLKIT_RESULT_KEY: receipt, + "status": "complete", + "comments": [{"path": "src/app.py", "content": "Handle the empty input."}], + "manifest": {"coverage": coverage}, + } + if field == "toolkit_analysis": + receipt["analysis_hmac_sha256"] = "a" * 64 + payload[field] = {"status": "unavailable"} + result = tmp_path / "result.json" + result.write_text(json.dumps(payload), encoding="utf-8") + assert load_ocr_result(result) == payload + + container = coverage if field == "selected" else payload + distinct_key = field[0] + "\u200b" + field[1:] + container[distinct_key] = [{}] * replacement_count + result.write_text(json.dumps(payload), encoding="utf-8") + with pytest.raises(OcrResultMalformed, match="keys collide during redaction"): + load_ocr_result(result) + + +def test_result_readback_omits_analysis_at_redaction_recursion_limit(tmp_path: Path) -> None: + """Keep the primary review when the decoded Analysis exceeds Python's call depth.""" + + receipt = publishable_receipt_current() + receipt["analysis_hmac_sha256"] = "a" * 64 + expected = {TOOLKIT_RESULT_KEY: receipt, "status": "complete", "comments": []} + recursion_limit = 200 + nested: object = None + for _ in range(recursion_limit): + nested = [nested] + result = tmp_path / "result.json" + result.write_text( + json.dumps({**expected, "toolkit_analysis": {"usage": nested}}), encoding="utf-8" + ) + + previous_limit = sys.getrecursionlimit() + try: + sys.setrecursionlimit(recursion_limit) + loaded = load_ocr_result(result) + finally: + sys.setrecursionlimit(previous_limit) + assert loaded == expected diff --git a/tests/test_operations_docs.py b/tests/test_operations_docs.py index 632b6c72..27d43726 100644 --- a/tests/test_operations_docs.py +++ b/tests/test_operations_docs.py @@ -396,7 +396,7 @@ def test_canonical_decision_flow_has_stable_palette_and_runtime_boundaries() -> "not a local-mode exception", "not an automatic-approval feature", "publication owns review-signal delivery", - "receipt v13", + "ordinary receipt", "OCR_REVIEW_PROGRESS", "Blocking pipe or unavailable", "Review continues unchanged", @@ -580,7 +580,7 @@ def test_context_receipt_and_mcp_profile_contracts_are_public() -> None: assert "`metadata`" in document assert "`enriched`" in document assert 'OCR_REVIEW_CONTEXT_MODE: "off"' in example - assert "receipt v13" in configuration + assert "ordinary receipt" in configuration assert "v1-v8 results remain unsupported" in configuration assert "v1-v8 remains unsupported" in operations assert "complete `metadata` context" in operations.lower() @@ -612,7 +612,7 @@ def test_builtin_search_coverage_and_receipt_v11_boundaries_are_public() -> None "absence_authoritative=true", "Stop once the required evidence is sufficient", "action receipt v3", - "Receipt v13", + "The ordinary receipt", ): assert phrase in configuration assert "DLP-admitted store" in security @@ -648,7 +648,7 @@ def test_production_bot_modes_and_current_contract_are_public() -> None: "forge_discussions", "remediation_threads", "CI outcomes select exact job names", - "external acquisition is now governed by operator registry v2", + "external acquisition is now governed by operator registry", "required: false", "zero selected records is complete", ): @@ -727,7 +727,7 @@ def test_unprotected_target_contract_is_complete_and_fail_closed() -> None: assert "required" in document assert "unprotected" in document for document in (configuration, gitlab, security, bounded): - assert "receipt v13" in document + assert "receipt" in document.lower() and "comment-only" in document.lower() for phrase in ( "Explicit empty strings", "context `off` or bounded `metadata`", @@ -893,10 +893,9 @@ def test_ocr_compatibility_workflow_is_bounded_and_protected() -> None: assert 'SECURITY_DOC = ROOT / "docs" / "security.md"' not in qualifier assert "public version references" not in policy assert "MAX_QUALIFICATION_CHAIN = 10" in settings - assert "OCR_UPDATE_BOT_TOKEN" in workflow - assert "gh auth setup-git" in workflow - assert "git switch -C" in workflow - assert "git push --force-with-lease" in workflow + assert "OCR_UPDATE_BOT_TOKEN" not in workflow + assert "gh pr create" not in workflow + assert "git push" not in workflow assert workflow.count("issues: write") == 1 assert "continue-on-error: true" in workflow qualify_job = workflow.split(" qualify:\n", 1)[1].split(" aggregate:\n", 1)[0] @@ -909,6 +908,12 @@ def test_ocr_compatibility_workflow_is_bounded_and_protected() -> None: ) assert "PYTHONPATH=src .venv/bin/python scripts/ocr_compat.py qualify" in qualify_job config = yaml.safe_load(workflow) + reject_ref = config["jobs"]["reject-ref"] + assert reject_ref["if"] == ( + "github.event_name == 'workflow_dispatch' && github.ref != 'refs/heads/main'" + ) + assert reject_ref["permissions"] == {} + assert "Run OCR compatibility from the main branch." in reject_ref["steps"][0]["run"] for name in ("discover", "qualify"): permissions = config["jobs"][name].get("permissions", config["permissions"]) assert permissions == "read-all" or ( @@ -920,7 +925,7 @@ def test_ocr_compatibility_workflow_is_bounded_and_protected() -> None: assert "issues: write" in aggregate and "--issue-repository" in aggregate assert "--status-output /tmp/ocr-compat/status.json" in workflow assert "/tmp/ocr-compat/incompatibility.json" in qualify_job - assert workflow.count("github.ref == 'refs/heads/main' && !inputs.qualification_only") == 2 + assert workflow.count("github.ref == 'refs/heads/main' && !inputs.qualification_only") == 1 assert "if: ${{ always() && !cancelled() }}" in workflow assert "if: steps.qualify.outcome == 'failure'" in workflow assert "run: exit 1" in workflow diff --git a/tests/test_posting_approval.py b/tests/test_posting_approval.py index 8665bfc8..6dd5ac80 100644 --- a/tests/test_posting_approval.py +++ b/tests/test_posting_approval.py @@ -5,6 +5,8 @@ import io import unittest from contextlib import redirect_stderr +from copy import deepcopy +from dataclasses import replace from typing import Any import pytest @@ -21,7 +23,7 @@ ) from ocr_toolkit.posting.payloads import build_marked_note_body from ocr_toolkit.posting.snapshot import BotCommentRefs -from ocr_toolkit.result_contract import ReviewOutcome +from ocr_toolkit.result_contract import EXCLUSION_REASONS, ReviewOutcome from ocr_toolkit.review_receipt import receipt_review_identity, validated_review_identity from tests.support import cleared_env, gitlab_config, native_range_input, patched_attr, patched_env from tests.test_review_receipt_v13 import CURRENT_RANGE, _receipt_v13 @@ -159,13 +161,33 @@ def receipt_v8( } -def publishable_receipt_current(*, target_protection: str = "protected") -> dict[str, Any]: - """Use a current exact-boundary receipt for result-driven posting tests.""" +def publishable_receipt_current( + *, + target_protection: str = "protected", + protection_mode: str = "auto", + selected: int = 1, + **kwargs: Any, +) -> dict[str, Any]: + """Build a current receipt for unit tests using synthetic Git identities.""" - return _receipt_v13( + receipt = _receipt_v13( target_protection=target_protection, - protection_mode="unprotected" if target_protection == "unprotected" else "auto", + protection_mode=protection_mode, + **kwargs, + ) + receipt.update( + schema_version=ocr_result.TOOLKIT_RESULT_SCHEMA_VERSION, + review_coverage={ + "schema_version": "ocr.review-coverage/v1", + "state": "complete", + "changed": selected, + "selected": selected, + "excluded": 0, + "exclusion_reasons": dict.fromkeys(EXCLUSION_REASONS, 0), + "selection_sha256": "a" * 64, + }, ) + return receipt def execute_current_approval( @@ -232,6 +254,51 @@ def test_disabled_dlp_receipt_is_valid_and_blocks_automatic_approval() -> None: assert not approval.toolkit_receipt_is_valid(inconsistent) +def test_filtered_receipts_keep_versioned_coverage_and_private_projection_contracts() -> None: + counts = dict.fromkeys(("forbidden", "invalid_text", "laundering", "limit", "pii", "secret"), 0) + publication = { + "schema": "ocr.publication/v2", + "state": "publication-filtered", + "reason_counts": {**counts, "pii": 1}, + "private_sanitization": {"fields": 0, "reason_counts": counts}, + "retained": {"comments": 1, "warnings": 0}, + "omitted": {"comments": 1, "warnings": 0, "fields": 0}, + "original": { + "outcome": "clean", + "selected": 1, + "completed": 1, + "reused": 0, + "failed": 0, + "waived": 0, + }, + } + historical = _receipt_v13() + historical["publication"] = deepcopy(publication) + assert approval.toolkit_receipt_is_valid(historical) + historical["publication"]["original"]["excluded"] = 0 + assert not approval.toolkit_receipt_is_valid(historical) + + receipt = publishable_receipt_current() + receipt["publication"] = publication + assert not approval.toolkit_receipt_is_valid(receipt) + publication["original"]["excluded"] = 0 + assert approval.toolkit_receipt_is_valid(receipt) + publication["original"].update(selected=2, completed=2) + assert not approval.toolkit_receipt_is_valid(receipt) + publication["original"].update(selected=1, completed=1, excluded=1) + assert not approval.toolkit_receipt_is_valid(receipt) + + publication["original"]["excluded"] = 0 + publication["reason_counts"] = counts + publication["private_sanitization"] = {"fields": 1, "reason_counts": {**counts, "pii": 1}} + assert not approval.toolkit_receipt_is_valid(receipt) + publication["omitted"]["comments"] = 0 + assert approval.toolkit_receipt_is_valid(receipt) + assert not approval.evaluate_approval_policy( + settings.BooleanSetting(True), complete_outcome(), [], [], 0, receipt + ).eligible + + def test_unprotected_receipt_never_reaches_approval_mutation_path() -> None: receipt = receipt_v8(target_protection="unprotected") eligibility = approval.evaluate_approval_policy( @@ -314,14 +381,14 @@ def eligibility( comments or [], warnings or [], omitted, - receipt_v8(), + publishable_receipt_current(), ) def enriched_receipt(*, mutable: bool = False, required_degraded: bool = False) -> dict[str, Any]: - """Return one v8 local-store-only enrichment receipt.""" + """Return one current local-store-only enrichment receipt.""" - receipt = receipt_v8() + receipt = publishable_receipt_current() receipt["context"] = { "mode": "enriched", "state": "degraded" if required_degraded else "complete", @@ -416,6 +483,16 @@ def test_incomplete_warning_omitted_budget_waived_and_legacy_block(self) -> None with self.subTest(name=name): self.assertFalse(decision.eligible) + def test_native_reuse_without_a_bound_prior_gitlab_review_cannot_approve(self) -> None: + outcome = replace(complete_outcome(), completed_count=0, reused_count=1) + + decision = eligibility(outcome=outcome) + + self.assertFalse(decision.eligible) + self.assertEqual( + decision.result.reason, "coverage reused items without a verified prior GitLab review" + ) + def test_degraded_context_receipt_blocks_without_exposing_provider_text(self) -> None: decision = approval.evaluate_approval_policy( settings.BooleanSetting(True), @@ -507,6 +584,8 @@ def test_filtered_receipt_rejects_outcomes_that_contradict_coverage(self) -> Non self.assertEqual(approval.publication_dlp_state(publication), "publication-filtered") invalid_originals = ( + {"outcome": [], "selected": 0, "completed": 0, "failed": 0}, + {"outcome": {}, "selected": 0, "completed": 0, "failed": 0}, {"outcome": "partial", "selected": 0, "completed": 0, "failed": 0}, {"outcome": "clean", "selected": 0, "completed": 0, "failed": 0}, {"outcome": "warning", "selected": 0, "completed": 0, "failed": 0}, @@ -529,18 +608,21 @@ def test_filtered_receipt_rejects_outcomes_that_contradict_coverage(self) -> Non self.assertIsNone(approval.publication_dlp_state(candidate)) def test_private_only_sanitization_keeps_existing_approval_gates(self) -> None: - receipt = receipt_v8() + receipt = publishable_receipt_current() receipt["publication"] = { + "schema": "ocr.publication/v2", "state": "private-sanitized", - "reason_counts": { - "forbidden": 0, - "invalid_text": 0, - "laundering": 0, - "limit": 0, - "pii": 1, - "secret": 0, + "private_sanitization": { + "fields": 1, + "reason_counts": { + "forbidden": 0, + "invalid_text": 0, + "laundering": 0, + "limit": 0, + "pii": 1, + "secret": 0, + }, }, - "sanitized_fields": 1, } decision = approval.evaluate_approval_policy( @@ -550,7 +632,7 @@ def test_private_only_sanitization_keeps_existing_approval_gates(self) -> None: self.assertTrue(decision.eligible) def test_evidence_action_attribution_does_not_change_approval_eligibility(self) -> None: - receipt = receipt_v8() + receipt = publishable_receipt_current() decision = approval.evaluate_approval_policy( settings.BooleanSetting(True), complete_outcome(), [], [], 0, receipt ) @@ -564,7 +646,7 @@ def test_evidence_action_attribution_does_not_change_approval_eligibility(self) self.assertIn("receipt is missing or invalid", decision.result.reason) def test_failed_attempts_do_not_authorize_successful_evidence_or_approval(self) -> None: - receipt = receipt_v8() + receipt = publishable_receipt_current() actions = receipt["evidence"]["actions"] actions["attempted"]["get"] = 1 receipt["evidence"]["calls"] = 2 @@ -584,16 +666,23 @@ def test_failed_attempts_do_not_authorize_successful_evidence_or_approval(self) self.assertIn("receipt is missing or invalid", decision.result.reason) def test_complete_metadata_and_external_mcp_have_independent_approval_effects(self) -> None: + metadata = publishable_receipt_current() + metadata["context"] = receipt_v8(context_state="complete")["context"] complete_metadata = approval.evaluate_approval_policy( settings.BooleanSetting(True), complete_outcome(), [], [], 0, - receipt_v8(context_state="complete", author_id=41), + metadata, ) external = approval.evaluate_approval_policy( - settings.BooleanSetting(True), complete_outcome(), [], [], 0, receipt_v8(external=True) + settings.BooleanSetting(True), + complete_outcome(), + [], + [], + 0, + publishable_receipt_current(external=True), ) self.assertTrue(complete_metadata.eligible) @@ -1125,6 +1214,10 @@ class ApprovalWorkflowTests(unittest.TestCase): SHA = "a" * 40 RUN_ID = "b" * 32 + def setUp(self) -> None: + # These rendering tests use synthetic SHAs. Real Git coverage is tested separately. + self.enterContext(patched_attr(workflow, "verified_review_coverage", lambda *_args: None)) + def tearDown(self) -> None: settings.post_mode.cache_clear() @@ -1247,7 +1340,11 @@ def _assert_unprotected_limitation_is_adjacent_once( summary: dict[str, bool], comments: list[dict[str, Any]], ) -> None: - receipt = publishable_receipt_current(target_protection="unprotected") + receipt = publishable_receipt_current( + target_protection="unprotected", + protection_mode="unprotected", + selected=0 if status == "skipped" else 2 if manifest_state == "partial" else 1, + ) if status in {"skipped", "failed"}: receipt["evidence"] = { "mandatory": False, @@ -1358,7 +1455,9 @@ def test_complete_filtered_review_keeps_coverage_and_activity_dimensions_separat ) -> None: """Render scenario B without inventing partial coverage or a failed item.""" - receipt = publishable_receipt_current(target_protection="unprotected") + receipt = publishable_receipt_current( + target_protection="unprotected", protection_mode="unprotected", selected=5 + ) receipt["publication"] = { "schema": "ocr.publication/v2", "state": "publication-filtered", @@ -1390,6 +1489,7 @@ def test_complete_filtered_review_keeps_coverage_and_activity_dimensions_separat "reused": 0, "failed": 0, "waived": 0, + "excluded": 0, }, } notes: list[tuple[str, str]] = [] diff --git a/tests/test_posting_helpers.py b/tests/test_posting_helpers.py index 444f5b6e..67233304 100644 --- a/tests/test_posting_helpers.py +++ b/tests/test_posting_helpers.py @@ -67,8 +67,8 @@ patched_env, review_receipt_v8, ) +from tests.test_posting_approval import publishable_receipt_current from tests.test_review_receipt_v11 import _receipt_v11 -from tests.test_review_receipt_v13 import _receipt_v13 def failed_receipt_v11() -> dict[str, Any]: @@ -307,18 +307,100 @@ def test_fingerprint_survives_line_shifts(self) -> None: ) def test_partial_publication_reuses_previous_fingerprint_without_duplicate(self) -> None: - previous = snapshot.BotCommentRefs() comments = [ - {"path": "src/a.py", "line": 7, "content": "same finding"}, + {"path": "src/a.py", "line": 7, "content": "same finding", "severity": "low"}, {"path": "src/b.py", "line": 9, "content": "new finding"}, ] markers.annotate_comment_fingerprints(comments) - previous.published_fingerprints.add(comments[0]["_ocr_fingerprint"]) + for badge_mode in ("plain", "shields"): + finding = comments[0] + body = gitlab.build_marked_note_body( + posting_formatting.format_inline_comment(finding, badge_mode=badge_mode), + fingerprint=finding["_ocr_fingerprint"], + write_id="d" * 32, + ) + previous = snapshot.BotCommentRefs() + snapshot.process_discussion_for_refs( + gitlab_config(), previous, "thread", [{"id": 9, "author": {"id": 7}, "body": body}] + ) - kept, carried = snapshot.filter_previously_published_comments(comments, previous) + kept, carried = snapshot.filter_previously_published_comments(comments, previous) + self.assertEqual(carried, 1) + self.assertEqual(kept, [comments[1]]) - self.assertEqual(carried, 1) - self.assertEqual(kept, [comments[1]]) + raised = {**finding, "severity": "high"} + self.assertEqual( + markers.comment_fingerprint(raised), markers.comment_fingerprint(finding) + ) + self.assertEqual( + snapshot.filter_previously_published_comments([raised], previous), + ([raised], 0), + ) + + def test_partial_publication_carries_forward_canonical_category_only_findings(self) -> None: + finding = {"path": "src/a.py", "line": 7, "content": "same finding", "category": "style"} + fingerprint = markers.comment_fingerprint(finding) + raised = {**finding, "severity": "high"} + for badge_mode in ("plain", "shields"): + with self.subTest(badge_mode=badge_mode): + rendered = posting_formatting.format_inline_comment(finding, badge_mode=badge_mode) + body = gitlab.build_marked_note_body(rendered, fingerprint=fingerprint) + previous = snapshot.BotCommentRefs() + snapshot.process_discussion_for_refs( + gitlab_config(), + previous, + "thread", + [{"id": 9, "author": {"id": 7}, "body": body}], + ) + self.assertEqual( + snapshot.filter_previously_published_comments([finding], previous), ([], 1) + ) + self.assertEqual( + snapshot.filter_previously_published_comments([raised], previous), ([raised], 0) + ) + + def test_partial_publication_cannot_carry_escalation_across_occurrences(self) -> None: + finding = {"path": "src/a.py", "content": "same finding", "existing_code": "return 1"} + prior = [ + {**finding, "line": 7, "severity": "high"}, + {**finding, "line": 9, "severity": "low"}, + ] + current = [ + {**finding, "line": 7, "severity": "low"}, + {**finding, "line": 9, "severity": "high"}, + ] + markers.annotate_comment_fingerprints(prior) + markers.annotate_comment_fingerprints(current) + previous = snapshot.BotCommentRefs( + published_finding_counts={ + (comment["_ocr_fingerprint"], comment["severity"]): 1 for comment in prior + } + ) + + assert markers.comment_fingerprint(prior[0]) == markers.comment_fingerprint(prior[1]) + assert prior[0]["_ocr_fingerprint"] != prior[1]["_ocr_fingerprint"] + assert snapshot.filter_previously_published_comments(current, previous) == (current, 0) + + def test_partial_publication_declines_carry_forward_when_first_anchor_moves(self) -> None: + old = { + "path": "src/a.py", + "line": 10, + "content": "same finding", + "existing_code": "return 1", + "category": "security", + } + fingerprint = markers.comment_fingerprint(old) + assert fingerprint is not None + previous = snapshot.BotCommentRefs(published_finding_counts={(fingerprint, ""): 1}) + current = [{**old, "line": 5}, dict(old)] + markers.annotate_comment_fingerprints(current) + assert current[0]["_ocr_fingerprint"] == fingerprint + assert current[1]["_ocr_fingerprint"] != fingerprint + + assert snapshot.filter_previously_published_comments(current, previous) == (current, 0) + assert snapshot.filter_previously_published_comments( + current[:1], previous, review_comments=current + ) == (current[:1], 0) def test_markers_are_parsed_only_from_owned_preamble(self) -> None: first = "a" * FINGERPRINT_LEN @@ -351,20 +433,18 @@ def test_markers_are_parsed_only_from_owned_preamble(self) -> None: ) ) - def test_partial_publication_consumes_one_legacy_marker_per_duplicate(self) -> None: + def test_partial_publication_carries_legacy_marker_for_unique_current_finding(self) -> None: comments = [ - {"path": "src/a.py", "line": 7, "content": "same finding"}, - {"path": "src/a.py", "line": 7, "content": "same finding"}, + {"path": "src/a.py", "line": 7, "content": "same finding", "severity": "medium"}, + {"path": "src/a.py", "line": 7, "content": "same finding", "severity": "medium"}, ] markers.annotate_comment_fingerprints(comments) legacy = markers.line_based_comment_fingerprint(comments[0]) self.assertIsNotNone(legacy) - previous = snapshot.BotCommentRefs(published_fingerprints={legacy or ""}) - - kept, carried = snapshot.filter_previously_published_comments(comments, previous) + previous = snapshot.BotCommentRefs(published_finding_counts={(legacy or "", "medium"): 1}) - self.assertEqual(carried, 1) - self.assertEqual(kept, [comments[1]]) + assert snapshot.filter_previously_published_comments(comments[:1], previous) == ([], 1) + assert snapshot.filter_previously_published_comments(comments, previous) == (comments, 0) def test_write_result_rejects_unknown_outcomes_and_malformed_write_ids(self) -> None: with self.assertRaises(ValueError): @@ -1001,7 +1081,7 @@ def test_diagnostic_uncertainty_does_not_replace_a_valid_review_with_schema_erro inline_bodies: list[str] = [] notes: list[tuple[str, str]] = [] - receipt = _receipt_v13() + receipt = publishable_receipt_current() receipt["tool_execution"] = {"state": "invalid", "failed": None} result_data = { "status": "complete", @@ -1066,6 +1146,7 @@ def capture_note( lambda _config: snapshot.BotCommentRefs(), ), patched_attr(workflow, "validate_review_freshness", lambda *_args: None), + patched_attr(workflow, "verified_review_coverage", lambda *_args: None), patched_attr(workflow, "post_review_discussion", capture_discussion), patched_attr(workflow, "post_review_note_bounded", capture_note), patched_attr(workflow, "finalize_posting", lambda *_args: True), @@ -1469,11 +1550,16 @@ def test_filtered_publication_posts_safe_new_findings_and_preserves_previous(sel notes: list[str] = [] cleanup_calls: list[str] = [] previous = snapshot.BotCommentRefs() - old = {"path": "src/old.py", "line": 7, "content": "Existing safe finding."} + old = { + "path": "src/old.py", + "line": 7, + "content": "Existing safe finding.", + "category": "security", + } new = {"path": "src/new.py", "line": 9, "content": "New safe finding."} old_fingerprint = markers.comment_fingerprint(old) self.assertIsNotNone(old_fingerprint) - previous.published_fingerprints.add(old_fingerprint or "") + previous.published_finding_counts[old_fingerprint or "", ""] = 1 publication = { "state": "publication-filtered", "reason_counts": { @@ -1493,6 +1579,7 @@ def test_filtered_publication_posts_safe_new_findings_and_preserves_previous(sel "reused": 0, "failed": 0, "waived": 0, + "excluded": 0, }, } @@ -1508,6 +1595,7 @@ def capture_note(_config: Any, *args: Any) -> dict[str, int]: ), patched_attr(workflow, "collect_previous_bot_comment_refs", lambda _config: previous), patched_attr(workflow, "validate_review_freshness", lambda *_args: None), + patched_attr(workflow, "verified_review_coverage", lambda *_args: None), patched_attr(workflow, "get_diff_refs", lambda _config: None), patched_attr( workflow, @@ -1533,7 +1621,7 @@ def capture_note(_config: Any, *args: Any) -> dict[str, int]: "comments": [old, new], "warnings": [], "_ocr_toolkit": { - **_receipt_v13(), + **publishable_receipt_current(selected=3), "publication": { "schema": "ocr.publication/v2", **publication, @@ -1560,6 +1648,8 @@ def capture_note(_config: Any, *args: Any) -> dict[str, int]: self.assertNotIn("Existing safe finding.", rendered) self.assertIn("Publication filtering signal", rendered) self.assertIn('"carried_forward_comments":1', rendered) + self.assertIn("newly published OCR comments", rendered) + self.assertIn("retained findings outside this guide's security assessment", rendered) def test_present_invalid_receipt_never_reaches_normal_publication(self) -> None: notes: list[str] = [] @@ -4120,7 +4210,7 @@ def test_reviewer_guide_does_not_promote_neutral_injection_phrase(self) -> None: guide = posting_formatting.format_reviewer_guide(comments, omitted_count=0) self.assertEqual(comments, original) - self.assertIn("**Security signal:** 1 published OCR finding", guide) + self.assertIn("**Security signal:** 1 newly published OCR finding", guide) self.assertIn("Estimated effort to review: 2/5", guide) def test_security_signal_accepts_only_closed_injection_classes(self) -> None: @@ -5497,7 +5587,13 @@ def test_pre_run_snapshot_baseline_contains_all_valid_endpoint_identities(self) {"id": 30, "note": "human", "author_id": 8}, { "id": 31, - "note": build_marker(pending_fingerprint) + "\nbot", + "note": gitlab.build_marked_note_body( + posting_formatting.format_inline_comment( + {"content": "Pending synthetic finding", "severity": "low"}, + badge_mode="plain", + ), + fingerprint=pending_fingerprint, + ), "author_id": 7, }, ] @@ -5538,7 +5634,9 @@ def page(_config: Any, endpoint: str, **_kwargs: Any) -> list[Any]: self.assertEqual(refs.discussion_note_refs, []) self.assertEqual(refs.all_draft_note_ids, [30, 31]) self.assertEqual(refs.draft_note_ids, [31]) - self.assertNotIn(pending_fingerprint, refs.published_fingerprints) + self.assertFalse( + any(value == pending_fingerprint for value, _ in refs.published_finding_counts) + ) def test_rollback_collection_keeps_current_run_bot_notes_with_human_reply(self) -> None: refs = snapshot.BotCommentRefs() diff --git a/tests/test_posting_v11_flow.py b/tests/test_posting_v11_flow.py index 141d214d..86574b5f 100644 --- a/tests/test_posting_v11_flow.py +++ b/tests/test_posting_v11_flow.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +from copy import deepcopy from dataclasses import replace from pathlib import Path from typing import Any @@ -10,7 +11,7 @@ import pytest from ocr_toolkit.ocr_result import load_ocr_result -from ocr_toolkit.posting import formatting, freshness, gitlab, gitlab_approval, workflow +from ocr_toolkit.posting import formatting, freshness, gitlab, gitlab_approval, markers, workflow from ocr_toolkit.posting.approval import ( ApprovalEligibility, ApprovalResult, @@ -32,14 +33,27 @@ GitLabProviderError, ) from ocr_toolkit.result_contract import ReviewOutcome +from ocr_toolkit.review_coverage import parse_review_coverage from ocr_toolkit.review_receipt import ReceiptReviewIdentity, validated_review_identity from tests.support import gitlab_config, native_range_input, review_receipt_v8 +from tests.test_posting_approval import publishable_receipt_current from tests.test_review_receipt_v11 import _receipt_v11 from tests.test_review_receipt_v13 import CURRENT_RANGE, _receipt_v13 +@pytest.fixture(autouse=True) +def isolate_git_coverage(monkeypatch: pytest.MonkeyPatch): + """Isolate publication and provider sequencing from verification of synthetic SHAs.""" + + verifier = workflow.verified_review_coverage + monkeypatch.setattr(workflow, "verified_review_coverage", lambda *_args: None) + return verifier + + def _identity(*, unprotected: bool = False) -> ReceiptReviewIdentity: - receipt = _receipt_v13(target_protection="unprotected" if unprotected else "protected") + receipt = publishable_receipt_current( + target_protection="unprotected" if unprotected else "protected" + ) identity = validated_review_identity(receipt) assert identity is not None return identity @@ -83,7 +97,7 @@ def _result(kind: str, *, comments: bool = False) -> dict[str, Any]: "waived": [], }, }, - "_ocr_toolkit": _receipt_v13(), + "_ocr_toolkit": publishable_receipt_current(selected=len(selected)), } @@ -108,7 +122,7 @@ def _pre_execution_status(reason: str) -> PreExecutionStatus: (("clean", False), ("clean", True), ("partial", False), ("failed", False)), ) @pytest.mark.parametrize("drift", ("target_changed", "policy_changed", "diff_changed")) -def test_stale_v11_result_never_reaches_normal_or_failure_write( +def test_stale_result_never_reaches_normal_or_failure_write( kind: str, has_comments: bool, drift: str, monkeypatch: pytest.MonkeyPatch ) -> None: """Same-H target, policy, or diff drift preserves the previous review.""" @@ -143,7 +157,7 @@ def test_stale_v11_result_never_reaches_normal_or_failure_write( assert calls == [] -def test_invalid_schema_with_valid_v11_receipt_is_job_only( +def test_invalid_schema_with_valid_current_receipt_is_job_only( monkeypatch: pytest.MonkeyPatch, ) -> None: """A valid receipt cannot authorize notes for a malformed result body.""" @@ -325,14 +339,14 @@ def test_receiptless_ci_result_cannot_post_with_same_source_head( @pytest.mark.parametrize("native_model", ("openai/gpt-5.4", "different-run-model", None)) -def test_v11_findings_use_exact_receipt_diff_tuple_and_protected_anchor( +def test_findings_use_exact_receipt_diff_tuple_and_protected_anchor( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, native_model: str | None, ) -> None: """Inline positions use the reviewed B/start/H, even when B differs from T.""" - receipt = _receipt_v13(target_protection="unprotected") + receipt = publishable_receipt_current(target_protection="unprotected") identity = validated_review_identity(receipt) assert identity is not None observed_refs: list[dict[str, str]] = [] @@ -349,7 +363,7 @@ def test_v11_findings_use_exact_receipt_diff_tuple_and_protected_anchor( monkeypatch.setattr( workflow, "get_diff_refs", - lambda _config: pytest.fail("v11 must not choose a version by head SHA alone"), + lambda _config: pytest.fail("must not choose a version by head SHA alone"), ) def discussion(*_args: Any, **kwargs: Any) -> gitlab.GitLabWriteResult: @@ -395,15 +409,19 @@ def note(_config: Any, _title: str, body: str, _transaction: Any) -> dict[str, i assert identity.policy_branch not in notes[0] -@pytest.mark.parametrize("include_analysis", [False, True]) -def test_v11_no_findings_summary_uses_protected_anchor( +@pytest.mark.parametrize( + ("include_analysis", "colliding_analysis_keys"), + [(False, False), (True, False), (True, True)], +) +def test_no_findings_summary_uses_protected_anchor( monkeypatch: pytest.MonkeyPatch, include_analysis: bool, + colliding_analysis_keys: bool, tmp_path: Path, ) -> None: - """A clean fallback still explains target protection and immutable authority.""" + """Keep the clean summary and protected anchor when optional Analysis is ambiguous.""" - receipt = _receipt_v13(target_protection="unprotected") + receipt = publishable_receipt_current(target_protection="unprotected") notes: list[str] = [] monkeypatch.setattr(workflow, "parse_result_outcome", lambda _result: _outcome("clean")) monkeypatch.setattr( @@ -434,16 +452,19 @@ def note(_config: Any, _title: str, body: str, _transaction: Any) -> dict[str, i receipt["analysis_hmac_sha256"] = publication_digest( result["toolkit_analysis"], receipt["review"] ) + if colliding_analysis_keys: + result["toolkit_analysis"]["usage"] = {"input_tokens": 1, "input\u200b_tokens": 2} path = tmp_path / "review.json" path.write_text(json.dumps(result)) + loaded = load_ocr_result(path) + if colliding_analysis_keys: + assert "toolkit_analysis" not in loaded + assert workflow.post_results(gitlab_config(), loaded, include_analysis=include_analysis) == 0 + expected_analysis = include_analysis and not colliding_analysis_keys + assert ("The API key is required." in notes[0]) is expected_analysis assert ( - workflow.post_results( - gitlab_config(), load_ocr_result(path), include_analysis=include_analysis - ) - == 0 - ) - assert ("The API key is required." in notes[0]) is include_analysis - assert ("Behavior/Impact Analysis (partial)" in notes[0]) is include_analysis + "Behavior/Impact Analysis (partial)" in notes[0] + ) is expected_analysis assert len(notes) == 1 assert "protected policy anchor" in notes[0] assert receipt["review"]["policy_sha"] in notes[0] @@ -451,7 +472,7 @@ def note(_config: Any, _title: str, body: str, _transaction: Any) -> dict[str, i assert "limited, comment-only mode" not in notes[0] -def test_current_partial_v11_posts_summary_without_replacing_old_findings( +def test_current_partial_posts_summary_without_replacing_old_findings( monkeypatch: pytest.MonkeyPatch, ) -> None: """A current partial review can report coverage while keeping prior findings.""" @@ -483,6 +504,74 @@ def preserve(_config: Any, _previous: Any, outcome: ReviewOutcome, **_kwargs: An assert calls == ["summary", "finalize-partial"] +@pytest.mark.parametrize("reason", ("excluded", "reused", "waived")) +def test_unfiltered_partial_coverage_carries_forward_matching_findings( + monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest, reason: str +) -> None: + result = _result("clean", comments=True) + result["comments"][0]["severity"] = "low" + coverage = result["manifest"]["coverage"] + if reason == "excluded": + coverage["excluded"] = [ + {"item_id": "unreviewed", "path": "asset.bin", "exclude_reason": "binary"} + ] + receipt = result["_ocr_toolkit"]["review_coverage"] + receipt.update(state="partial", changed=2, excluded=1) + receipt["exclusion_reasons"]["binary"] = 1 + elif reason == "reused": + coverage["reused"] = coverage["completed"] + coverage["completed"] = [] + else: + waived = {"item_id": "unreviewed", "path": "waived.py"} + coverage["selected"].append(waived) + coverage["waived"] = [{**waived, "reason": "Synthetic waiver"}] + result["_ocr_toolkit"]["review_coverage"].update(changed=2, selected=2) + + fingerprint = markers.comment_fingerprint(result["comments"][0]) + assert fingerprint is not None + previous = BotCommentRefs( + published_finding_counts={(fingerprint, "low"): 1}, + plain_note_ids=[91, 92], + summary_plain_note_ids=[92], + discussions_to_resolve=["previous-thread"], + ) + summaries: list[str] = [] + deleted: list[int] = [] + monkeypatch.setenv("OCR_POST_MODE", "direct") + monkeypatch.setenv("OCR_AUTO_APPROVE", "true") + for setting in (workflow.post_mode, workflow.auto_approve): + setting.cache_clear() + request.addfinalizer(setting.cache_clear) + current_coverage = parse_review_coverage(result["_ocr_toolkit"]["review_coverage"]) + monkeypatch.setattr(workflow, "verified_review_coverage", lambda *_args: current_coverage) + monkeypatch.setattr(workflow, "validate_review_freshness", lambda *_args: None) + monkeypatch.setattr(workflow, "collect_previous_bot_comment_refs", lambda _config: previous) + monkeypatch.setattr(workflow, "finalize_posting", lambda *_args: True) + monkeypatch.setattr( + workflow, "post_review_discussion", lambda *_args, **_kwargs: pytest.fail("duplicate") + ) + monkeypatch.setattr(workflow, "execute_approval", lambda *_args: pytest.fail("approval")) + monkeypatch.setattr(workflow, "resolve_discussion", lambda *_args: pytest.fail("resolution")) + monkeypatch.setattr( + workflow, + "post_review_note_bounded", + lambda _config, _title, body, _txn: summaries.append(body) or {"id": 100}, + ) + monkeypatch.setattr( + workflow.gitlab_api, + "delete_plain_note", + lambda _config, note_id: deleted.append(note_id) or True, + ) + + assert workflow.post_results(gitlab_config(), result) == 0 + assert deleted == [92] and len(summaries) == 1 + assert "no new findings published from reviewed files" in summaries[0] + assert "1 matching previous finding retained" in summaries[0] + assert ("1 file not reviewed" in summaries[0]) is (reason != "reused") + assert "Automatic approval: `not eligible`" in summaries[0] + assert "Publication filtering signal" not in summaries[0] + + @pytest.mark.parametrize( ("code", "kind", "receipt", "failure_class", "expect_post"), [ @@ -521,7 +610,7 @@ def test_nonzero_result_routes_only_admitted_operational_partial( assert bool(calls) == expect_post -def test_current_failed_v11_is_job_only_after_freshness( +def test_current_failed_result_is_job_only_after_freshness( monkeypatch: pytest.MonkeyPatch, ) -> None: """Failed result status is bound to the live tuple and does not collect old notes.""" @@ -721,8 +810,8 @@ def test_unprotected_target_cannot_approve_even_if_eligibility_is_wrong( assert "unprotected" in result.result.reason -@pytest.mark.parametrize("receipt", (None, review_receipt_v8())) -def test_eligible_approval_requires_current_v11_identity_before_sync_or_write( +@pytest.mark.parametrize("receipt", (None, review_receipt_v8(), _receipt_v13())) +def test_eligible_approval_requires_current_identity_before_sync_or_write( receipt: dict[str, Any] | None, monkeypatch: pytest.MonkeyPatch ) -> None: """Legacy receipts and missing identity cannot bypass the adapter directly.""" @@ -730,12 +819,12 @@ def test_eligible_approval_requires_current_v11_identity_before_sync_or_write( monkeypatch.setattr( gitlab_approval, "wait_for_synchronized_approval_state", - lambda *_args, **_kwargs: pytest.fail("missing v11 identity must stop before sync"), + lambda *_args, **_kwargs: pytest.fail("missing current identity must stop before sync"), ) monkeypatch.setattr( gitlab, "approve_merge_request", - lambda *_args: pytest.fail("missing v11 identity must never approve"), + lambda *_args: pytest.fail("missing current identity must never approve"), ) identity = validated_review_identity(receipt) result = gitlab_approval.execute_approval( @@ -860,7 +949,7 @@ def publish(*_args: Any) -> bool: def test_mid_publication_drift_stops_next_write_and_rolls_back_current_run( next_write: str, monkeypatch: pytest.MonkeyPatch ) -> None: - """A live v11 drift between notes cannot publish the rest of an old review.""" + """A live drift between notes cannot publish the rest of an old review.""" stale = False writes: list[str] = [] @@ -1137,7 +1226,7 @@ def lookup(*_args: Any) -> int: assert writes == ["rollback-current"] -def test_v11_unconfirmed_summary_update_preserves_previous_review( +def test_unconfirmed_summary_update_preserves_previous_review( monkeypatch: pytest.MonkeyPatch, ) -> None: """A final summary write failure cannot certify old-note replacement.""" @@ -1299,11 +1388,16 @@ def test_unconfirmed_previous_cleanup_retains_current_review_and_stops( assert "provider did not confirm the mutation" in capsys.readouterr().err -def test_confirmed_previous_cleanup_checks_freshness_before_each_mutation( - monkeypatch: pytest.MonkeyPatch, +@pytest.mark.parametrize(("excluded_count", "reused_count"), ((0, 0), (1, 0), (0, 1))) +def test_confirmed_previous_cleanup_checks_freshness_and_preserves_partial_findings( + monkeypatch: pytest.MonkeyPatch, excluded_count: int, reused_count: int ) -> None: writes: list[str] = [] - previous = BotCommentRefs(plain_note_ids=[91, 92], discussions_to_resolve=["prior-thread"]) + previous = BotCommentRefs( + plain_note_ids=[91, 92], + summary_plain_note_ids=[92], + discussions_to_resolve=["prior-thread"], + ) monkeypatch.setattr( workflow, "validate_review_freshness", @@ -1322,11 +1416,20 @@ def test_confirmed_previous_cleanup_checks_freshness_before_each_mutation( assert workflow.finalize_previous_review_state( gitlab_config(), previous, - _outcome("clean"), + replace( + _outcome("clean"), + excluded_count=excluded_count, + completed_count=0 if reused_count else 1, + reused_count=reused_count, + ), review_identity=_identity(), transaction=PostingTransaction(), ) - assert writes == ["fresh", "delete-91", "fresh", "delete-92", "fresh", "resolve-prior-thread"] + assert writes == ( + ["fresh", "delete-92"] + if excluded_count or reused_count + else ["fresh", "delete-91", "fresh", "delete-92", "fresh", "resolve-prior-thread"] + ) def test_pre_execution_status_requires_full_live_tuple_and_exact_setup_policy( @@ -1652,12 +1755,14 @@ def test_provider_rejection_of_stale_approval_preserves_previous_review( assert result.preserve_previous_review +@pytest.mark.parametrize("receipt_factory", (review_receipt_v8, _receipt_v11, _receipt_v13)) def test_historical_receipt_is_readback_only_for_current_publication( monkeypatch: pytest.MonkeyPatch, + receipt_factory, ) -> None: - """A v9 receipt cannot be reinterpreted as a v11 current-review identity.""" + """A historical receipt is valid for readback but cannot authorize a new write.""" - receipt = review_receipt_v8() + receipt = receipt_factory() assert validated_review_identity(receipt) is not None monkeypatch.setattr( workflow, @@ -1683,21 +1788,98 @@ def test_formatting_only_displays_validated_policy_sha_without_branch_name() -> assert "limited, comment-only mode" not in summary -def test_operational_partial_retains_safe_finding_after_publication_filter(tmp_path, monkeypatch): +@pytest.mark.parametrize("scenario", ("public", "budget", "private-manifest")) +def test_operational_partial_retains_safe_finding_after_publication_filter( + tmp_path, monkeypatch, isolate_git_coverage, scenario +): from ocr_toolkit import review_runner + from ocr_toolkit.evidence.gitlink_projection import ( + PreviewExclusion, + gitlink_selection_proof, + make_gitlink_projection, + ) + from ocr_toolkit.evidence.gitlinks import plan_review_input + from ocr_toolkit.evidence.repository import GitRepositoryReader from ocr_toolkit.mcp_config import MCPCapability, MCPComposition + from ocr_toolkit.ocr_result import TOOLKIT_REVIEW_SELECTION_KEY + from ocr_toolkit.preflight import RECOMMENDED_OCR_VERSION + from tests.test_gitlinks import _git from tests.test_review_runner import ( BUILTIN_EVIDENCE_TOOLS, DEFAULT_IDENTITY, SUMMARY_ACTION_COUNTS, ) + budget = scenario == "budget" + private_manifest = scenario == "private-manifest" + monkeypatch.setattr(workflow, "verified_review_coverage", isolate_git_coverage) + monkeypatch.chdir(tmp_path) + _git(tmp_path, "init", "-q") + _git(tmp_path, "config", "user.name", "Synthetic") + _git(tmp_path, "config", "user.email", "synthetic@example.invalid") + _git(tmp_path, "commit", "--allow-empty", "-qm", "base") + base = _git(tmp_path, "rev-parse", "HEAD") + files = ("module.py", "worker.py", "ignored.py") + if budget: + files += ("budget.py",) + for name in files: + (tmp_path / name).write_text("value = 1\n", encoding="utf-8") + _git(tmp_path, "add", *files) + _git(tmp_path, "commit", "-qm", "head") + head = _git(tmp_path, "rev-parse", "HEAD") + reader = GitRepositoryReader(tmp_path) + projection = make_gitlink_projection(reader, plan_review_input(reader, base, head)) + selected = tuple(entry for entry in projection.ordinary_diff if entry.path != "ignored.py") + ignored = next(entry for entry in projection.ordinary_diff if entry.path == "ignored.py") + excluded = (PreviewExclusion(ignored, "user_exclude"),) + records = { + entry.path: {"item_id": item_id, "path": entry.path, "fingerprint": digest} + for entry, (item_id, digest) in zip( + projection.ordinary_diff, projection.fingerprints, strict=True + ) + } + result = _result("partial", comments=True) result.pop("_ocr_toolkit") - result["comments"].append( - {"path": "module.py", "line": 2, "content": "hidden synthetic content"} - ) + if not private_manifest: + result["comments"].append( + {"path": "module.py", "line": 1, "content": "hidden synthetic content"} + ) result["tool_calls"] = {"total": 1, "by_tool": {"ocr_toolkit_evidence": 1}} + manifest = result["manifest"] + manifest["input"] = { + **native_range_input(base, head), + "source_artifact_sha256": gitlink_selection_proof(projection, selected)[ + "source_artifact_sha256" + ], + } + manifest["execution"] = {"ocr_version": f"v{RECOMMENDED_OCR_VERSION}"} + manifest["coverage"] = { + "selected": [records[entry.path] for entry in selected], + "excluded": [ + { + "item_id": records[ignored.path]["item_id"], + "path": ignored.path, + "exclude_reason": excluded[0].reason, + } + ], + "completed": [records["module.py"]], + "failed": [{**records["worker.py"], "classification": "provider"}], + "reused": [], + "waived": [], + } + if budget: + result["summary"] = {"budget_exceeded": True} + manifest["coverage"]["failed"].append({**records["budget.py"], "classification": "budget"}) + identity = replace( + DEFAULT_IDENTITY, + source_sha=head, + diff_head_sha=head, + diff_start_sha=base, + diff_base_sha=base, + target_sha=base, + policy_sha=base, + ) path = tmp_path / "review.json" path.write_text(json.dumps(result)) review_runner._finalize_ocr_result( @@ -1705,50 +1887,53 @@ def test_operational_partial_retains_safe_finding_after_publication_filter(tmp_p MCPComposition( {}, (MCPCapability("ocr_toolkit_evidence", BUILTIN_EVIDENCE_TOOLS, True),), (), () ), - DEFAULT_IDENTITY, + identity, None, SUMMARY_ACTION_COUNTS, - forbidden=("hidden synthetic content",), + forbidden=("ignored.py" if private_manifest else "hidden synthetic content",), ocr_exit_code=1, - expected_range=CURRENT_RANGE, + projection=projection, + selected_diff=selected, + excluded_diff=excluded, ) - projected = json.loads(path.read_text()) + projected = load_ocr_result(path) receipt = projected["_ocr_toolkit"] assert "manifest" not in projected assert projected["comments"] == result["comments"][:1] + if private_manifest: + assert not any(receipt["publication"]["omitted"].values()) + assert receipt["publication"]["private_sanitization"]["fields"] + assert "ignored.py" not in path.read_text() assert receipt["publication"]["original"]["operational_partial"] is True - assert validated_review_identity(receipt) is not None + receipt_identity = validated_review_identity(receipt) + assert receipt_identity is not None and receipt_identity.schema_version == 15 + assert workflow.verified_review_coverage(projected, receipt_identity).excluded == 1 assert workflow._admitted_operational_partial(projected) - receipt["publication"]["original"]["operational_partial"] = 1 - assert not workflow._admitted_operational_partial(projected) - publication = receipt["publication"] - publication["original"]["operational_partial"] = True - historical = _receipt_v11() - historical["publication"] = publication - assert validated_review_identity(historical) is None - publication["original"].pop("operational_partial") - assert validated_review_identity(historical) is not None + rejected = deepcopy(projected) + publication = rejected["_ocr_toolkit"]["publication"] + publication["original"]["operational_partial"] = 1 + assert not workflow._admitted_operational_partial(rejected) + if not private_manifest: + historical = _receipt_v11() + historical["publication"] = deepcopy(publication) + historical_original = historical["publication"]["original"] + historical_original.pop("excluded") + assert validated_review_identity(historical) is None + historical_original.pop("operational_partial") + assert validated_review_identity(historical) is not None publication["original"]["operational_partial"] = True publication["retained"]["comments"] = 0 - assert not workflow._admitted_operational_partial(projected) - publication["retained"]["comments"] = 1 - projected["status"] = "budget_exceeded" - projected["summary"] = {"budget_exceeded": True} - assert not workflow._admitted_operational_partial(projected) - publication["original"]["failed"] += 1 - publication["original"]["selected"] += 1 - assert workflow._admitted_operational_partial(projected) + assert not workflow._admitted_operational_partial(rejected) - monkeypatch.chdir(tmp_path) monkeypatch.setenv("CI_MERGE_REQUEST_EVENT_TYPE", "detached") - monkeypatch.setenv("CI_COMMIT_SHA", CURRENT_RANGE.head) - monkeypatch.setenv("CI_MERGE_REQUEST_DIFF_BASE_SHA", CURRENT_RANGE.base) + monkeypatch.setenv("CI_COMMIT_SHA", head) + monkeypatch.setenv("CI_MERGE_REQUEST_DIFF_BASE_SHA", base) monkeypatch.setenv("OCR_AUTO_APPROVE", "true") monkeypatch.setenv("OCR_POST_MODE", "direct") monkeypatch.setattr( workflow, "validate_review_freshness", - lambda *_: freshness.ReviewFreshnessResult(DEFAULT_IDENTITY.policy_sha, False), + lambda *_: freshness.ReviewFreshnessResult(base, False), ) monkeypatch.setattr( workflow, @@ -1775,9 +1960,14 @@ def note(_config, _title, body, _transaction): "delete_previous_bot_comments_if_collected", lambda *_: pytest.fail("prior findings deleted"), ) + tampered = deepcopy(projected) + del tampered[TOOLKIT_REVIEW_SELECTION_KEY] + assert workflow.post_results(gitlab_config(), tampered) == 1 + assert findings == summaries == [] assert workflow.post_ocr_failure(gitlab_config(), tmp_path / "stderr", 1, path) == 1 assert len(findings) == len(summaries) == 1 assert "Review this line." in str(findings) and "hidden synthetic content" not in str(findings) + from ocr_toolkit.telemetry.publications import parse_publication from ocr_toolkit.telemetry.publications.signals import parse_ocr_publication_dlp_signal marker = next( @@ -1785,3 +1975,12 @@ def note(_config, _title, body, _transaction): ) signal, invalid = parse_ocr_publication_dlp_signal(marker) assert "operational_partial" not in marker and signal is not None and not invalid + assert "; excluded 1." in summaries[0] + if private_manifest: + assert "Private manifest fields were sanitized." in summaries[0] + assert "ignored.py" not in summaries[0] + expected_status = "Review stopped at token budget" if budget else "Review incomplete" + assert f"**{expected_status} — 1 finding published" in summaries[0] + publication_event = parse_publication(summaries[0]) + assert publication_event and publication_event["coverage"]["excluded"] == 1 + assert publication_event["outcome"] == ("budget_exceeded" if budget else "incomplete") diff --git a/tests/test_quality_script.py b/tests/test_quality_script.py index daad69b5..5ab11996 100644 --- a/tests/test_quality_script.py +++ b/tests/test_quality_script.py @@ -1,6 +1,7 @@ """Contracts for the quiet quality-command and local secret-scan wrappers.""" import os +import secrets import shlex import shutil import subprocess @@ -250,60 +251,129 @@ def test_quality_script_preserves_failure_status_and_stops( assert "coverage report" in invocations[-1] -def test_gitleaks_wrapper_scans_the_complete_feature_history(tmp_path: Path) -> None: - """Match CI's first-parent, no-merge history before a branch is pushed.""" - +@pytest.mark.parametrize("real_scanner", [False, True]) +def test_gitleaks_wrapper_scans_the_complete_feature_history( + tmp_path: Path, real_scanner: bool +) -> None: + """Scan transient merge findings with the explicit dev target's policy.""" + + wrapper = SCRIPT.parent / "gitleaks.sh" + pinned_version = subprocess.check_output([wrapper, "--version"], text=True).strip() + if real_scanner: + executable = shutil.which("gitleaks") + if executable is None or ( + subprocess.check_output([executable, "version"], text=True).strip() != pinned_version + ): + pytest.skip("the pinned Gitleaks CLI is unavailable") repository = tmp_path / "repository" repository.mkdir() - subprocess.run(["git", "init", "-q", "-b", "main"], cwd=repository, check=True) - subprocess.run(["git", "config", "user.name", "Synthetic User"], cwd=repository, check=True) - subprocess.run( - ["git", "config", "user.email", "synthetic@example.invalid"], cwd=repository, check=True - ) + + def git(*args: str) -> str: + return subprocess.check_output(["git", *args], cwd=repository, text=True).strip() + + git("init", "-q", "-b", "main") + git("config", "user.name", "Synthetic User") + git("config", "user.email", "synthetic@example.invalid") tracked = repository / "tracked.txt" tracked.write_text("base\n", encoding="utf-8") - subprocess.run(["git", "add", "tracked.txt"], cwd=repository, check=True) - subprocess.run(["git", "commit", "-qm", "base"], cwd=repository, check=True) - base_commit = subprocess.check_output( - ["git", "rev-parse", "HEAD"], cwd=repository, text=True - ).strip() - for index in range(2): - tracked.write_text(f"feature {index}\n", encoding="utf-8") - subprocess.run(["git", "commit", "-qam", f"feature {index}"], cwd=repository, check=True) - - binary_dir = tmp_path / "bin" - binary_dir.mkdir() - captured_args = tmp_path / "gitleaks-arguments.txt" - pinned_version = subprocess.check_output( - [str(SCRIPT.parent / "gitleaks.sh"), "--version"], text=True - ).strip() - fake_gitleaks = binary_dir / "gitleaks" - fake_gitleaks.write_text( - "#!/bin/sh\n" - f'if [ "${{1:-}}" = version ]; then echo {pinned_version}; exit 0; fi\n' - f"printf '%s\\n' \"$@\" > {captured_args}\n", - encoding="utf-8", + ignore = repository / ".gitleaksignore" + ignore.write_text("tracked.txt:generic-api-key:1\n", encoding="utf-8") + git("add", "tracked.txt", ".gitleaksignore") + git("commit", "-qm", "main policy") + git("switch", "-qc", "dev") + ignore.write_text("# trusted base policy\ntrusted.txt:generic-api-key:1\n", encoding="utf-8") + git("commit", "-qam", "dev policy") + base = git("rev-parse", "HEAD") + git("update-ref", "refs/remotes/origin/dev", base) + git("switch", "-q", "main") + git("commit", "--allow-empty", "-qm", "main advances") + git("update-ref", "refs/remotes/origin/main", "HEAD") + git("switch", "-qc", "feature", "origin/dev") + git("switch", "-qc", "feature-side") + tracked.write_text("side update\n", encoding="utf-8") + git("commit", "-qam", "side update") + git("switch", "-q", "feature") + tracked.write_text("first-parent update\n", encoding="utf-8") + git("commit", "-qam", "first-parent update") + conflict = subprocess.run( + ["git", "merge", "--no-ff", "--no-edit", "feature-side"], + cwd=repository, + capture_output=True, + text=True, + check=False, ) - fake_gitleaks.chmod(0o755) - for command in ("git", "sed"): - resolved = shutil.which(command) - assert resolved is not None - (binary_dir / command).symlink_to(resolved) + assert conflict.returncode == 1 + assert "CONFLICT (content)" in conflict.stdout + synthetic_value = secrets.token_hex(24) + tracked.write_text(f'api_key = "{synthetic_value}" # gitleaks:allow\n', encoding="utf-8") + trusted = repository / "trusted.txt" + trusted.write_text(f'api_key = "{secrets.token_hex(24)}"\n', encoding="utf-8") + git("add", "tracked.txt", "trusted.txt") + git("commit", "-qm", "resolve conflict") + tracked.write_text("safe final tree\n", encoding="utf-8") + git("rm", "trusted.txt") + ignore.write_text("tracked.txt:generic-api-key:1\n", encoding="utf-8") + (repository / ".gitleaks.toml").write_text('title = "candidate policy"\n', encoding="utf-8") + git("add", ".gitleaks.toml", ".gitleaksignore", "tracked.txt") + git("commit", "-qm", "clean up and change candidate policy") + head = git("rev-parse", "HEAD") + environment = { + **os.environ, + "GITLEAKS_CONFIG": str(repository / ".gitleaks.toml"), + "GITLEAKS_CONFIG_TOML": 'title = "ambient policy"', + } - environment = os.environ.copy() - environment["PATH"] = str(binary_dir) - subprocess.run( - [str(PROJECT_ROOT / "scripts" / "gitleaks.sh"), base_commit, "HEAD"], + captured_args = tmp_path / "gitleaks-arguments.txt" + if not real_scanner: + binary_dir = tmp_path / "bin" + binary_dir.mkdir() + fake_gitleaks = binary_dir / "gitleaks" + fake_gitleaks.write_text( + "#!/bin/sh\n" + "set -eu\n" + f'if [ "${{1:-}}" = version ]; then echo {pinned_version}; exit 0; fi\n' + "test ! -e .gitleaks.toml\n" + 'test -z "${GITLEAKS_CONFIG:-}${GITLEAKS_CONFIG_TOML:-}"\n' + "IFS= read -r ignore_policy < .gitleaksignore\n" + 'test "$ignore_policy" = "# trusted base policy"\n' + f"printf '%s\\n' \"$@\" > {shlex.quote(str(captured_args))}\n", + encoding="utf-8", + ) + fake_gitleaks.chmod(0o755) + environment["PATH"] = f"{binary_dir}{os.pathsep}{environment['PATH']}" + wrong_target = subprocess.run( + [wrapper, "origin/main"], cwd=repository, env=environment, - check=True, + capture_output=True, + text=True, + timeout=30, + check=False, ) - - arguments = captured_args.read_text(encoding="utf-8") - first_feature_commit = subprocess.check_output( - ["git", "rev-list", "--first-parent", "--no-merges", "--reverse", f"{base_commit}..HEAD"], + assert wrong_target.returncode == 2 + assert "gitleaks base ref must be an ancestor" in wrong_target.stderr + completed = subprocess.run( + [wrapper, "origin/dev"], cwd=repository, + env=environment, + capture_output=True, text=True, - ).splitlines()[0] - assert "detect" in arguments - assert f"--no-merges --first-parent {first_feature_commit}^.." in arguments + timeout=30, + check=False, + ) + + if real_scanner: + assert completed.returncode == 1, completed.stderr + assert "leaks found: 1" in completed.stderr + assert synthetic_value not in completed.stdout + completed.stderr + else: + assert completed.returncode == 0, completed.stderr + assert captured_args.read_text(encoding="utf-8").splitlines() == [ + "git", + "--redact=100", + "--exit-code=1", + "--log-level=warn", + "--ignore-gitleaks-allow", + f"--log-opts=--no-ext-diff --no-textconv --diff-merges=first-parent {base}..{head}", + ".", + ] diff --git a/tests/test_release_authorization.py b/tests/test_release_authorization.py index 16eb21dd..17f8d5d1 100644 --- a/tests/test_release_authorization.py +++ b/tests/test_release_authorization.py @@ -14,6 +14,7 @@ from typing import Any import pytest +import yaml SCRIPT = Path(__file__).parents[1] / "scripts" / "release_authorization.py" WORKFLOW = Path(__file__).parents[1] / ".github" / "workflows" / "release.yml" @@ -281,6 +282,18 @@ def test_required_checks_must_succeed_from_the_exact_ruleset_app() -> None: authorize(checks=wrong_app) +@pytest.mark.parametrize("conclusion", ["skipped", "neutral"]) +def test_draft_or_skipped_checks_are_not_release_authorization(conclusion: str) -> None: + checks = check_runs() + checks["check_runs"][0]["conclusion"] = conclusion + with pytest.raises(release.AuthorizationError, match="unsuccessful required check"): + authorize(checks=checks) + + checks["check_runs"][0].update(name="draft-quality", conclusion="success") + with pytest.raises(release.AuthorizationError, match="missing required checks"): + authorize(checks=checks) + + def test_duplicate_or_incomplete_latest_check_response_fails_closed() -> None: checks = check_runs() checks["check_runs"].append( @@ -329,6 +342,97 @@ def test_release_workflow_classifies_ordinary_merges_before_authorization() -> N assert "needs.classify.outputs.release == 'true'" in workflow +@pytest.mark.parametrize( + "scenario", ["matched", "wrong_base", "wrong_parent", "fork", "retired", "side_parent"] +) +def test_manual_recovery_verifies_protected_policy_before_checkout( + tmp_path: Path, scenario: str +) -> None: + job = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))["jobs"]["authorize"] + assert "github.ref == 'refs/heads/main'" in job["if"] + trusted_checkout, gate, checkout = job["steps"][:3] + assert trusted_checkout["if"] == "github.event_name == 'workflow_dispatch'" + assert trusted_checkout["with"] == { + "ref": "${{ github.sha }}", + "path": "dispatch-main", + "fetch-depth": 0, + "persist-credentials": False, + } + assert gate["if"] == "github.event_name == 'workflow_dispatch'" + assert checkout["uses"].startswith("actions/checkout@") + + history = tmp_path / "dispatch-main" + history.mkdir() + + def git(*args: str) -> str: + return subprocess.check_output(["git", *args], cwd=history, text=True).strip() + + git("init", "-q", "-b", "main") + git("config", "user.name", "Synthetic User") + git("config", "user.email", "synthetic@example.invalid") + git("commit", "--allow-empty", "-qm", "historical policy") + base = git("rev-parse", "HEAD") + git("commit", "--allow-empty", "-qm", "squash release") + merge = git("rev-parse", "HEAD") + if scenario in {"retired", "side_parent"}: + git("switch", "-qc", "restored-main", base) + git("commit", "--allow-empty", "-qm", "current policy") + if scenario == "side_parent": + git("merge", "--no-ff", "-qm", "merge old history as a side parent", merge) + git("merge-base", "--is-ancestor", merge, "HEAD") + dispatch_sha = git("rev-parse", "HEAD") + + repository = "example/open-code-review-toolkit" + pr = release_pr() + pr["base"]["repo"] = {"full_name": repository} + pr["base"]["sha"] = base + pr["merge_commit_sha"] = merge + if scenario == "fork": + pr["head"]["repo"]["full_name"] = "fork/open-code-review-toolkit" + parent = dispatch_sha if scenario == "wrong_parent" else base + (tmp_path / "pr.json").write_text(json.dumps(pr)) + (tmp_path / "merge.json").write_text(json.dumps(commit_payload(merge, "e" * 40, [parent]))) + fake_curl = tmp_path / "curl" + fake_curl.write_text( + "#!/bin/sh\n" + 'case " $* " in\n' + ' *" --max-time 30 --max-filesize 1048576 "*) ;;\n' + " *) exit 1 ;;\n" + "esac\n" + "for url do :; done\n" + 'case "$url" in\n' + ' "https://api.github.com/repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER") cat pr.json ;;\n' + ' "https://api.github.com/repos/$GITHUB_REPOSITORY/git/commits/$MERGE") cat merge.json ;;\n' + " *) exit 1 ;;\n" + "esac\n" + ) + fake_curl.chmod(0o700) + environment = { + **os.environ, + "PATH": f"{tmp_path}{os.pathsep}{os.environ['PATH']}", + "GITHUB_REPOSITORY": repository, + "GITHUB_SHA": dispatch_sha, + "GH_TOKEN": "synthetic-token", + "PR_NUMBER": "5", + "VERSION": "0.1.0", + "HEAD": "c" * 40, + "MERGE": merge, + "BASE": dispatch_sha if scenario == "wrong_base" else base, + } + completed = subprocess.run( + ["bash", "-e", "-o", "pipefail", "-c", gate["run"]], + cwd=tmp_path, + env=environment, + text=True, + capture_output=True, + timeout=10, + check=False, + ) + assert (completed.returncode == 0) is (scenario == "matched"), completed.stderr + if scenario in {"retired", "side_parent"}: + assert "outside the dispatch main first-parent history" in completed.stderr + + def test_release_workflow_keeps_strict_release_authorization() -> None: workflow = WORKFLOW.read_text(encoding="utf-8") diff --git a/tests/test_release_notes.py b/tests/test_release_notes.py index 464ba12c..d230539e 100644 --- a/tests/test_release_notes.py +++ b/tests/test_release_notes.py @@ -43,6 +43,7 @@ def test_towncrier_categories_preserve_conditional_release_contract() -> None: "security": "Security", "deprecation": "Deprecations", "removal": "Removals", + "contributor": "Contributors", } diff --git a/tests/test_repository_coverage.py b/tests/test_repository_coverage.py index 0163bbbc..11ad9edf 100644 --- a/tests/test_repository_coverage.py +++ b/tests/test_repository_coverage.py @@ -311,6 +311,7 @@ def test_post_rebuilds_native_partial_coverage_and_rejects_tampering( "execution": {"ocr_version": f"v{preflight.RECOMMENDED_OCR_VERSION}"}, "coverage": { "selected": [item], + "excluded": [], "completed": [item], "reused": [], "failed": [], @@ -330,10 +331,11 @@ def test_post_rebuilds_native_partial_coverage_and_rejects_tampering( with pytest.raises(RepositoryEvidenceError, match="coverage"): workflow.verified_partial_repository_coverage(result, identity) result["_ocr_toolkit"]["repository_coverage"] = _coverage() + result["status"] = result["manifest"]["terminal_state"] = "skipped" result["manifest"]["coverage"]["selected"] = [] result["manifest"]["coverage"]["completed"] = [] result["manifest"]["input"]["source_artifact_sha256"] = hashlib.sha256().hexdigest() - with pytest.raises(RepositoryEvidenceError, match="selected coverage"): + with pytest.raises(RepositoryEvidenceError, match="fresh complete"): workflow.verified_partial_repository_coverage(result, identity) @@ -383,6 +385,7 @@ def test_dlp_filtered_gitlink_review_keeps_safe_finding_and_verifiable_coverage( manifest["execution"] = {"ocr_version": f"v{preflight.RECOMMENDED_OCR_VERSION}"} manifest["coverage"] = { "selected": [item], + "excluded": [], "completed": [item], "reused": [], "failed": [], diff --git a/tests/test_result_contract.py b/tests/test_result_contract.py index be4b5130..d1d0bedc 100644 --- a/tests/test_result_contract.py +++ b/tests/test_result_contract.py @@ -98,6 +98,7 @@ def manifest_result( "selected": [{"item_id": item} for item in selected], "completed": [{"item_id": item} for item in completed], "reused": [{"item_id": item} for item in reused], + "excluded": [], "failed": [ {"item_id": item, "classification": classification} for item, classification in failed @@ -152,6 +153,39 @@ def test_manifest_complete_exposes_bounded_coverage_summary() -> None: ) +def test_manifest_exclusions_are_disjoint_and_visible() -> None: + result = manifest_result("complete", selected=["a"], completed=["a"]) + result["manifest"]["coverage"]["selected"][0]["path"] = "selected.py" + result["manifest"]["coverage"]["excluded"] = [ + {"item_id": "b", "path": "hidden.py", "exclude_reason": "default_path"} + ] + outcome = parse_result_outcome(result) + assert outcome.excluded_count == 1 + assert outcome.coverage_summary.endswith("waived 0; excluded 1.") + + result["manifest"]["coverage"]["excluded"][0]["item_id"] = "a" + with pytest.raises(OcrResultContractError, match="overlap"): + parse_result_outcome(result) + + +@pytest.mark.parametrize("old_path", ["src/old.py", None, [], "", "src/new.py"]) +def test_manifest_excluded_rename_allows_only_a_distinct_bounded_old_path(old_path: object) -> None: + result = manifest_result("complete", selected=["a"], completed=["a"]) + result["manifest"]["coverage"]["excluded"] = [ + { + "item_id": "b", + "path": "src/new.py", + "old_path": old_path, + "exclude_reason": "user_exclude", + } + ] + if old_path == "src/old.py": + assert parse_result_outcome(result).excluded_count == 1 + else: + with pytest.raises(OcrResultContractError, match=r"coverage\.excluded\[0\]"): + parse_result_outcome(result) + + def test_manifest_partial_and_budget_failure_are_supported() -> None: """Publish completed findings while clearly identifying incomplete coverage.""" diff --git a/tests/test_review_coverage.py b/tests/test_review_coverage.py new file mode 100644 index 00000000..85760b37 --- /dev/null +++ b/tests/test_review_coverage.py @@ -0,0 +1,77 @@ +"""Immutable ordinary-diff coverage receipts and approval policy.""" + +from __future__ import annotations + +from dataclasses import replace + +import pytest + +from ocr_toolkit.posting.approval import evaluate_approval_policy +from ocr_toolkit.posting.settings import BooleanSetting +from ocr_toolkit.result_contract import EXCLUSION_REASONS +from ocr_toolkit.review_coverage import ReviewCoverageError, parse_review_coverage +from ocr_toolkit.review_receipt import ( + automatic_approval_metadata_reason, + toolkit_receipt_is_valid, +) +from tests.test_review_receipt_v11 import _clean_outcome +from tests.test_review_receipt_v13 import _receipt_v13 + + +def _coverage(*, excluded: int = 0) -> dict[str, object]: + """Build one closed path-free v15 selection summary.""" + + reasons = dict.fromkeys(sorted(EXCLUSION_REASONS), 0) + reasons["default_path"] = excluded + return { + "schema_version": "ocr.review-coverage/v1", + "state": "partial" if excluded else "complete", + "changed": 2, + "selected": 2 - excluded, + "excluded": excluded, + "exclusion_reasons": reasons, + "selection_sha256": "a" * 64, + } + + +def test_review_coverage_requires_exact_partition_and_reason_counts() -> None: + assert parse_review_coverage(_coverage(excluded=1)).state == "partial" + malformed = _coverage(excluded=1) + malformed["selected"] = 2 + with pytest.raises(ReviewCoverageError, match="inconsistent"): + parse_review_coverage(malformed) + + +@pytest.mark.parametrize("state", [[], {}, None]) +def test_review_coverage_rejects_non_string_states(state: object) -> None: + malformed = _coverage() + malformed["state"] = state + with pytest.raises(ReviewCoverageError, match="invalid values"): + parse_review_coverage(malformed) + + +def test_v15_receipt_blocks_excluded_changed_paths() -> None: + receipt = _receipt_v13() + receipt.update(schema_version=15, review_coverage=_coverage(excluded=1)) + assert toolkit_receipt_is_valid(receipt) + assert ( + automatic_approval_metadata_reason(receipt) + == "one or more immutable changed paths were excluded from review" + ) + assert not evaluate_approval_policy( + BooleanSetting(True), _clean_outcome(), [], [], 0, receipt + ).eligible + + +def test_v15_complete_partition_preserves_clean_approval() -> None: + receipt = _receipt_v13() + receipt.update(schema_version=15, review_coverage=_coverage()) + assert toolkit_receipt_is_valid(receipt) + assert automatic_approval_metadata_reason(receipt) == "" + assert evaluate_approval_policy( + BooleanSetting(True), _clean_outcome(), [], [], 0, receipt + ).eligible + excluded_outcome = replace(_clean_outcome(), excluded_count=1) + assert not evaluate_approval_policy( + BooleanSetting(True), excluded_outcome, [], [], 0, receipt + ).eligible diff --git a/tests/test_review_receipt_v11.py b/tests/test_review_receipt_v11.py index a336abdf..a2810b02 100644 --- a/tests/test_review_receipt_v11.py +++ b/tests/test_review_receipt_v11.py @@ -106,9 +106,10 @@ def test_protected_target_v11_binds_independent_diff_and_policy_identities( assert identity.project_id == identity.policy_project_id == "1" assert identity.target_branch == identity.policy_branch == "main" assert identity.protection_mode == protection_mode - assert evaluate_approval_policy( - BooleanSetting(True), _clean_outcome(), [], [], 0, receipt - ).eligible + assert automatic_approval_metadata_reason(receipt) == "" + approval = evaluate_approval_policy(BooleanSetting(True), _clean_outcome(), [], [], 0, receipt) + assert not approval.eligible + assert approval.result.reason == "a current ordinary review receipt is required" @pytest.mark.parametrize("job_id", ("0", "01", "", 11, None, "a" * 1000)) diff --git a/tests/test_review_receipt_v13.py b/tests/test_review_receipt_v13.py index 3df9db60..4e170422 100644 --- a/tests/test_review_receipt_v13.py +++ b/tests/test_review_receipt_v13.py @@ -35,7 +35,7 @@ def _receipt_v13( *, verified: bool = True, diagram: DiagramResult | None = None, **kwargs: Any ) -> dict[str, Any]: - """Build a current fixture while keeping the frozen v11 fixture unchanged.""" + """Build the frozen v13 receipt.""" receipt = _receipt_v11(**kwargs) diagram = diagram or DiagramResult("off", "disabled") @@ -88,15 +88,15 @@ def test_non_string_receipt_enums_are_invalid_without_incidental_type_errors(pat generated_diagram(sequence=True, mode="spoiler"), ), ) -def test_every_optional_state_and_output_tool_failure_preserves_clean_approval( +def test_every_historical_optional_state_and_output_tool_failure_preserves_readback( diagram: DiagramResult, ) -> None: receipt = _receipt_v13(diagram=diagram) assert toolkit_receipt_is_valid(receipt) assert automatic_approval_metadata_reason(receipt) == "" - assert evaluate_approval_policy( - BooleanSetting(True), _clean_outcome(), [], [], 0, receipt - ).eligible + approval = evaluate_approval_policy(BooleanSetting(True), _clean_outcome(), [], [], 0, receipt) + assert not approval.eligible + assert approval.result.reason == "a current ordinary review receipt is required" def test_optional_output_failure_does_not_hide_a_failed_evidence_read() -> None: diff --git a/tests/test_review_runner.py b/tests/test_review_runner.py index c90bc04f..72a27263 100644 --- a/tests/test_review_runner.py +++ b/tests/test_review_runner.py @@ -19,15 +19,22 @@ import pytest from ocr_toolkit import ocr_result, review_runner +from ocr_toolkit.common.git import isolated_git_environment from ocr_toolkit.context.ci_outcomes import CIOutcomeSnapshot from ocr_toolkit.context.contracts import TextBudgets -from ocr_toolkit.context.dlp import ForbiddenMatcher, ForbiddenValue +from ocr_toolkit.context.dlp import ForbiddenMatcher, ForbiddenValue, admission from ocr_toolkit.context.policy import parse_policy from ocr_toolkit.context.store import ContextStore from ocr_toolkit.evidence import EvidenceRecord, EvidenceSnapshot, EvidenceStore, RefRole from ocr_toolkit.evidence.actions import record_action from ocr_toolkit.evidence.artifacts import EvidenceArtifacts, repository_artifacts -from ocr_toolkit.evidence.repository import RepositoryEvidenceError +from ocr_toolkit.evidence.gitlink_projection import ( + GitlinkProjection, + gitlink_selection_proof, + make_gitlink_projection, +) +from ocr_toolkit.evidence.gitlinks import plan_review_input +from ocr_toolkit.evidence.repository import GitRepositoryReader, RepositoryEvidenceError from ocr_toolkit.evidence.review_context import normalize_merge_request_context from ocr_toolkit.mcp_config import MCPCapability, MCPComposition from ocr_toolkit.posting import approval, gitlab, settings, snapshot, workflow @@ -37,11 +44,12 @@ GitLabReviewSnapshot, ) from ocr_toolkit.reporting.dlp import publication_dlp_state -from ocr_toolkit.result_contract import parse_result_outcome +from ocr_toolkit.result_contract import EXCLUSION_REASONS, parse_result_outcome from ocr_toolkit.review_range import ReviewRange from tests.support import gitlab_config, native_range_input, patched_attr, patched_env from tests.test_context_broker import ci_outcome from tests.test_context_policy import ci_policy_value, encoded_policy, remediation_policy_value +from tests.test_evidence_repository import git DEFAULT_IDENTITY = review_runner.ReviewIdentity( source_sha="a" * 40, @@ -327,6 +335,41 @@ def complete_review_payload(*, tool_calls: dict[str, object]) -> dict[str, objec } +def _ordinary_review_refs(root: Path, *paths: str) -> tuple[str, str]: + git(root, "init", "-q") + for path in paths: + source = root / path + source.parent.mkdir(parents=True, exist_ok=True) + source.write_text("value = 1\n", encoding="utf-8") + git(root, "add", "--", *paths) + git(root, "commit", "-qm", "base") + base = git(root, "rev-parse", "HEAD") + for path in paths: + (root / path).write_text("value = 2\n", encoding="utf-8") + git(root, "commit", "-qam", "head") + return base, git(root, "rev-parse", "HEAD") + + +def _bind_ordinary_native_manifest( + payload: dict[str, object], projection: GitlinkProjection +) -> dict: + manifest = payload["manifest"] + selected = projection.ordinary_diff + rows = [ + {"item_id": item_id, "path": entry.path, "fingerprint": fingerprint} + for (item_id, fingerprint), entry in zip(projection.fingerprints, selected, strict=True) + ] + manifest["input"] = { + **native_range_input(projection.plan.base_sha, projection.plan.head_sha), + "source_artifact_sha256": gitlink_selection_proof(projection, selected)[ + "source_artifact_sha256" + ], + } + manifest["execution"] = {"ocr_version": f"v{review_runner.preflight.RECOMMENDED_OCR_VERSION}"} + manifest["coverage"].update(selected=rows, completed=rows.copy(), excluded=[]) + return manifest + + def enriched_identity() -> review_runner.ReviewIdentity: """Return one provider-normalized enriched-review identity.""" @@ -760,6 +803,16 @@ def test_safe_mr_and_enrichment_data_preserve_auto_approval_but_remediation_does review_range=ReviewRange("c" * 40, "a" * 40), ) metadata["schema_version"] = ocr_result.TOOLKIT_RESULT_SCHEMA_VERSION + complete_coverage = { + "schema_version": "ocr.review-coverage/v1", + "state": "complete", + "changed": 1, + "selected": 1, + "excluded": 0, + "exclusion_reasons": dict.fromkeys(EXCLUSION_REASONS, 0), + "selection_sha256": "e" * 64, + } + metadata["review_coverage"] = complete_coverage metadata["publication"] = {"schema": "ocr.publication/v2", "state": "passed"} eligible = approval.evaluate_approval_policy( settings.BooleanSetting(True), @@ -796,6 +849,7 @@ def test_safe_mr_and_enrichment_data_preserve_auto_approval_but_remediation_does review_range=ReviewRange("c" * 40, "a" * 40), ) blocked["schema_version"] = ocr_result.TOOLKIT_RESULT_SCHEMA_VERSION + blocked["review_coverage"] = complete_coverage blocked["publication"] = {"schema": "ocr.publication/v2", "state": "passed"} decision = approval.evaluate_approval_policy( settings.BooleanSetting(True), @@ -1294,6 +1348,14 @@ def test_private_failure_arguments_preserve_finalized_signal_and_gitlab_notes( ) -> None: """Drop opaque arguments before DLP and preserve the complete posting projection.""" + root = tmp_path / "checkout" + root.mkdir() + base, head = _ordinary_review_refs(root, "src/safe.py", "src/second.py") + monkeypatch.chdir(root) + reader = GitRepositoryReader(root) + projection = make_gitlink_projection(reader, plan_review_input(reader, base, head)) + selected = projection.ordinary_diff + identity = replace(DEFAULT_IDENTITY, source_sha=head, diff_head_sha=head, diff_base_sha=base) composition = MCPComposition( payload={}, capabilities=(MCPCapability("ocr_toolkit_evidence", BUILTIN_EVIDENCE_TOOLS, True),), @@ -1307,7 +1369,7 @@ def test_private_failure_arguments_preserve_finalized_signal_and_gitlab_notes( monkeypatch.setattr( workflow, "current_merge_request_lifecycle", - lambda *_args: workflow.GitLabMergeRequestLifecycle("1", "2", "a" * 40, "opened"), + lambda *_args: workflow.GitLabMergeRequestLifecycle("1", "2", head, "opened"), ) monkeypatch.setattr(workflow, "get_diff_refs", lambda _: None) monkeypatch.setattr(workflow, "validate_review_freshness", lambda *_args: None) @@ -1339,6 +1401,8 @@ def test_private_failure_arguments_preserve_finalized_signal_and_gitlab_notes( } ) payload["token_usage"] = {"input_tokens": 100, "output_tokens": 20, "total_tokens": 120} + manifest = _bind_ordinary_native_manifest(payload, projection) + coverage = manifest["coverage"] if public_case == "clean": payload["comments"] = [] elif public_case == "filtered": @@ -1348,11 +1412,10 @@ def test_private_failure_arguments_preserve_finalized_signal_and_gitlab_notes( {"type": "comment_args_repaired", "message": "Repaired serialized comments"} ] elif public_case == "partial": - payload["manifest"]["terminal_state"] = "partial" - coverage = payload["manifest"]["coverage"] - coverage["selected"].append({"item_id": "unfinished"}) + manifest["terminal_state"] = "partial" + unfinished = coverage["completed"].pop() coverage["failed"].append( - {"item_id": "unfinished", "classification": "provider", "reason": "Unavailable"} + {**unfinished, "classification": "provider", "reason": "Unavailable"} ) payload["status"] = "partial" result = tmp_path / f"result-{include_arguments}.json" @@ -1362,10 +1425,12 @@ def test_private_failure_arguments_preserve_finalized_signal_and_gitlab_notes( _, filtered, publication = review_runner._finalize_ocr_result( result, composition, - DEFAULT_IDENTITY, + identity, None, SUMMARY_ACTION_COUNTS, forbidden=("private-argument-canary",), + projection=projection, + selected_diff=selected, ) persisted = json.loads(result.read_text(encoding="utf-8")) serialized = result.read_text(encoding="utf-8") @@ -2016,7 +2081,9 @@ def test_ocr_result_receipt_blocks_approval_when_mr_context_was_admitted( } -def test_publication_projection_blocks_context_copy_secret_pii_and_laundering() -> None: +def test_publication_projection_blocks_context_copy_secret_pii_and_laundering( + monkeypatch: pytest.MonkeyPatch, +) -> None: forbidden = ( "prefix private context sentence suffix", "ghp_abcdefghijklmnopqrstuvwxyz123456", @@ -2108,13 +2175,19 @@ def test_publication_projection_blocks_context_copy_secret_pii_and_laundering() assert projected["comments"] assert publication["state"] == "passed" and not blocked - work_bound_payload: dict[str, object] = { - "status": "success", - "comments": [{"content": "safe " * 400}], - } + long_finding = {"content": "safe " * 399 + "safe"} + work_bound_payload: dict[str, object] = {"status": "success", "comments": [long_finding]} + large_forbidden = ("private " * 20_000,) + projected, publication, blocked = review_runner._publication_projection( + work_bound_payload, forbidden=large_forbidden, allowed_tools=frozenset() + ) + assert projected["comments"] == [long_finding] + assert publication["state"] == "passed" and not blocked + + monkeypatch.setattr(admission, "MAX_FORBIDDEN_MATCH_WORK", 100) projected, publication, blocked = review_runner._publication_projection( work_bound_payload, - forbidden=("private " * 20_000,), + forbidden=large_forbidden, allowed_tools=frozenset(), ) assert projected["comments"] == [] @@ -2324,27 +2397,84 @@ def test_publication_dlp_retains_only_safe_local_findings_without_provider_recei assert "ocr_toolkit_evidence" in rendered -def test_background_preview_advisory_is_atomically_finalized_without_blocking_approval( - tmp_path: Path, +def test_publication_preserves_technical_findings_and_omits_sensitive_neighbors( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - """Keep the accepted numeric advisory outside warnings, DLP, and approval inputs.""" - + """Run real immutable source proof, finalization and local Markdown delivery together.""" + root = tmp_path.resolve() / "source" + root.mkdir() + prefix = [ + "git", + "-C", + str(root), + "-c", + "core.hooksPath=/dev/null", + "-c", + "commit.gpgsign=false", + "-c", + "user.name=Synthetic Author", + "-c", + "user.email=author@example.invalid", + ] + environment = isolated_git_environment() + + def git(*args: str) -> str: + return subprocess.run( + [*prefix, *args], env=environment, check=True, capture_output=True, text=True + ).stdout.strip() + + git("init", "-q") + git("commit", "--allow-empty", "-qm", "base") + base = git("rev-parse", "HEAD") + product = "MAX_SCAN_BYTES = 16 * 1024 * 1024" + date_range = "2026-11-03…2026-11-30" + dated_link = "[§8](../../BUDGET.md#8-замер-2026-11-30)" + phone = "+1 202 555 0114" + secret = "synthetic-private-value" + path = "scan.py" + (root / path).write_text( + product + "\nwindow = None\nguide = None\nowner = None\nconfig = None\n", + encoding="utf-8", + ) + git("add", path) + git("commit", "-qm", "head") + head = git("rev-parse", "HEAD") + monkeypatch.chdir(root) + safe = [ + { + "path": path, + "start_line": 1, + "end_line": 1, + "content": f"Preserve the limit when changing `{product}`.", + "existing_code": product, + }, + {"path": path, "line": 2, "content": f"| Period | {date_range} |"}, + {"path": path, "line": 3, "content": f"Read {dated_link} for the budget."}, + ] + rejected = [ + { + "path": path, + "line": 4, + "content": f"Window {date_range}. Compare `{product}`. Contact {phone}.", + }, + {"path": path, "line": 5, "content": f'Read {dated_link}. password="{secret}"'}, + ] result = tmp_path / "result.json" result.write_text( json.dumps( { "status": "complete", - "comments": [], + "comments": [*safe, *rejected], "warnings": [], "tool_calls": {"total": 1, "by_tool": {"ocr_toolkit_evidence": 1}}, "manifest": { "schema_version": "ocr.run-manifest/v1", "operation": "review", "terminal_state": "complete", - "input": native_range_input("c" * 40, "a" * 40), + "input": native_range_input(base, head), "coverage": { - "selected": [{"item_id": "synthetic-item"}], - "completed": [{"item_id": "synthetic-item"}], + "selected": [{"item_id": "scan"}], + "completed": [{"item_id": "scan"}], "reused": [], "failed": [], "waived": [], @@ -2360,17 +2490,73 @@ def test_background_preview_advisory_is_atomically_finalized_without_blocking_ap external_servers=(), secret_values=(), ) + local_state = review_runner.ReviewRunState(local=True) + + _, blocked, publication = review_runner._finalize_ocr_result( + result, + composition, + replace(LOCAL_IDENTITY, source_sha=head), + None, + SUMMARY_ACTION_COUNTS, + forbidden=(), + report_consumer=local_state.admit_report, + state=local_state, + expected_range=ReviewRange(base, head), + ocr_exit_code=0, + ) + + assert blocked and publication["state"] == "publication-filtered" + assert publication["omitted"] == {"comments": 2, "warnings": 0, "fields": 2} + assert publication["reason_counts"]["pii"] == publication["reason_counts"]["secret"] == 1 + persisted = result.read_text(encoding="utf-8") + finalized = json.loads(persisted) + assert finalized["status"] == "completed_with_errors" + assert finalized["comments"] == safe + assert local_state.report is not None + assert list(local_state.report.comments) == safe + assert local_state.report.outcome.status == "complete" + markdown = tmp_path / "review.md" + review_runner.publish_local_report(local_state.report, markdown) + rendered = markdown.read_text(encoding="utf-8") + assert all(value in rendered for value in (product, date_range, dated_link)) + for private in (phone, secret, "Window", "Contact"): + assert private not in persisted and private not in rendered + + +def test_background_preview_advisory_is_atomically_finalized_without_blocking_approval( + tmp_path: Path, +) -> None: + """Keep the accepted numeric advisory outside warnings, DLP, and approval inputs.""" + + base, head = _ordinary_review_refs(tmp_path, "src/safe.py") + reader = GitRepositoryReader(tmp_path) + projection = make_gitlink_projection(reader, plan_review_input(reader, base, head)) + identity = replace(DEFAULT_IDENTITY, source_sha=head, diff_head_sha=head, diff_base_sha=base) + payload = complete_review_payload( + tool_calls={"total": 1, "by_tool": {"ocr_toolkit_evidence": 1}} + ) + payload["comments"] = [] + _bind_ordinary_native_manifest(payload, projection) + result = tmp_path / "result.json" + result.write_text(json.dumps(payload), encoding="utf-8") + composition = MCPComposition( + payload={}, + capabilities=(MCPCapability("ocr_toolkit_evidence", BUILTIN_EVIDENCE_TOOLS, True),), + external_servers=(), + secret_values=(), + ) advisory = ocr_result.background_recommended_advisory(actual=2_100, recommended=2_000) _usage, blocked, publication = review_runner._finalize_ocr_result( result, composition, - replace(DEFAULT_IDENTITY, mr_author_id=41, target_protection="protected"), + identity, None, SUMMARY_ACTION_COUNTS, forbidden=(), toolkit_advisory=advisory, - expected_range=ReviewRange("c" * 40, "a" * 40), + projection=projection, + selected_diff=projection.ordinary_diff, ) persisted = json.loads(result.read_text(encoding="utf-8")) @@ -2837,26 +3023,15 @@ def test_review_groups_remain_private_and_cannot_change_approval(tmp_path: Path) external_servers=(), secret_values=(), ) - identity = replace(DEFAULT_IDENTITY, mr_author_id=41, target_protection="protected") - base_payload: dict[str, object] = { - "status": "complete", - "comments": [], - "warnings": [], - "tool_calls": {"total": 1, "by_tool": {"ocr_toolkit_evidence": 1}}, - "manifest": { - "schema_version": "ocr.run-manifest/v1", - "operation": "review", - "terminal_state": "complete", - "coverage": { - "selected": [{"item_id": "review-a"}], - "completed": [{"item_id": "review-a"}], - "reused": [], - "failed": [], - "waived": [], - }, - }, - } - base_payload["manifest"]["input"] = native_range_input("c" * 40, "a" * 40) + base, head = _ordinary_review_refs(tmp_path, "src/core.py") + reader = GitRepositoryReader(tmp_path) + projection = make_gitlink_projection(reader, plan_review_input(reader, base, head)) + identity = replace(DEFAULT_IDENTITY, source_sha=head, diff_head_sha=head, diff_base_sha=base) + base_payload = complete_review_payload( + tool_calls={"total": 1, "by_tool": {"ocr_toolkit_evidence": 1}} + ) + base_payload["comments"] = [] + _bind_ordinary_native_manifest(base_payload, projection) baseline_projection = review_runner._canonical_result_projection(base_payload) for name, groups, expected_state in ( @@ -2890,7 +3065,8 @@ def test_review_groups_remain_private_and_cannot_change_approval(tmp_path: Path) None, SUMMARY_ACTION_COUNTS, forbidden=(), - expected_range=ReviewRange("c" * 40, "a" * 40), + projection=projection, + selected_diff=projection.ordinary_diff, ) persisted = json.loads(result.read_text(encoding="utf-8")) @@ -4712,11 +4888,16 @@ def test_evidence_review_prepares_internal_context_before_ocr( ) -> None: """Clean every execution while preserving immutable input and terminal attribution.""" + root = tmp_path / "checkout" + root.mkdir() + base, head = _ordinary_review_refs(root, "src/safe.py") + monkeypatch.chdir(root) monkeypatch.setenv("OCR_REVIEW_PROGRESS", "true" if progress_on else "false") + monkeypatch.setenv("OCR_REVIEW_DIAGRAM_MODE", "off") monkeypatch.setenv("CI_PROJECT_ID", "1") monkeypatch.setenv("CI_MERGE_REQUEST_IID", "2") monkeypatch.setenv("CI_MERGE_REQUEST_EVENT_TYPE", "detached") - monkeypatch.setenv("CI_COMMIT_SHA", "b" * 40) + monkeypatch.setenv("CI_COMMIT_SHA", head) monkeypatch.delenv("CI_MERGE_REQUEST_SOURCE_BRANCH_SHA", raising=False) events: list[object] = [] composition_inputs: list[dict[str, object]] = [] @@ -4724,13 +4905,14 @@ def test_evidence_review_prepares_internal_context_before_ocr( session_homes: list[Path] = [] real_subprocess_run = subprocess.run original_home = os.environ.get("HOME") - artifacts = review_runner.repository_artifacts(tmp_path) + artifacts = review_runner.repository_artifacts(root) review_runner.prepare_artifact_directory(artifacts) artifacts.pre_execution_status.write_text("stale", encoding="utf-8") artifacts.pre_execution_status.chmod(0o600) + head_sha = head class Store: - head = SimpleNamespace(commit_sha="b" * 40) + head = SimpleNamespace(commit_sha=head_sha) base = None policy = None target = None @@ -4768,10 +4950,31 @@ def run(result: Path, stderr: Path, args: list[str], **_kwargs: object) -> int: return ocr_exit_code def preview(argv: list[str], **kwargs: object) -> subprocess.CompletedProcess[bytes]: - if "stdout" not in kwargs: + if argv[0] != "/synthetic/ocr": return real_subprocess_run(argv, **kwargs) # type: ignore[return-value] + if argv[1:] == ["--version"]: + version = review_runner.preflight.RECOMMENDED_OCR_VERSION + return subprocess.CompletedProcess(argv, 0, stdout=f"open-code-review v{version}\n") events.append(("preview", argv)) - kwargs["stdout"].write(b'{"files":[]}\n') # type: ignore[union-attr] + stdout = json.dumps( + { + "files": [ + { + "path": "src/safe.py", + "status": "modified", + "insertions": 1, + "deletions": 1, + "will_review": True, + } + ], + "total_insertions": 1, + "total_deletions": 1, + "total_files": 1, + "reviewable_count": 1, + "excluded_count": 0, + } + ).encode() + kwargs["stdout"].write(stdout) # type: ignore[union-attr] kwargs["stderr"].write( # type: ignore[union-attr] b"[ocr] --max-tools 30 is below minimum 50, using 50\n" ) @@ -4812,9 +5015,11 @@ def bootstrap(*_args: object, **kwargs: object) -> str: identity = replace( DEFAULT_IDENTITY, - source_sha="b" * 40, - policy_sha="a" * 40, - target_sha="a" * 40, + source_sha=head, + diff_head_sha=head, + diff_base_sha=base, + policy_sha=base, + target_sha=base, target_protection=target_protection, mr_author_id=41 if target_protection != "local" else None, policy_protection=("unprotected" if target_protection == "unprotected" else "protected"), @@ -4822,12 +5027,6 @@ def bootstrap(*_args: object, **kwargs: object) -> str: ) with ( - patched_attr( - review_runner, - "_immutable_review_refs", - lambda _refs: review_runner.ReviewRefs("a" * 40, "b" * 40), - ), - patched_attr(review_runner, "plan_gitlink_input", lambda *_args: None), patched_attr(review_runner, "_write_isolated_runtime_config", lambda: None), patched_attr( review_runner, @@ -4862,7 +5061,7 @@ def bootstrap(*_args: object, **kwargs: object) -> str: patched_attr( review_runner, "evidence_summary", - lambda *_args: {"base": "a" * 40, "head": "b" * 40, "records": 3}, + lambda *_args: {"base": base, "head": head, "records": 3}, ), patched_attr( review_runner, "_verify_evidence_mcp", lambda _store: events.append("self-query") @@ -4881,9 +5080,9 @@ def bootstrap(*_args: object, **kwargs: object) -> str: tmp_path / "stderr.log", [ "--from", - "base", + base, "--to", - "head", + head, "--format", "json", "--max-tools", @@ -4905,10 +5104,10 @@ def bootstrap(*_args: object, **kwargs: object) -> str: assert events[0] == ( "collect", { - "base_ref": "a" * 40, - "head_ref": "b" * 40, - "policy_ref": "a" * 40, - "target_ref": "a" * 40, + "base_ref": base, + "head_ref": head, + "policy_ref": base, + "target_ref": base, "include_policy_records": target_protection != "unprotected", }, ) @@ -4927,7 +5126,7 @@ def bootstrap(*_args: object, **kwargs: object) -> str: "protected_policy_fallback": False, } ] - assert events[1] == ("enrich", f"invocation:{'b' * 40}") + assert events[1] == ("enrich", f"invocation:{head}") assert events[2] == ("write", artifacts.store) assert events[3] == ("bootstrap", artifacts.bootstrap, "bootstrap") assert events[4] == "apply" @@ -4938,9 +5137,9 @@ def bootstrap(*_args: object, **kwargs: object) -> str: "/synthetic/ocr", "review", "--from", - "a" * 40, + base, "--to", - "b" * 40, + head, "--format", "json", "--max-tools", diff --git a/tests/test_review_runner_publication_boundaries.py b/tests/test_review_runner_publication_boundaries.py new file mode 100644 index 00000000..48bacbd6 --- /dev/null +++ b/tests/test_review_runner_publication_boundaries.py @@ -0,0 +1,639 @@ +"""Verify publication handoffs without native execution or a live provider.""" + +from __future__ import annotations + +import json +from dataclasses import replace +from pathlib import Path + +import pytest + +from ocr_toolkit import ocr_result, review_analysis, review_runner +from ocr_toolkit.context.dlp import ForbiddenValue +from ocr_toolkit.evidence import source_reader +from ocr_toolkit.evidence.gitlink_projection import ( + PreviewExclusion, + gitlink_selection_proof, + make_gitlink_projection, +) +from ocr_toolkit.evidence.gitlinks import plan_gitlink_input, plan_review_input +from ocr_toolkit.evidence.repository import GitRepositoryReader, RepositoryEvidenceError +from ocr_toolkit.mcp_config import MCPCapability, MCPComposition +from ocr_toolkit.posting import gitlab, snapshot, workflow +from ocr_toolkit.posting.approval import evaluate_approval_policy, toolkit_receipt_is_valid +from ocr_toolkit.posting.settings import BooleanSetting +from ocr_toolkit.posting.workflow import verified_review_coverage +from ocr_toolkit.preflight import RECOMMENDED_OCR_VERSION +from ocr_toolkit.result_contract import parse_result_outcome +from ocr_toolkit.review_debug import DebugBundle +from ocr_toolkit.review_range import ReviewRange +from ocr_toolkit.review_receipt import validated_review_identity +from ocr_toolkit.telemetry.publications import parse_publication +from tests.support import gitlab_config, native_range_input +from tests.test_evidence_repository import git +from tests.test_gitlinks import _fixture as gitlink_fixture +from tests.test_gitlinks import _ordinary_exclusion_fixture +from tests.test_review_runner import ( + BUILTIN_EVIDENCE_TOOLS, + DEFAULT_IDENTITY, + LOCAL_IDENTITY, + SUMMARY_ACTION_COUNTS, + _bind_ordinary_native_manifest, + _ordinary_review_refs, +) + +_COMPOSITION = MCPComposition( + payload={}, + capabilities=(MCPCapability("ocr_toolkit_evidence", BUILTIN_EVIDENCE_TOOLS, True),), + external_servers=(), + secret_values=(), +) +_SAFE = {"path": "main.php", "line": 2, "content": "Preserve the boundary check."} +_PRIVATE = {"path": "main.php", "line": 2, "content": "Contact +1 202 555 0114."} + + +def _native_result(base: str, head: str) -> dict: + item = {"item_id": "completed", "path": "main.php"} + return { + "status": "complete", + "comments": [_SAFE.copy()], + "warnings": [], + "tool_calls": {"total": 1, "by_tool": {"ocr_toolkit_evidence": 1}}, + "manifest": { + "schema_version": "ocr.run-manifest/v1", + "operation": "review", + "terminal_state": "complete", + "input": native_range_input(base, head), + "coverage": { + "selected": [item.copy()], + "excluded": [], + "completed": [item.copy()], + "failed": [], + "reused": [], + "waived": [], + }, + }, + } + + +@pytest.mark.parametrize( + ("changes", "exit_code", "message"), + [ + pytest.param( + {"analysis_raw": "private trace"}, 0, "unsolicited", id="unsolicited-analysis" + ), + pytest.param({"status": "unexpected"}, 0, "outcome is invalid", id="unknown-status"), + pytest.param({}, 1, "exit does not match", id="successful-result-on-failed-exit"), + pytest.param({"warnings": {}}, None, "not valid bounded JSON", id="invalid-warnings"), + ], +) +def test_unadmitted_native_envelopes_leave_no_publishable_result( + tmp_path: Path, changes: dict, exit_code: int | None, message: str +) -> None: + base, head = "b" * 40, "a" * 40 + result = tmp_path / "result.json" + result.write_text(json.dumps({**_native_result(base, head), **changes}), encoding="utf-8") + reports = [] + + with pytest.raises(review_runner.ReviewRunnerError, match=message): + review_runner._finalize_ocr_result( + result, + _COMPOSITION, + LOCAL_IDENTITY, + None, + SUMMARY_ACTION_COUNTS, + forbidden=(), + report_consumer=reports.append, + ocr_exit_code=exit_code, + ) + + assert not result.exists() + assert not reports + + +@pytest.mark.parametrize("mismatch", ["caller", "native"]) +def test_range_mismatch_discards_only_an_unadmitted_native_result( + tmp_path: Path, mismatch: str +) -> None: + base, head, other = "b" * 40, "a" * 40, "c" * 40 + result = tmp_path / "result.json" + payload = _native_result(base, other if mismatch == "native" else head) + original = json.dumps(payload) + result.write_text(original, encoding="utf-8") + expected_range = ReviewRange(base, other if mismatch == "caller" else head) + reports = [] + + with pytest.raises(review_runner.ReviewRunnerError, match="range"): + review_runner._finalize_ocr_result( + result, + _COMPOSITION, + LOCAL_IDENTITY, + None, + SUMMARY_ACTION_COUNTS, + forbidden=(), + expected_range=expected_range, + report_consumer=reports.append, + ) + + if mismatch == "caller": + assert result.read_text(encoding="utf-8") == original + else: + assert not result.exists() + assert not reports + + +def test_operational_partial_remains_distinct_after_publication_filtering(tmp_path: Path) -> None: + base, head = "b" * 40, "a" * 40 + payload = _native_result(base, head) + payload["status"] = payload["manifest"]["terminal_state"] = "partial" + coverage = payload["manifest"]["coverage"] + failed = {"item_id": "failed", "path": "other.php"} + coverage["selected"].append(failed) + coverage["failed"].append({**failed, "classification": "provider"}) + payload["comments"].append(_PRIVATE) + result = tmp_path / "result.json" + result.write_text(json.dumps(payload), encoding="utf-8") + reports = [] + + _, filtered, publication = review_runner._finalize_ocr_result( + result, + _COMPOSITION, + LOCAL_IDENTITY, + None, + SUMMARY_ACTION_COUNTS, + forbidden=(), + expected_range=ReviewRange(base, head), + report_consumer=reports.append, + ocr_exit_code=1, + ) + + assert filtered and publication["original"]["operational_partial"] is True + assert publication["original"]["failed"] == 1 + assert json.loads(result.read_text(encoding="utf-8"))["comments"] == [_SAFE] + assert reports[0].outcome.kind == "partial" + assert reports[0].outcome.failed_count == 1 + assert "202 555 0114" not in result.read_text(encoding="utf-8") + + +@pytest.mark.parametrize("damage_manifest", [False, True]) +def test_finalizer_binds_filtered_gitlink_coverage_and_admitted_analysis( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, damage_manifest: bool +) -> None: + repo = tmp_path / "repo" + repo.mkdir() + base, head = gitlink_fixture(repo, "updated") + monkeypatch.chdir(repo) + monkeypatch.setenv("CI_JOB_TOKEN", "synthetic-approval-token") + reader = GitRepositoryReader(repo) + plan = plan_gitlink_input(reader, base, head) + assert plan is not None + projection = make_gitlink_projection(reader, plan) + selected = projection.ordinary_diff + selection = gitlink_selection_proof(projection, selected) + item_id, fingerprint = projection.fingerprints[0] + item = {"item_id": item_id, "path": "main.php", "fingerprint": fingerprint} + payload = _native_result(base, head) + manifest = payload["manifest"] + manifest["execution"] = {"ocr_version": f"v{RECOMMENDED_OCR_VERSION}"} + manifest["coverage"]["selected"] = [item] + manifest["coverage"]["completed"] = [item] + manifest["input"]["source_artifact_sha256"] = ( + "0" * 64 if damage_manifest else selection["source_artifact_sha256"] + ) + payload["comments"].append(_PRIVATE) + payload.update( + schema_version=review_analysis.COMBINED_SCHEMA, + review_status="complete", + analysis="Inspect the updated threshold.", + analysis_raw="private native trace placeholder", + analysis_meta={ + "schema_version": review_analysis.METADATA_SCHEMA, + "execution_status": "completed", + "submission_accepted": True, + "declared_completion": "complete", + }, + llm={"model": "fixture-model", "provider_trace": "private provider data"}, + ) + identity = replace(DEFAULT_IDENTITY, source_sha=head, diff_head_sha=head, diff_base_sha=base) + result = tmp_path / "result.json" + result.write_text(json.dumps(payload), encoding="utf-8") + reports = [] + + def finalize(): + return review_runner._finalize_ocr_result( + result, + _COMPOSITION, + identity, + None, + SUMMARY_ACTION_COUNTS, + forbidden=(), + projection=projection, + selected_diff=selected, + analysis_requested=True, + configured_model="fixture-model", + report_consumer=reports.append, + ocr_exit_code=0, + ) + + if damage_manifest: + with pytest.raises(review_runner.ReviewRunnerError, match="did not prove the immutable"): + finalize() + assert not result.exists() and not reports + return + + _, filtered, _ = finalize() + raw = result.read_text(encoding="utf-8") + saved = json.loads(raw) + receipt = saved[ocr_result.TOOLKIT_RESULT_KEY] + assert filtered and toolkit_receipt_is_valid(receipt) + assert saved[ocr_result.TOOLKIT_GITLINK_SELECTION_KEY] == selection + assert reports[0].repository_coverage.payload() == receipt["repository_coverage"] + assert receipt["repository_coverage"]["gitlink_updated"] == 1 + assert receipt["repository_coverage"]["ordinary_completed"] == 1 + assert saved["comments"] == [_SAFE] and saved["llm"] == {"model": "fixture-model"} + admitted_analysis = saved[review_analysis.PRIVATE_RESULT_KEY] + assert admitted_analysis["markdown"] == "Inspect the updated threshold." + assert receipt["analysis_hmac_sha256"] == review_analysis.publication_digest( + admitted_analysis, receipt["review"] + ) + assert "private native trace placeholder" not in raw and "private provider data" not in raw + + +@pytest.mark.parametrize("filter_publication", [False, True]) +def test_preview_only_gitignore_remains_partial_on_posting_readback( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, filter_publication: bool +) -> None: + repo = tmp_path / "checkout" + repo.mkdir() + base, head = _ordinary_exclusion_fixture(repo) + monkeypatch.chdir(repo) + reader = GitRepositoryReader(repo) + projection = make_gitlink_projection(reader, plan_review_input(reader, base, head)) + ignored, reviewed = projection.ordinary_diff + selected = (reviewed,) + selected_id, fingerprint = projection.fingerprints[1] + record = {"item_id": selected_id, "path": reviewed.path, "fingerprint": fingerprint} + payload = _native_result(base, head) + payload["comments"] = [dict(_PRIVATE, path=reviewed.path)] if filter_publication else [] + manifest = payload["manifest"] + manifest["execution"] = {"ocr_version": "v1.14.6"} + manifest["coverage"].update(selected=[record], completed=[record]) + manifest["input"]["source_artifact_sha256"] = gitlink_selection_proof(projection, selected)[ + "source_artifact_sha256" + ] + identity = replace(DEFAULT_IDENTITY, source_sha=head, diff_head_sha=head, diff_base_sha=base) + result = tmp_path / "result.json" + result.write_text(json.dumps(payload), encoding="utf-8") + + _, filtered, publication = review_runner._finalize_ocr_result( + result, + _COMPOSITION, + identity, + None, + SUMMARY_ACTION_COUNTS, + forbidden=(), + projection=projection, + selected_diff=selected, + excluded_diff=(PreviewExclusion(ignored, "gitignore"),), + ocr_exit_code=0, + ) + + assert filtered is filter_publication + if filtered: + assert publication["original"]["excluded"] == 1 + saved = json.loads(result.read_text(encoding="utf-8")) + receipt = saved[ocr_result.TOOLKIT_RESULT_KEY] + review_identity = validated_review_identity(receipt) + assert review_identity is not None + assert verified_review_coverage(saved, review_identity).state == "partial" + assert not evaluate_approval_policy( + BooleanSetting(True), parse_result_outcome(saved), [], [], 0, receipt + ).eligible + del saved[ocr_result.TOOLKIT_REVIEW_SELECTION_KEY] + with pytest.raises(RepositoryEvidenceError, match=r"omitted an immutable|proof is invalid"): + verified_review_coverage(saved, review_identity) + + +@pytest.mark.parametrize("remove_finding_path", [False, True]) +def test_manifest_identity_dlp_retains_only_bound_findings( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, remove_finding_path: bool +) -> None: + repo = tmp_path / "checkout" + repo.mkdir() + withheld_path = "src/fixture-context-only.py" + safe = dict(_SAFE, path="src/safe.py") + base, head = _ordinary_review_refs(repo, withheld_path, safe["path"]) + monkeypatch.chdir(repo) + reader = GitRepositoryReader(repo) + projection = make_gitlink_projection(reader, plan_review_input(reader, base, head)) + payload = _native_result(base, head) + payload["comments"] = [safe] + manifest = _bind_ordinary_native_manifest(payload, projection) + if remove_finding_path: + forbidden = withheld_path + payload["comments"].append(dict(_SAFE, path=withheld_path)) + else: + forbidden = manifest["coverage"]["selected"][0]["fingerprint"] + identity = replace(DEFAULT_IDENTITY, source_sha=head, diff_head_sha=head, diff_base_sha=base) + result = tmp_path / "result.json" + result.write_text(json.dumps(payload), encoding="utf-8") + + _, filtered, publication = review_runner._finalize_ocr_result( + result, + _COMPOSITION, + identity, + None, + SUMMARY_ACTION_COUNTS, + forbidden=(forbidden,), + projection=projection, + selected_diff=projection.ordinary_diff, + ocr_exit_code=0, + ) + + raw = result.read_text(encoding="utf-8") + saved = ocr_result.load_ocr_result(result) + assert filtered and "manifest" not in saved + assert publication["retained"]["comments"] == 1 + assert publication["omitted"]["comments"] == int(remove_finding_path) + assert publication["private_sanitization"]["reason_counts"]["forbidden"] > 0 + assert saved["comments"] == [safe] and forbidden not in raw + receipt = saved[ocr_result.TOOLKIT_RESULT_KEY] + review_identity = validated_review_identity(receipt) + assert review_identity is not None + assert verified_review_coverage(saved, review_identity).state == "complete" + assert not evaluate_approval_policy( + BooleanSetting(True), parse_result_outcome(saved), saved["comments"], [], 0, receipt + ).eligible + + +@pytest.mark.parametrize( + ("exclude_file", "include_safe"), ((False, True), (True, True), (False, False)) +) +def test_disabled_readback_keeps_private_git_identity_and_drops_redacted_anchors( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, exclude_file: bool, include_safe: bool +) -> None: + repo = tmp_path / "checkout" + repo.mkdir() + private_path = "src/password=synthetic-selected.py" + excluded_path = "src/password=synthetic-excluded.py" + safe_path = "src/safe.py" + base, head = _ordinary_review_refs(repo, private_path, excluded_path, safe_path) + monkeypatch.chdir(repo) + reader = GitRepositoryReader(repo) + projection = make_gitlink_projection(reader, plan_review_input(reader, base, head)) + excluded = next(entry for entry in projection.ordinary_diff if entry.path == excluded_path) + selected = tuple( + entry for entry in projection.ordinary_diff if not exclude_file or entry != excluded + ) + exclusion = (PreviewExclusion(excluded, "user_exclude"),) if exclude_file else () + safe_finding = dict(_SAFE, path=safe_path, line=1) + findings = [safe_finding] if include_safe else [] + private_findings = [dict(_SAFE, path=private_path)] + if not include_safe: + private_findings.append(dict(_SAFE, path=excluded_path)) + payload = _native_result(base, head) + payload["comments"] = [*findings, *private_findings] + payload["internal"] = "password=synthetic-provider-trace" + manifest = _bind_ordinary_native_manifest(payload, projection) + coverage = manifest["coverage"] + if exclude_file: + (excluded_record,) = [row for row in coverage["selected"] if row["path"] == excluded_path] + coverage["selected"].remove(excluded_record) + coverage["completed"].remove(excluded_record) + coverage["excluded"] = [ + { + "item_id": excluded_record["item_id"], + "path": excluded_path, + "exclude_reason": "user_exclude", + } + ] + manifest["input"]["source_artifact_sha256"] = gitlink_selection_proof(projection, selected)[ + "source_artifact_sha256" + ] + identity = replace( + DEFAULT_IDENTITY, + source_sha=head, + diff_head_sha=head, + diff_base_sha=base, + diff_start_sha=base, + policy_sha=base, + target_sha=base, + ) + result = tmp_path / "result.json" + result.write_text(json.dumps(payload), encoding="utf-8") + + _, filtered, publication = review_runner._finalize_ocr_result( + result, + _COMPOSITION, + identity, + None, + SUMMARY_ACTION_COUNTS, + forbidden=(), + dlp_enabled=False, + projection=projection, + selected_diff=selected, + excluded_diff=exclusion, + ocr_exit_code=0, + ) + + saved = ocr_result.load_ocr_result(result) + assert not filtered and publication["state"] == "disabled" + assert saved["comments"] == findings + assert ocr_result.readback_omitted_findings(saved) == len(private_findings) + assert ocr_result.readback_omitted_findings(json.loads(result.read_text())) == 0 + assert "synthetic-provider-trace" not in saved["internal"] + receipt = saved[ocr_result.TOOLKIT_RESULT_KEY] + review_identity = validated_review_identity(receipt) + assert review_identity is not None + assert verified_review_coverage(saved, review_identity).excluded == int(exclude_file) + assert not evaluate_approval_policy( + BooleanSetting(True), parse_result_outcome(saved), saved["comments"], [], 0, receipt + ).eligible + + bodies: list[str] = [] + deleted: list[int] = [] + previous = snapshot.BotCommentRefs( + plain_note_ids=[20, 21], + summary_plain_note_ids=[20], + discussion_note_refs=[("old-finding", 22)], + ) + monkeypatch.setenv("OCR_POST_MODE", "direct") + monkeypatch.setenv("OCR_AUTO_APPROVE", "true") + monkeypatch.setattr(workflow, "validate_review_freshness", lambda *_args: None) + monkeypatch.setattr(workflow, "collect_previous_bot_comment_refs", lambda _: previous) + monkeypatch.setattr(workflow, "finalize_posting", lambda *_args: True) + monkeypatch.setattr( + workflow, + "post_review_discussion", + lambda *_args, **kwargs: ( + bodies.append(kwargs["body"]) or gitlab.GitLabWriteResult("posted") + ), + ) + monkeypatch.setattr( + workflow, + "post_review_note_bounded", + lambda _cfg, title, body, _txn: bodies.append(title + body) or {"id": 30}, + ) + monkeypatch.setattr( + workflow.gitlab_api, "delete_plain_note", lambda _cfg, note: deleted.append(note) or True + ) + monkeypatch.setattr( + workflow.gitlab_api, + "delete_discussion_note", + lambda _cfg, _thread, note: deleted.append(note) or True, + ) + + assert workflow.post_results(gitlab_config(), saved) == 0 + assert len(bodies) == 1 + len(findings) + if include_safe: + assert safe_finding["content"] in bodies[0] + assert "1 finding published" in bodies[-1] + assert "1 finding withheld after location redaction" in bodies[-1] + else: + assert "no findings published; 2 findings withheld after location redaction" in bodies[-1] + assert ("OCR reported partial coverage" in bodies[-1]) is exclude_file + assert ( + "Review incomplete" if exclude_file else "Review complete; output incomplete" + ) in bodies[-1] + event = parse_publication(bodies[-1]) + assert event and event["outcome"] == "incomplete" + assert event["coverage"]["completed"] == len(selected) + assert event["posting"]["omitted"] == 0 + assert not any("synthetic-selected" in body or "synthetic-excluded" in body for body in bodies) + assert deleted == [20] + + tampered = json.loads(result.read_text()) + tampered["comments"][-1]["path"] = "src/password=synthetic-unselected.py" + result.write_text(json.dumps(tampered)) + with pytest.raises(ocr_result.OcrResultMalformed, match="outside native selected coverage"): + ocr_result.load_ocr_result(result) + + +def test_publication_journal_keeps_composition_rejections_value_free(tmp_path: Path) -> None: + composed = {"detail": "benign"} + payload = _native_result("b" * 40, "a" * 40) + payload["comments"].extend( + [ + {"path": "main.php", "line": 3, "content": composed}, + {"path": "main.php", "line": 4, "content": [None] * 32768}, + {"path": "main.php", "line": 5, "content": {"reasoning_content": "private trace"}}, + ] + ) + payload["request"] = { + "owner +1 202 555 0114": "private trace", + "extra": "owner@example.invalid", + } + debug = DebugBundle(tmp_path / "debug", other_outputs=()) + try: + projected, publication, filtered = review_runner._publication_projection( + payload, + forbidden=(ForbiddenValue(str(composed), "external_context"),), + allowed_tools=review_runner.PUBLIC_REVIEW_TOOL_CALL_NAMES, + debug=debug, + ) + finally: + debug.close() + + assert filtered and projected["comments"] == [_SAFE] + assert publication["reason_counts"]["limit"] == 1 + assert publication["source_attribution"]["counts"]["external_context"] == 1 + assert { + (tuple(decision["path"]), decision["reason"]) + for decision in debug.decisions + if decision["action"] == "reject-rendered-prose" + } == {(("comments", 1, "content"), "forbidden"), (("comments", 2, "content"), "limit")} + journal = json.dumps(debug.decisions) + for private in (str(composed), "202 555 0114", "owner@example.invalid", "private trace"): + assert private not in journal + + +@pytest.mark.parametrize("source_budget_exhausted", [False, True]) +def test_source_request_budget_never_waives_unproven_optional_code( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, source_budget_exhausted: bool +) -> None: + root = tmp_path / "source" + root.mkdir() + git(root, "init", "-q") + git(root, "commit", "--allow-empty", "-qm", "base") + base = git(root, "rev-parse", "HEAD") + existing = ("List value;", "") + path = "types.txt" + (root / path).write_text("\n".join(existing) + "\n", encoding="utf-8") + git(root, "add", path) + git(root, "commit", "-qm", "head") + head = git(root, "rev-parse", "HEAD") + monkeypatch.chdir(root) + if source_budget_exhausted: + monkeypatch.setattr(source_reader, "MAX_TEXT_SPANS", 1) + findings = [ + {"path": path, "line": line, "content": "Inspect the declaration."} for line in (1, 2) + ] + with_code = [ + {**finding, "existing_code": source} + for finding, source in zip(findings, existing, strict=True) + ] + payload = _native_result(base, head) + payload["comments"] = with_code + result = tmp_path / "result.json" + result.write_text(json.dumps(payload), encoding="utf-8") + + _, filtered, publication = review_runner._finalize_ocr_result( + result, + _COMPOSITION, + replace(LOCAL_IDENTITY, source_sha=head), + None, + SUMMARY_ACTION_COUNTS, + forbidden=(), + expected_range=ReviewRange(base, head), + ) + + assert filtered is source_budget_exhausted + assert json.loads(result.read_text(encoding="utf-8"))["comments"] == ( + findings if source_budget_exhausted else with_code + ) + if source_budget_exhausted: + assert publication["omitted"] == {"comments": 0, "warnings": 0, "fields": 2} + + +def test_disabled_dlp_still_excludes_native_failure_arguments_from_publication( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + payload = _native_result("b" * 40, "a" * 40) + payload["tool_calls"] = { + "total": 2, + "by_tool": {"ocr_toolkit_evidence": 1, "file_read": 1}, + "failure": 1, + "failure_by_tool": {"file_read": 1}, + "failure_details": [ + { + "tool_call_number": 2, + "tool_name": "file_read", + "file_path": "main.php", + "arguments": "private source arguments placeholder", + "error": "Source file unavailable", + } + ], + } + result = tmp_path / "result.json" + result.write_text(json.dumps(payload), encoding="utf-8") + + _, filtered, publication = review_runner._finalize_ocr_result( + result, + _COMPOSITION, + LOCAL_IDENTITY, + None, + SUMMARY_ACTION_COUNTS, + forbidden=(), + dlp_enabled=False, + ) + + saved = result.read_text(encoding="utf-8") + diagnostic = capsys.readouterr().err + assert not filtered and publication["state"] == "disabled" + assert json.loads(saved)["tool_calls"] == { + "total": 2, + "by_tool": {"ocr_toolkit_evidence": 1, "file_read": 1}, + "failure": 1, + } + assert "private source arguments placeholder" not in saved + diagnostic + assert "Source file unavailable" in diagnostic and "Source file unavailable" not in saved diff --git a/tests/test_review_runtime_cleanup.py b/tests/test_review_runtime_cleanup.py new file mode 100644 index 00000000..8cc4b3fa --- /dev/null +++ b/tests/test_review_runtime_cleanup.py @@ -0,0 +1,337 @@ +"""Verify cleanup and guarded retry at the local review process boundary.""" + +from __future__ import annotations + +import json +import os +import sys +from dataclasses import dataclass, replace +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from ocr_toolkit import review_runner +from ocr_toolkit.evidence.artifacts import repository_artifacts +from tests.test_evidence_repository import git +from tests.test_review_runner import LOCAL_IDENTITY + + +@dataclass(frozen=True) +class _ReviewPeer: + root: Path + binary: Path + base: str + head: str + result: Path + stderr: Path + report: Path + events: Path + home: Path + native_home: Path + + @property + def args(self) -> list[str]: + return ["--from", self.base, "--to", self.head] + + def run(self, **options) -> int: + return review_runner.run_evidence_review( + self.result, self.stderr, self.args, local=True, report_path=self.report, **options + ) + + def invocations(self) -> list[dict]: + return [json.loads(line) for line in self.events.read_text(encoding="utf-8").splitlines()] + + +@pytest.fixture +def review_peer(tmp_path, monkeypatch) -> _ReviewPeer: + root = tmp_path / "checkout" + root.mkdir() + git(root, "init", "-q") + (root / "ordinary.unknown").write_text("baseline\n", encoding="utf-8") + git(root, "add", ".") + git(root, "commit", "-qm", "base") + base = git(root, "rev-parse", "HEAD") + (root / "ordinary.unknown").write_text("next\n", encoding="utf-8") + git(root, "commit", "-qam", "head") + head = git(root, "rev-parse", "HEAD") + + home = tmp_path / "operator-home" + native_home = tmp_path / "operator-native-home" + for path in (home, native_home): + path.mkdir(mode=0o700) + (path / "untouched").write_text("operator state", encoding="utf-8") + for name in tuple(os.environ): + if name.startswith(("CI_", "GIT_", "OCR_")): + monkeypatch.delenv(name) + for name, value in { + "HOME": str(home), + "OCR_HOME": str(native_home), + "OCR_LLM_URL": "https://inference.example.invalid/v1", + "OCR_LLM_TOKEN": "synthetic-token", + "OCR_LLM_MODEL": "synthetic-model", + "OCR_LLM_PROTOCOL": "openai", + "OCR_TELEMETRY_ENABLED": "false", + "PATH": f"{tmp_path}{os.pathsep}{os.environ['PATH']}", + }.items(): + monkeypatch.setenv(name, value) + monkeypatch.chdir(root) + events = tmp_path / "calls.jsonl" + binary = tmp_path / "ocr" + binary.write_text( + f"#!{sys.executable}\n" + "import json, os, sys\n" + "from pathlib import Path\n" + "args = sys.argv[2:]\n" + f"with open({str(events)!r}, 'a', encoding='utf-8') as calls:\n" + " print(json.dumps({'args': args, 'home': os.environ['HOME'], " + "'native_home': os.environ.get('OCR_HOME')}), file=calls)\n" + "if '--preview' in args:\n" + " excluded = '--exclude' in args\n" + " if excluded and os.environ.get('SYNTHETIC_OCR_PREVIEW') == 'refused':\n" + " print('Error: background content is 81 characters, exceeding the hard " + "limit of 80 (aborting)', file=sys.stderr)\n" + " raise SystemExit(2)\n" + " print(json.dumps({'files': [], 'excluded': excluded}))\n" + " raise SystemExit(0)\n" + "scenario = os.environ.get('SYNTHETIC_OCR_RESUME', '')\n" + "if '--resume' in args and scenario in {'refused', 'partial', 'other'}:\n" + " if scenario == 'partial':\n" + " print('{\"status\":')\n" + " print('Error: resume rejected: incompatible inputs' if scenario != 'other' " + "else 'Error: provider unavailable', file=sys.stderr)\n" + " raise SystemExit(1)\n" + "if '--background-file' in args:\n" + " bootstrap = Path(args[args.index('--background-file') + 1])\n" + " assert bootstrap.is_file()\n" + " bootstrap.with_name('diagram.json').write_text('{}', encoding='utf-8')\n" + "print(json.dumps({'status': 'skipped', 'comments': [], 'warnings': [], " + "'message': 'No supported files changed.', 'tool_calls': {'total': 0, 'by_tool': {}}}))\n", + encoding="utf-8", + ) + binary.chmod(0o700) + return _ReviewPeer( + root, + binary, + base, + head, + tmp_path / "result.json", + tmp_path / "stderr.log", + tmp_path / "report.md", + events, + home, + native_home, + ) + + +@pytest.mark.parametrize("failure", ["evidence", "session", "optional-diagram"]) +def test_cleanup_failure_keeps_required_and_optional_ownership_distinct( + review_peer, monkeypatch, capsys, failure +): + peer = review_peer + artifacts = repository_artifacts(peer.root) + remove_artifact = review_runner.remove_private_artifact + remove_tree = review_runner.shutil.rmtree + injected = [] + + def remove(path): + removed = path.is_file() + remove_artifact(path) + if removed and (failure, path) in { + ("evidence", artifacts.store), + ("optional-diagram", artifacts.diagram), + }: + injected.append(path) + raise OSError("synthetic artifact cleanup error") + + def remove_directory(path, *args, **kwargs): + remove_tree(path, *args, **kwargs) + if failure == "session" and Path(path).name.startswith("ocr-toolkit-session-"): + injected.append(Path(path)) + raise OSError("synthetic session cleanup error") + + monkeypatch.setattr(review_runner, "remove_private_artifact", remove) + monkeypatch.setattr(review_runner.shutil, "rmtree", remove_directory) + peer.result.write_text("stale result", encoding="utf-8") + if failure == "optional-diagram": + assert peer.run() == 0 + assert json.loads(peer.result.read_text(encoding="utf-8"))["status"] == "skipped" + assert "Stopped at" not in peer.report.read_text(encoding="utf-8") + assert "diagram" in capsys.readouterr().err.lower() + assert injected == [artifacts.diagram] + else: + with pytest.raises(review_runner.ReviewRunnerError, match="private session cleanup failed"): + peer.run() + assert not peer.result.exists() + assert "Stopped at: `cleanup`." in peer.report.read_text(encoding="utf-8") + assert len(injected) == 1 + preview, execution = peer.invocations() + assert "--preview" in preview["args"] and "--preview" not in execution["args"] + assert preview["home"] == execution["home"] and not Path(execution["home"]).exists() + assert preview["native_home"] is None and execution["native_home"] is None + assert os.environ["HOME"] == str(peer.home) and os.environ["OCR_HOME"] == str(peer.native_home) + assert (peer.home / "untouched").read_text(encoding="utf-8") == "operator state" + assert (peer.native_home / "untouched").read_text(encoding="utf-8") == "operator state" + assert not artifacts.store.exists() and not artifacts.bootstrap.exists() + assert not artifacts.diagram.exists() + with review_runner.locked_review_run(artifacts): + assert artifacts.review_run_lock.is_file() + + +@pytest.mark.parametrize("destination", ["artifact", "console", "journal"]) +def test_reporting_fault_preserves_other_owner_outputs_and_releases_lock( + review_peer, tmp_path, monkeypatch, capsys, destination +): + peer = review_peer + debug = tmp_path / "debug" + if destination == "artifact": + + def fail_artifact(report, path, *_args): + assert report.failure_stage is None and path == peer.report + raise OSError("synthetic filesystem error") + + monkeypatch.setattr(review_runner, "publish_local_report", fail_artifact) + with pytest.raises(review_runner.ReviewRunnerError, match="report artifact output failed"): + peer.run(debug_dir=debug) + elif destination == "console": + + def fail_console(report, _stream): + assert report.failure_stage is None + raise BrokenPipeError("synthetic closed local consumer") + + monkeypatch.setattr(review_runner, "write_local_report", fail_console) + with pytest.raises(review_runner.ReviewRunnerError, match="local report output failed"): + peer.run(debug_dir=debug) + else: + flush = review_runner.DebugBundle.flush + + def fail_final_journal(bundle, *, complete=False): + if complete: + raise OSError("synthetic journal write error") + return flush(bundle, complete=complete) + + monkeypatch.setattr(review_runner.DebugBundle, "flush", fail_final_journal) + assert peer.run(debug_dir=debug) == 0 + + captured = capsys.readouterr() + journal = json.loads((debug / "journal.json").read_text(encoding="utf-8")) + assert journal["complete"] is (destination != "journal") + assert json.loads(peer.result.read_text(encoding="utf-8"))["status"] == "skipped" + assert (debug / "safe-result.json").read_bytes() == peer.result.read_bytes() + if destination == "artifact": + assert not peer.report.exists() + assert "Stopped at: `reporting`." in captured.out + assert "Stopped at: `reporting`." in (debug / "summary.md").read_text(encoding="utf-8") + else: + assert "Stopped at" not in peer.report.read_text(encoding="utf-8") + assert (debug / "summary.md").read_bytes() == peer.report.read_bytes() + if destination == "journal": + assert "Local debug journal output failed." in captured.err + with review_runner.locked_review_run(repository_artifacts(peer.root)): + assert all(not Path(call["home"]).exists() for call in peer.invocations()) + + +@pytest.mark.parametrize( + ("scenario", "expected_code", "attempts", "clear_prior"), + [ + ("refused", 0, [True, False], True), + ("partial", 1, [True], False), + ("other", 1, [True], False), + ("accepted", 0, [True], False), + ("checkpoint-read-error", 0, [False], True), + ], +) +def test_continuation_only_retries_after_proved_predispatch_refusal( + review_peer, tmp_path, monkeypatch, capsys, scenario, expected_code, attempts, clear_prior +): + peer = review_peer + monkeypatch.setenv("SYNTHETIC_OCR_RESUME", scenario) + session_home = tmp_path / "session" + session_home.mkdir(mode=0o700) + prior = object() + session_id = "00000000-0000-4000-8000-000000000001" + + def native_session(home): + assert home == session_home + if scenario == "checkpoint-read-error": + raise OSError("checkpoint became unreadable") + return session_id + + continuation = SimpleNamespace(prior=prior, native_session=native_session) + state = review_runner.ReviewRunState(local=True, continuation=continuation) + code, _preview = review_runner._run_background_qualified_review( + peer.result, + peer.stderr, + peer.args, + ocr_binary=str(peer.binary), + session_home=session_home, + artifacts=repository_artifacts(peer.root), + refs=review_runner.ReviewRefs(peer.base, peer.head), + identity=replace(LOCAL_IDENTITY, source_sha=peer.head, policy_sha=peer.base), + state=state, + ) + assert code == expected_code + preview, *executions = peer.invocations() + assert preview["args"] == [*peer.args, "--preview"] + assert [entry["args"] for entry in executions] == [ + [*peer.args, "--resume", session_id] if resume else peer.args for resume in attempts + ] + assert (continuation.prior is None) is clear_prior + assert ("Starting a full review" in capsys.readouterr().err) is clear_prior + if expected_code == 0: + assert json.loads(peer.result.read_text(encoding="utf-8"))["status"] == "skipped" + assert peer.stderr.read_bytes() == b"" + else: + assert bool(peer.result.read_bytes()) is (scenario == "partial") + + +@pytest.mark.parametrize("selection", ["confirmed", "mismatch", "refused"]) +def test_incremental_model_executes_only_the_confirmed_selection( + review_peer, tmp_path, monkeypatch, selection +): + peer = review_peer + session_home = tmp_path / "session" + session_home.mkdir(mode=0o700) + if selection == "refused": + monkeypatch.setenv("SYNTHETIC_OCR_PREVIEW", "refused") + narrowed = [*peer.args, "--exclude", "ordinary.unknown"] + confirmed = [] + + def select(stdout): + assert json.loads(stdout) == {"files": [], "excluded": False} + return narrowed + + def confirm(stdout): + confirmed.append(json.loads(stdout)) + return selection == "confirmed" + + incremental = SimpleNamespace( + reason="", + child_environment=dict(os.environ), + select=select, + confirm=confirm, + ) + code, preview = review_runner._run_background_qualified_review( + peer.result, + peer.stderr, + peer.args, + ocr_binary=str(peer.binary), + session_home=session_home, + artifacts=repository_artifacts(peer.root), + refs=review_runner.ReviewRefs(peer.base, peer.head), + identity=replace(LOCAL_IDENTITY, source_sha=peer.head, policy_sha=peer.base), + state=review_runner.ReviewRunState(local=True, incremental_session=incremental), + ) + assert code == 0 + model_args = narrowed if selection == "confirmed" else peer.args + assert [entry["args"] for entry in peer.invocations()] == [ + [*peer.args, "--preview"], + [*narrowed, "--preview"], + model_args, + ] + assert json.loads(preview.preview_stdout)["excluded"] is (selection == "confirmed") + assert confirmed == ([] if selection == "refused" else [{"files": [], "excluded": True}]) + assert ("narrowed native preview did not accept" in incremental.reason) is ( + selection == "refused" + ) + assert not list(session_home.iterdir()) diff --git a/tests/test_site_release_notify.py b/tests/test_site_release_notify.py index f3154ccf..f73bbfa4 100644 --- a/tests/test_site_release_notify.py +++ b/tests/test_site_release_notify.py @@ -2,6 +2,7 @@ from __future__ import annotations +import hashlib import json import os import subprocess @@ -16,7 +17,7 @@ def _verification_step() -> str: jobs = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))["jobs"] - steps = jobs["notify"]["steps"] + steps = jobs["verify"]["steps"] return next(step["run"] for step in steps if step.get("id") == "release") @@ -24,26 +25,75 @@ def test_site_dispatch_occurs_once_after_read_only_verification() -> None: jobs = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))["jobs"] steps = jobs["notify"]["steps"] assert "--method POST" not in _verification_step() + assert "OCR_SITE_DISPATCH_TOKEN" not in str(jobs["verify"]) + assert not any("uses" in step for job in jobs.values() for step in job["steps"]) + assert jobs["notify"]["environment"] == "site-release-notification" + assert jobs["notify"]["needs"] == "verify" + assert "needs.verify.outputs.release_tag != ''" in jobs["notify"]["if"] dispatch = next(step for step in steps if step.get("name") == "Request site refresh") - assert dispatch["if"] == "steps.release.outputs.release_tag != ''" assert dispatch["run"].count("--method POST") == 1 @pytest.mark.parametrize( - ("states", "duplicate", "expected_code", "expected_error", "expected_reads", "published"), + ("states", "overrides", "expected_code", "expected_error", "expected_reads", "published"), [ - (["in_progress", "success"], False, 0, "", 2, True), - (["in_progress"] * 6, False, 1, "remained unfinished", 6, False), - (["failure"], False, 1, "was not successful", 1, False), - (["skipped"], False, 0, "", 1, False), - (["invalid"], False, 1, "invalid status", 1, False), - (["success"], True, 1, "", 1, False), + (["in_progress", "success"], {}, 0, "", 2, True), + (["in_progress"] * 6, {}, 1, "remained unfinished", 6, False), + (["failure"], {}, 1, "was not successful", 1, False), + (["skipped"], {}, 0, "", 1, False), + (["invalid"], {}, 1, "invalid status", 1, False), + (["success"], {"duplicate": True}, 1, "", 1, False), + (["success"], {"job_attempt": 1}, 1, "", 1, False), + (["success"], {"omit_marker": True}, 1, "", 1, False), + ( + ["success"], + {"latest_tag": "v0.12.2"}, + 1, + "does not match the publication job tag", + 1, + False, + ), + (["success"], {"receipt_digest": "0" * 64}, 1, "digest does not match", 1, False), + (["success"], {"receipt_attempt": 1}, 1, "", 1, False), + (["success"], {"receipt_attempt": 1, "receipt_mode": "reused"}, 0, "", 1, True), + (["success"], {"receipt_attempt": 3, "receipt_mode": "reused"}, 1, "", 1, False), + ( + ["success"], + {"receipt_run": 39784500000, "receipt_attempt": 1, "receipt_mode": "reused"}, + 1, + "", + 1, + False, + ), + ( + ["success"], + { + "event": "workflow_dispatch", + "branch": "main", + "receipt_run": 39784500000, + "receipt_attempt": 1, + "receipt_mode": "reused", + }, + 0, + "", + 1, + True, + ), + ( + ["success"], + {"event": "workflow_dispatch", "branch": "dev"}, + 1, + "", + 1, + False, + ), + (["success"], {"reviewed_head": "3" * 40}, 1, "", 1, False), ], ) def test_release_job_readback_is_bounded_and_fail_closed( tmp_path: Path, states: list[str], - duplicate: bool, + overrides: dict[str, object], expected_code: int, expected_error: str, expected_reads: int, @@ -51,6 +101,53 @@ def test_release_job_readback_is_bounded_and_fail_closed( ) -> None: bin_dir = tmp_path / "bin" bin_dir.mkdir() + source_sha = "1" * 40 + merge_sha = "2" * 40 + run_id = 39784597413 + run_attempt = 2 + receipt = { + "schema_version": "ocr-toolkit.release-receipt/v2", + "tag": "v0.12.1", + "version": "0.12.1", + "workflow": { + "run_id": overrides.get("receipt_run", run_id), + "run_attempt": overrides.get("receipt_attempt", run_attempt), + }, + "reviewed": {"head": overrides.get("reviewed_head", source_sha), "merge": merge_sha}, + "github": {"annotated_tag_target": merge_sha}, + } + receipt_bytes = (json.dumps(receipt) + "\n").encode() + digest = overrides.get("receipt_digest", hashlib.sha256(receipt_bytes).hexdigest()) + mode = overrides.get("receipt_mode", "created") + marker = { + "name": f"Site release receipt v0.12.1 {digest} {mode}", + "status": "completed", + "conclusion": "success", + } + job = { + "name": "publish-github-release", + "run_id": run_id, + "run_attempt": overrides.get("job_attempt", run_attempt), + "head_sha": source_sha, + "steps": [] if overrides.get("omit_marker") else [marker], + } + latest = { + "immutable": True, + "draft": False, + "prerelease": False, + "published_at": "2026-10-22T13:21:49Z", + "tag_name": overrides.get("latest_tag", "v0.12.1"), + "assets": [ + { + "id": 123, + "name": "release-receipt.json", + "state": "uploaded", + "size": len(receipt_bytes), + } + ], + } + (tmp_path / "latest.json").write_text(json.dumps(latest)) + (tmp_path / "receipt.json").write_bytes(receipt_bytes) fake_gh = bin_dir / "gh" fake_gh.write_text( f"#!{sys.executable}\n" @@ -60,7 +157,7 @@ def test_release_job_readback_is_bounded_and_fail_closed( "request = sys.argv[-1]\n" "if request.endswith('/actions/workflows/release.yml'):\n" " value = {'id': 315030204, 'path': '.github/workflows/release.yml', 'state': 'active'}\n" - "elif '/attempts/1/jobs?' in request:\n" + "elif '/attempts/2/jobs?' in request:\n" " count_file = root / 'job-reads'\n" " count = int(count_file.read_text()) if count_file.exists() else 0\n" " count_file.write_text(str(count + 1))\n" @@ -68,20 +165,17 @@ def test_release_job_readback_is_bounded_and_fail_closed( " state = states[min(count, len(states) - 1)]\n" " status = 'completed' if state in ('success', 'failure', 'skipped') else state\n" " conclusion = state if status == 'completed' else None\n" - " value = {'total_count': 1, 'jobs': [{'name': 'publish-github-release', " - "'status': status, 'conclusion': conclusion}]}\n" + " job = json.loads(os.environ['FAKE_JOB'])\n" + " job.update(status=status, conclusion=conclusion)\n" + " value = {'total_count': 1, 'jobs': [job]}\n" " if os.environ['FAKE_DUPLICATE_JOB'] == '1':\n" " value['jobs'].append(value['jobs'][0].copy())\n" " value['total_count'] = 2\n" "elif request.endswith('/releases/latest'):\n" - " value = {'immutable': True, 'draft': False, 'prerelease': False, " - "'published_at': '2026-10-22T13:21:49Z', 'tag_name': 'v0.12.1', " - "'assets': [{'id': 123, 'name': 'release-receipt.json', 'state': 'uploaded', " - "'size': 100}]}\n" + " value = json.loads((root / 'latest.json').read_text())\n" "elif request.endswith('/releases/assets/123'):\n" - " value = {'schema_version': 'ocr-toolkit.release-receipt/v2', " - "'tag': 'v0.12.1', 'version': '0.12.1', " - "'workflow': {'run_id': 39784597413, 'run_attempt': 1}}\n" + " sys.stdout.buffer.write((root / 'receipt.json').read_bytes())\n" + " raise SystemExit(0)\n" "else:\n" " raise SystemExit('unexpected GitHub request')\n" "print(json.dumps(value))\n", @@ -97,12 +191,16 @@ def test_release_job_readback_is_bounded_and_fail_closed( "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}", "FAKE_STATE_DIR": str(tmp_path), "FAKE_JOB_STATES": json.dumps(states), - "FAKE_DUPLICATE_JOB": "1" if duplicate else "0", + "FAKE_JOB": json.dumps(job), + "FAKE_DUPLICATE_JOB": "1" if overrides.get("duplicate") else "0", "GH_TOKEN": "synthetic-token", "GITHUB_REPOSITORY": "xeonvs/open-code-review-toolkit", - "SOURCE_RUN_ID": "39784597413", - "SOURCE_RUN_ATTEMPT": "1", + "SOURCE_RUN_ID": str(run_id), + "SOURCE_RUN_ATTEMPT": str(run_attempt), "SOURCE_WORKFLOW_ID": "315030204", + "SOURCE_HEAD_SHA": source_sha, + "SOURCE_EVENT": str(overrides.get("event", "pull_request")), + "SOURCE_HEAD_BRANCH": str(overrides.get("branch", "release/v0.12.1")), "RUNNER_TEMP": str(tmp_path), "GITHUB_OUTPUT": str(output), } diff --git a/tests/test_telemetry_metrics.py b/tests/test_telemetry_metrics.py index d1e86adc..76958c85 100644 --- a/tests/test_telemetry_metrics.py +++ b/tests/test_telemetry_metrics.py @@ -26,6 +26,21 @@ def handle_starttag(self, tag, attrs): self.links.append(dict(attrs)["href"]) +def test_rendered_coverage_exclusions_reach_technical_totals(): + note = summarize_result( + 0, + 0, + 0, + 0, + outcome_status="partial", + coverage_summary="Coverage: selected 1; completed 1; reused 0; failed 0; waived 0; excluded 2.", + ) + publication = parse_publication(build_marked_note_body(summary_with_run_marker(note, "a" * 32))) + assert publication and publication["coverage"]["excluded"] == 2 + totals = technical_summary([publication], {}, prices={}, costs=False)["counts"] + assert totals["coverage"]["excluded"] == 2 + + def _snapshot(): parsed = parse_publication( "## Open Code Review\n\n" diff --git a/tests/test_telemetry_publications.py b/tests/test_telemetry_publications.py index 26d6762a..776812fe 100644 --- a/tests/test_telemetry_publications.py +++ b/tests/test_telemetry_publications.py @@ -509,6 +509,28 @@ def test_historical_run_labels_and_visible_technical_lines_are_read_without_iden assert "historic_synthetic" not in json.dumps(result) +@pytest.mark.parametrize("excluded", (1, 10_000, 10_001)) +def test_excluded_coverage_remains_visible_to_publication_telemetry(excluded): + note = ( + "## Open Code Review\n\n" + "**Review incomplete — no findings published**\n\n" + f"- Coverage: selected 1; completed 1; reused 0; failed 0; waived 0; excluded {excluded}.\n" + ) + result = parse_publication(note) + assert result and result["recognized"] + if excluded > 10_000: + assert not result["coverage"] + return + assert result["coverage"] == { + "selected": 1, + "completed": 1, + "reused": 0, + "failed": 0, + "waived": 0, + "excluded": excluded, + } + + def test_current_repository_coverage_and_protected_fallback_remain_distinct(): from ocr_toolkit.repository_coverage import RepositoryCoverage, repository_coverage_summary diff --git a/tests/test_testpypi_preview.py b/tests/test_testpypi_preview.py index d39c2be2..44e39623 100644 --- a/tests/test_testpypi_preview.py +++ b/tests/test_testpypi_preview.py @@ -333,7 +333,7 @@ def test_distribution_build_is_a_bounded_pull_request_gate() -> None: pull_request_block = workflow.split(" pull_request:", 1)[1].split("\n\npermissions:", 1)[0] assert "pull_request:" in workflow - assert "branches: [main]" in workflow + assert "branches: [main, dev]" in pull_request_block assert " push:" not in workflow assert "paths:" not in pull_request_block assert "timeout-minutes: 15" in workflow @@ -352,7 +352,7 @@ def test_ci_matrix_covers_supported_python_minors_and_os_boundaries() -> None: assert " push:" not in workflow assert "continue-on-error: ${{ matrix.advisory }}" in workflow assert "test-python312:" in workflow - assert "name: test-ubuntu-latest-py3.12" in workflow + assert "|| 'test-ubuntu-latest-py3.12' }}" in workflow assert " test-matrix:\n needs: classify" in workflow assert workflow.count("--ignore=tests/test_installed_policy_e2e.py") == 2 assert "run: uv run --no-sync pytest -q\n" in workflow diff --git a/uv.lock b/uv.lock index 596c12ad..e93894c2 100644 --- a/uv.lock +++ b/uv.lock @@ -160,11 +160,11 @@ filecache = [ [[package]] name = "certifi" -version = "2026.10.23" +version = "2026.11.20" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } +sdist = { url = "https://files.pythonhosted.org/packages/51/33/4cd27639502f010084bcef7a2036391dd637439901341ce1a530f36f6e51/certifi-2026.11.20.tar.gz", hash = "sha256:af1cb240a8133f105aa52684a3a3258339d7f2fd0bd4e2812698ff5cf5588c4e", size = 128901, upload-time = "2026-11-20T23:37:49.522Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, + { url = "https://files.pythonhosted.org/packages/6d/39/5eec3296860b94ac20bb8ed807725b88f6adfab3f343df592afd975f5f86/certifi-2026.11.20-py3-none-any.whl", hash = "sha256:7422df25243767b9877031a2248cb14d09ddac9beee846f4cef3d5c9191d488f", size = 127913, upload-time = "2026-11-20T23:37:48.117Z" }, ] [[package]] @@ -667,20 +667,20 @@ wheels = [ [[package]] name = "httpcore2" -version = "2.16.0" +version = "2.16.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "h11" }, { name = "truststore" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/c0/61/afa9d6b7452f9eca73f73d45324eb0bb52f098fd5e6049bf6b8263be9b4e/httpcore2-2.16.0.tar.gz", hash = "sha256:c72cd0413563b17e1cd8354677dff887466f8ec2551679759e93126534428643", size = 69886, upload-time = "2026-10-21T07:09:45.31Z" } +sdist = { url = "https://files.pythonhosted.org/packages/92/9d/df40b41f7db0370f82019820709244e7b660c52aa3da3c9e5c4e8141f6e6/httpcore2-2.16.2.tar.gz", hash = "sha256:6c519d0f7b44f7269fa9bbb4d2763db395a4a2370f046d8e8e0a4b38227815d2", size = 70064, upload-time = "2026-11-16T10:12:19.491Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/af/c2/ce417c397afa5181f0e3c6ff01a4d01639414e1adef08730d97571297151/httpcore2-2.16.0-py3-none-any.whl", hash = "sha256:5c4358319f2602d984ad93182c9fee5160f22e9da7babdda870a5e7c4e2dc34f", size = 85070, upload-time = "2026-10-21T07:09:42.802Z" }, + { url = "https://files.pythonhosted.org/packages/2a/e8/009c347feac27f8960605aa98d55ed263b5870dd4fd80b82fd1d00d5716c/httpcore2-2.16.2-py3-none-any.whl", hash = "sha256:16051ae2a42f776007543f32de9349a317b23d2cbb4e1456b4bac0e88b87419a", size = 85551, upload-time = "2026-11-16T10:12:16.674Z" }, ] [[package]] name = "httpx2" -version = "2.16.0" +version = "2.16.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio", marker = "sys_platform != 'emscripten'" }, @@ -690,9 +690,9 @@ dependencies = [ { name = "truststore", marker = "sys_platform != 'emscripten'" }, { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/43/73/5ca2cedf5e4e50423d1c258877865a6b62793633b561c58499f8aeb33b7e/httpx2-2.16.0.tar.gz", hash = "sha256:0d54c98128e8f2ff7fbbde0fca8c359e5f032edeaaaac443cdb7f31f685bcd7f", size = 103116, upload-time = "2026-10-21T07:09:46.348Z" } +sdist = { url = "https://files.pythonhosted.org/packages/1c/77/6515121dc5ac3c743ad1bff5afe635bcd1a3f23cc40db3c5c89f7d02917d/httpx2-2.16.2.tar.gz", hash = "sha256:748b615678f07d8e3b183efe81ad13b655ca88bfc56ce4589219b2d442860574", size = 103370, upload-time = "2026-11-16T10:12:20.49Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7b/3d/2e4bc4fd1ef9770871669adb348d612a6e4786b303a23f9935b81c48dd60/httpx2-2.16.0-py3-none-any.whl", hash = "sha256:fd2c5d7909e8d86fe92d53020c310ca0e4e431b838c207c5754b9bbf0308d49a", size = 97880, upload-time = "2026-10-21T07:09:44.01Z" }, + { url = "https://files.pythonhosted.org/packages/77/de/8c4306a3d6aa2495111986addf33a9e561eff4c47552e4c4b9251160d0ad/httpx2-2.16.2-py3-none-any.whl", hash = "sha256:f05c13aade4c45dbf1c9060647a1058f0acad62398fad96e741269edb33d46f5", size = 97893, upload-time = "2026-11-16T10:12:18.192Z" }, ] [[package]] @@ -706,83 +706,83 @@ wheels = [ [[package]] name = "hypothesis" -version = "6.170.15" +version = "6.170.23" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "sortedcontainers" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/96/ec/59f14eb701087710888b66bfef2dc8bee9dd4a364c69a732db0cc1d3d2dc/hypothesis-6.170.15.tar.gz", hash = "sha256:a4a57e5fb106ecb29cad37e22e411d957e20d933bfb9fb029e1999b1deb8a0b6", size = 521997, upload-time = "2026-11-06T09:54:57.339Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/84/cf/3b56a81685915f6bf0d67b3a6c1139fd9bd4583066161823834e42b9eaa7/hypothesis-6.170.15-cp311-abi3-macosx_10_12_x86_64.whl", hash = "sha256:db8211e0a56fa29bf9e5d9ff9cd969a91ff4e5ffa8fb4983d3dd788253aeee2c", size = 800537, upload-time = "2026-11-06T09:53:36.823Z" }, - { url = "https://files.pythonhosted.org/packages/b6/09/477b3233cca8c447a6dc5fcc076a7294a4fdacb615d960695f6970d706dc/hypothesis-6.170.15-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:34e0859a53f20200f39db3f9cd92112eb6034c31dc670e88d56d8725f453562d", size = 795693, upload-time = "2026-11-06T09:54:14.601Z" }, - { url = "https://files.pythonhosted.org/packages/7c/7a/34e042f1545472abe29ecf9eebac6f748096580f6fb831817f097addbe29/hypothesis-6.170.15-cp311-abi3-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:5c5980821384206939c1c9d519b7adfb80b54d07e669ab0d36fe877f08cff07a", size = 1162432, upload-time = "2026-11-06T09:53:55.461Z" }, - { url = "https://files.pythonhosted.org/packages/3a/7f/95b7b04d2b7e45669db446ee10d97f5d04b143bba380559a7f3a7e0c5b1f/hypothesis-6.170.15-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f29339b5cd4c2a221885e8b7ddbd447b4dc7ee14f763a6f5aaff726d4d3fd5ed", size = 1124598, upload-time = "2026-11-06T09:54:26.015Z" }, - { url = "https://files.pythonhosted.org/packages/33/8e/896172d9706bfe2e09c9154fecb11c7b76e50014442783dd9d5b404c8c84/hypothesis-6.170.15-cp311-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:d836a61c3dd94c6fc4677f4d0d95d30b92eb0ceab6f2b5c58e35c32545583170", size = 1155097, upload-time = "2026-11-06T09:54:47.123Z" }, - { url = "https://files.pythonhosted.org/packages/29/33/b8791c6a9b4232c3cc8f592d3e36175bcb4bad6203f7e461db0a4f5fa11b/hypothesis-6.170.15-cp311-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:d18ffd069360589a66ed125db62f12b490b3b9f6d47e5fd2505f1089d63a0f17", size = 1148988, upload-time = "2026-11-06T09:54:33.101Z" }, - { url = "https://files.pythonhosted.org/packages/87/2c/3ee87dd6fdec16ce55a4aeb5f72ae24756855cdc4ee87637fb68c4daeadc/hypothesis-6.170.15-cp311-abi3-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:7636424c7b1477fdd279fce5a210b67687a3024ac7759fe2e46a767a76f8761c", size = 1201778, upload-time = "2026-11-06T09:53:49.736Z" }, - { url = "https://files.pythonhosted.org/packages/6b/6a/f2757fde7d1b3b5dda6df3441d346b59c60627f2c216d966739289149903/hypothesis-6.170.15-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:99a1a4711b5276e5bfc3aa0cca034d0e45f8696a46ac8dce008308f580c18234", size = 1168007, upload-time = "2026-11-06T09:54:34.331Z" }, - { url = "https://files.pythonhosted.org/packages/8d/79/b6ff2a2840e4bcdea5c4cf1bcdd3803954a632beec16cb9d77a9ee8ddbb8/hypothesis-6.170.15-cp311-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:f545a04342a53008fa696a0592f0a026278ee61fab04f3e9e395d0c7eba42fef", size = 1124154, upload-time = "2026-11-06T09:53:24.354Z" }, - { url = "https://files.pythonhosted.org/packages/52/d0/19bc4a98e9583936dbe6e754014ad1133d3a43c9068a880c4e91ce384fad/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1f11d685322a56ee73c2a7566ec9d1195740313c3b965bad3121c340ec0e657b", size = 1299503, upload-time = "2026-11-06T09:53:12.86Z" }, - { url = "https://files.pythonhosted.org/packages/ee/06/fad2d1546c08eb4133f9478716bf6bc5f881e0d06b5b4f1faf34fd515a5a/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:f6d5d34fa6b56f236ad9659043123efb85391a8a5640f067c9de82b0be0bff73", size = 1428191, upload-time = "2026-11-06T09:54:44.43Z" }, - { url = "https://files.pythonhosted.org/packages/ca/cd/71d43284cca9c5145ceae04ddac1adfc57e9da57cf8efd30c0876844c9bf/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_i686.whl", hash = "sha256:2ff9983a58647b03754fa3d1005e59a9c563e15256340fc062b4a34c7969d52a", size = 1382322, upload-time = "2026-11-06T09:54:06.405Z" }, - { url = "https://files.pythonhosted.org/packages/0f/56/5754189cd709d4eb34601f8ebb57f1d2381b2dd74f62352ba6b84bce4a12/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:6e461d7b392a630593134611ebb1fce6baba88dbbf4f07661a37ff58ff4e1b6a", size = 1278225, upload-time = "2026-11-06T09:52:59.772Z" }, - { url = "https://files.pythonhosted.org/packages/7e/a9/5224ea74356981f01222c42f0acc55821fb5aadf3f1f15adc797c7eefbd2/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:62c0675a837bbe0f3f7c7a89b701bee159759840c23b9bec9d565d3434fb0b3a", size = 1294018, upload-time = "2026-11-06T09:54:29.127Z" }, - { url = "https://files.pythonhosted.org/packages/9d/c5/297f16660b15eacb2872af9fb127e7fe83f48f6f9caf223cb5abd5a25bd8/hypothesis-6.170.15-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:124b0b9962ff6b25786692b7b6cb0065f8bb7870081ddd9baf4745b0ff4a5c7a", size = 1333737, upload-time = "2026-11-06T09:54:03.427Z" }, - { url = "https://files.pythonhosted.org/packages/19/18/7e35ba1bc1f0e3ec55d9d97864db42b5ffeea92766ae4bd7ced0f77cc930/hypothesis-6.170.15-cp311-abi3-win32.whl", hash = "sha256:d34e54f485777eb217c85c425ddbe7b278ef56540feedb5de4097a5abc9f5719", size = 687717, upload-time = "2026-11-06T09:54:40.259Z" }, - { url = "https://files.pythonhosted.org/packages/fa/d6/c16f5abdb56baa2d401de38c2f758090796c1716fed9aa690179772e6adf/hypothesis-6.170.15-cp311-abi3-win_amd64.whl", hash = "sha256:de9fe573a4955b0cf0354822fbfe9b79882e8de02f26287313fe1ad47ba3e69f", size = 693782, upload-time = "2026-11-06T09:53:17.157Z" }, - { url = "https://files.pythonhosted.org/packages/13/7a/ae3b7fdd44c30b662f27344ccb810d080d11b7f557c2cffa88d01e677295/hypothesis-6.170.15-cp311-abi3-win_arm64.whl", hash = "sha256:de5e11c568fd411a3cf07e4e34d4f8cf07d638de2f254c8bd87c1879679cdd9a", size = 692109, upload-time = "2026-11-06T09:53:52.599Z" }, - { url = "https://files.pythonhosted.org/packages/91/db/84d418c965fe889d21e7791f946f7c893bf492bcedb38f3f5b8eb405a035/hypothesis-6.170.15-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:29223a2d180e463f1205b7e5eb397db0c4827de06f2ae571b00c392d355c410e", size = 802327, upload-time = "2026-11-06T09:54:20.994Z" }, - { url = "https://files.pythonhosted.org/packages/9d/8f/63d8644162728ba8b2c8a8a8b6a34476663c964cc0f6885c19f84ead40d6/hypothesis-6.170.15-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7953ad8f123b4289801b833666aaab757ba52e91ed687d954eb26f4af7328e5b", size = 794302, upload-time = "2026-11-06T09:54:24.828Z" }, - { url = "https://files.pythonhosted.org/packages/ec/2e/d479c69c08d5aabd7e6499f3dddc22b241db42922d746d05df9548213229/hypothesis-6.170.15-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b1f37920547eafa77814bc9b638e47299562123023bdf3c9cb002795bb90fc92", size = 1123978, upload-time = "2026-11-06T09:54:36.215Z" }, - { url = "https://files.pythonhosted.org/packages/ee/e2/824c524d04152e5c26111247d2d4dbf210d43df7c6612f7ff22c20de5abc/hypothesis-6.170.15-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e9e20ec17d2095e9314ea232b4e34b5510def0d9e7a7e764cc70cae88fe4b0c4", size = 1167677, upload-time = "2026-11-06T09:54:55.123Z" }, - { url = "https://files.pythonhosted.org/packages/ce/49/4aab201f1fd0109560d985076a4c852c1abda14984470369bf29ea89ade3/hypothesis-6.170.15-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:11c541cf103c784306f6037e5ab962cbe3d5891d36fd98df993f38d7ddbcd360", size = 1298862, upload-time = "2026-11-06T09:53:51.237Z" }, - { url = "https://files.pythonhosted.org/packages/db/a7/83fc4ef9484deefd955949a9a72a14d9435b6ace339feb27de25bf286e29/hypothesis-6.170.15-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:eecdcd38395facf6ea3af90320a574f5e63c310c194d2a0eb75f121223942386", size = 1333300, upload-time = "2026-11-06T09:53:39.58Z" }, - { url = "https://files.pythonhosted.org/packages/d5/18/5f1a5ce07a9e6b7a2cbfb6a8bceb9b5161de5477abb8d99d659a898b7554/hypothesis-6.170.15-cp312-cp312-win_amd64.whl", hash = "sha256:7dfb3d92df4faa67d3c975d1ecdefabc5a2481b789048f52cd5fb775c6c517b8", size = 691422, upload-time = "2026-11-06T09:54:05.043Z" }, - { url = "https://files.pythonhosted.org/packages/16/16/d75485989f250dd5017d1627902961c2f985686355f50d10170a2490d970/hypothesis-6.170.15-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:e3f478d4d9e13d528e352a4d938dea10b25793663ac752d774d7d35b008a1b45", size = 802290, upload-time = "2026-11-06T09:53:33.892Z" }, - { url = "https://files.pythonhosted.org/packages/24/45/54e42ac718e1164090c04b588024e4818a8e2a28b9002faa21e9fd59ab67/hypothesis-6.170.15-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:9c92af3f0c8844d9eba793a4371035a45e88bb59579a1408ce5d3cceb9e2b1da", size = 794293, upload-time = "2026-11-06T09:54:09.14Z" }, - { url = "https://files.pythonhosted.org/packages/b8/ee/1a81a7d544e321165159a07e666f6c302ec109beccca3b37f8d0de54e0cd/hypothesis-6.170.15-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:dce4d989f6b9c0a589b944591f13de3dff34e186c14401e11b819fed81d70a5b", size = 1123881, upload-time = "2026-11-06T09:53:01.454Z" }, - { url = "https://files.pythonhosted.org/packages/c9/07/4d506b2e37601ec8b38a0c4b8f547dd344bd8eccd577dbd0543a744fce03/hypothesis-6.170.15-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f25261d1656f830a78863844be5fb55cd0208154dc9ddec85d44fe691488c557", size = 1167605, upload-time = "2026-11-06T09:53:32.309Z" }, - { url = "https://files.pythonhosted.org/packages/a5/77/a88824d02272f149870e36aaad0197dc5a186f53a1896ea3117f250b8414/hypothesis-6.170.15-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5ae92fa40b57c1cd331d63fe6f95aecfdb6aa32f15b4c418c108c41fcd4aef84", size = 1298841, upload-time = "2026-11-06T09:53:15.809Z" }, - { url = "https://files.pythonhosted.org/packages/68/b9/6e1b55b6b32926cebb7ef37076d8fda9d0f87045e90e4b75e93eeb9a56ac/hypothesis-6.170.15-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b829dc3cbd73fe08c02151afc438448180907da62c154cfa68abd178eafd4d48", size = 1333319, upload-time = "2026-11-06T09:52:57.279Z" }, - { url = "https://files.pythonhosted.org/packages/c8/77/7d2009c663eb26b329c622091f7593ee6c90eac663f389fdf7311d44b035/hypothesis-6.170.15-cp313-cp313-win_amd64.whl", hash = "sha256:1f7ede44b875dddd8f3e7562e6702c363e82c6fb680b0fe079536bae662987f8", size = 691393, upload-time = "2026-11-06T09:54:56.287Z" }, - { url = "https://files.pythonhosted.org/packages/96/85/977d43b789fe4ca530e76020bbd2db07a9af3c17a4bf27a276416b6540e5/hypothesis-6.170.15-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:ffac67d06f765fd000a132e71117ee92dbd59863cea18403220ca4e39b50397f", size = 802549, upload-time = "2026-11-06T09:54:17.455Z" }, - { url = "https://files.pythonhosted.org/packages/cb/1a/51e637155a8c897774463389f1341ec8d466a9860cf5e004689866c557b2/hypothesis-6.170.15-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:82b613ee882068e781d810eb73a8195b59edd6cc47e8acbe4971562044a99c83", size = 794333, upload-time = "2026-11-06T09:54:27.915Z" }, - { url = "https://files.pythonhosted.org/packages/24/c1/ea255465b482ba5fc5f678e4347d6c6bbe878c827ca652d634328be96534/hypothesis-6.170.15-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:eb6fe3d1cb91d4f14fd307f10ae969ef7e866c16e4010a750d1cade145dfd764", size = 1124402, upload-time = "2026-11-06T09:53:02.773Z" }, - { url = "https://files.pythonhosted.org/packages/7a/69/32a05f0ae41f699f30ff872be74fe46ee1d45ead7abfb114afe3a4b4a3ee/hypothesis-6.170.15-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f91f27a89e8d55c7f043cb1e10705096236d4f7bcb35f3ac4f821e0c9b9bcd05", size = 1167795, upload-time = "2026-11-06T09:54:00.357Z" }, - { url = "https://files.pythonhosted.org/packages/c2/fb/c16886cea3a7ae3045093480775eb058eed549f41aa0e21a8d96aa7d51b1/hypothesis-6.170.15-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e0e4ab687c0f2bd62b7963dc8c3c8d29211cdc6db7ce05d37ef2a20d21219c18", size = 1299361, upload-time = "2026-11-06T09:53:04.441Z" }, - { url = "https://files.pythonhosted.org/packages/b7/f3/ad57518f76503276c896388affeccca1ffb1cccc529d063dac588c4bb652/hypothesis-6.170.15-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:b01d130c103fdf78a4a748cae7d095edfe5d37534828413a509936fb3567db61", size = 1333515, upload-time = "2026-11-06T09:53:18.642Z" }, - { url = "https://files.pythonhosted.org/packages/2b/08/500fbe05990d886d4502fa334f6cf03607be473b2a2efffb660238135f05/hypothesis-6.170.15-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:1138c03edf4c4401afb28e50255644b4ab4e1ad52864456cd4e84458ba8c671a", size = 634104, upload-time = "2026-11-06T09:54:22.317Z" }, - { url = "https://files.pythonhosted.org/packages/41/53/11e3260a72024f41246061ad204627f8336bfbf0ec2b180648d01a05491f/hypothesis-6.170.15-cp314-cp314-win_amd64.whl", hash = "sha256:57ae2617424f5bb55af0146b47e0aff64a9d6677a4d5216cf2a66bd3bda0d457", size = 691115, upload-time = "2026-11-06T09:53:41.223Z" }, - { url = "https://files.pythonhosted.org/packages/ba/41/655fca0f45b7ea6df6b5bb70ab52b740cc6bc30b971366036eddd36a77c9/hypothesis-6.170.15-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:c0514f3f8ab5d56103b756317dedc8476945b0633e51112312247e3caecd0eb2", size = 800640, upload-time = "2026-11-06T09:53:05.61Z" }, - { url = "https://files.pythonhosted.org/packages/a5/89/6bf52da8b15846c7263eac9fcffb89cc1d1c82f96ca5b839a0d00bb3aa3a/hypothesis-6.170.15-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:cc5434cde3b22c900dfe01f891804b48f6e2aa93e891ca98a14c07dd04fa6d54", size = 792915, upload-time = "2026-11-06T09:53:11.508Z" }, - { url = "https://files.pythonhosted.org/packages/11/f9/a0c2a356c7a3a4b65ec2f80382c9ea5acc1a86247ac64ecb1b7dfc38ee95/hypothesis-6.170.15-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f22900eec7df2696073c05f60c666654eaa93f17aebe8964f751d75b131dcd90", size = 1122841, upload-time = "2026-11-06T09:53:21.626Z" }, - { url = "https://files.pythonhosted.org/packages/ef/f1/d4fa867fae5a733e4041720622417804bcfb79c00d265c5451243a5aba20/hypothesis-6.170.15-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7288412dfba6b5a6f875279a25409eda6b25d097c26ea710540f904287c55d06", size = 1166715, upload-time = "2026-11-06T09:54:42.908Z" }, - { url = "https://files.pythonhosted.org/packages/04/5d/cbf8acf14caa5a2e4d34dd088a507cc84da49a660b6f532104d8afdb2903/hypothesis-6.170.15-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7d546a5d6a5549a6b34304f7315d20aff7afd206996592329877da529b9d9153", size = 1297608, upload-time = "2026-11-06T09:53:29.22Z" }, - { url = "https://files.pythonhosted.org/packages/9c/a0/912a0ebf3ab19b39235233f9e1664147f6e842aa6915828d68c1d1e13f27/hypothesis-6.170.15-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:bd8b36d0403eff6473686c0e4d8b7704780ebf548b0b2cc86cb9cbbbe64f8c2f", size = 1332521, upload-time = "2026-11-06T09:53:47.664Z" }, - { url = "https://files.pythonhosted.org/packages/37/36/d9286c792272651db4059a3497a19cc7f4f60e0452c862274d506b0132fd/hypothesis-6.170.15-cp314-cp314t-win_amd64.whl", hash = "sha256:67eb006925a3a49ddc4a48d9af8314349291a7eee9b2baea6beb93bc48211ead", size = 691229, upload-time = "2026-11-06T09:54:45.888Z" }, - { url = "https://files.pythonhosted.org/packages/91/42/b152b66db2061b47ff928efc7162c2dcf4591d92dab19b3c574af3552220/hypothesis-6.170.15-cp315-abi3.abi3t-macosx_10_12_x86_64.whl", hash = "sha256:e007ff1dfb8bfa228b97ed6695325cfa1ba6487c7e1175c884e8795e71fb41a5", size = 800291, upload-time = "2026-11-06T09:54:07.899Z" }, - { url = "https://files.pythonhosted.org/packages/67/6f/49fe04f0b4cfd142d474e08a1855ea093c7367e6ff33e7c5d4a64592f743/hypothesis-6.170.15-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:742846b0e2e31640acf8bba7c2b8b6eb9cecd6817a906af6d4b5ced9db697660", size = 792763, upload-time = "2026-11-06T09:54:51.025Z" }, - { url = "https://files.pythonhosted.org/packages/88/e6/61ec7fb3b84dd8d8644d6a322d5dba4501e2f32d0b10b8b5467e7d6defd4/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:508488dd4e92e03ecd16ea086f33d766855ed1febd322a439ec231c920b1740a", size = 1158761, upload-time = "2026-11-06T09:54:02.105Z" }, - { url = "https://files.pythonhosted.org/packages/8d/ae/c9eb63eb1b2d935551494aa42ecf91bb214d89c52631854dfbb09ccb6d39/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ccc6a9ce18dced7f0d2cba36f334f44697c1c6e692949c1bbd0bc67a7065c86a", size = 1121659, upload-time = "2026-11-06T09:54:12.041Z" }, - { url = "https://files.pythonhosted.org/packages/0a/44/b99e644480a31153de52489dc4c062df5f82a10fbb2b699d0f17ecb08171/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:b8a0b5b3e21a1d2e235f42a813fbf04872196ad53151fdd4cfe02723db699f8d", size = 1152560, upload-time = "2026-11-06T09:54:41.478Z" }, - { url = "https://files.pythonhosted.org/packages/f8/0a/bfc1c697f34e395d635f49d2a29f1bfc41a0eccdcf9fba32fb33601325de/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:b59187094929ce6d5351a6f92e7f3831cd463fe69591def6ebd0023a3073af2e", size = 1146287, upload-time = "2026-11-06T09:53:42.894Z" }, - { url = "https://files.pythonhosted.org/packages/bb/69/90fac02af55ccbea1d1b3bbc72512c4f998e3fabc6b375c8c0afd0e6003f/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:0ecf4e2948c3de57ea12d66f6cf6c0e3ad88b5eae0d216cfa2922800ba5522a7", size = 1200042, upload-time = "2026-11-06T09:54:37.409Z" }, - { url = "https://files.pythonhosted.org/packages/f8/eb/6810206ee4864b39da6e81b2318516773d5a89b0e2132c00dfc9aa760179/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:55e3dcd5d8fbfd5a97018ff2712f375148b62ef537490c281a198977f3588578", size = 1165971, upload-time = "2026-11-06T09:53:25.72Z" }, - { url = "https://files.pythonhosted.org/packages/e1/c8/ebfb57d277e571c207d690efa56462f1f582721e5170bb86af42c3f97b07/hypothesis-6.170.15-cp315-abi3.abi3t-manylinux_2_31_riscv64.whl", hash = "sha256:417fe54775f846fa4903bb2094ce3092a0ecc107db6676b21fd8069fcc328cb9", size = 1120269, upload-time = "2026-11-06T09:53:56.767Z" }, - { url = "https://files.pythonhosted.org/packages/8a/2b/69dff10b56fbc21dc0d240de503d741ec14cb6819f67530bca0b6ff7c5af/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:47438186039fcfba3a245bb407490d442ce2c9cce4370565f1bfcdcb887e91e2", size = 1296436, upload-time = "2026-11-06T09:53:54.24Z" }, - { url = "https://files.pythonhosted.org/packages/5f/43/42b037bb17dca205f5953b11792ecc2c73dbf7ec743d5dc490d010edb9b0/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_armv7l.whl", hash = "sha256:372b05075d4a259c5ebf3fcf43dc689ef5d4335bed9d0c9dd25d14997842c0c0", size = 1425535, upload-time = "2026-11-06T09:53:27.106Z" }, - { url = "https://files.pythonhosted.org/packages/a8/29/bb3050f958b0e3156909011afdcc07812b58a47eba50f53a39d931c1256b/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_i686.whl", hash = "sha256:2161fb65416bf8da3b1c3119aa92ea63cc177fd88249bf7dc4ca64b4872e0bd1", size = 1379162, upload-time = "2026-11-06T09:54:23.523Z" }, - { url = "https://files.pythonhosted.org/packages/a5/db/30a2291c92cd437b0c8184bcead204add93d174a1317894dc50ddd3a681d/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_ppc64le.whl", hash = "sha256:b3db4c8aecd13e043c419d90ccb683fdf19711b547ca9d23e685a35157d4657f", size = 1274757, upload-time = "2026-11-06T09:54:38.796Z" }, - { url = "https://files.pythonhosted.org/packages/a5/0a/5e1bf0060a1f9486f6cad2b512b5101526dc376565eb669c20964ccee730/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_riscv64.whl", hash = "sha256:3b81f08d6052ac74f479215029e253d88fb80e9867e8bc034252d345abfa94ce", size = 1292003, upload-time = "2026-11-06T09:53:14.207Z" }, - { url = "https://files.pythonhosted.org/packages/0b/b9/9d18977c7ec9fa0d0fb22f0e52b3a270fef7b8251579d46660fca285e289/hypothesis-6.170.15-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:a51297c26ab637a97ec3283a39de163efce0a926d0ccd4378faabf5994adb01f", size = 1331925, upload-time = "2026-11-06T09:54:53.632Z" }, - { url = "https://files.pythonhosted.org/packages/ff/af/a86d51e4550c92a794777a59a9332d135c975c6f6c25b7506c447c3be27e/hypothesis-6.170.15-cp315-abi3.abi3t-win32.whl", hash = "sha256:51246e702c458b42a4b5079c3e6904c9dfb5193de920ed91fdbfa09fa694c55b", size = 685060, upload-time = "2026-11-06T09:53:35.48Z" }, - { url = "https://files.pythonhosted.org/packages/dc/3d/ef64b33ef8c5eceb7448860b77bc1d28e3e3b3e92b7d662456fee227f4b0/hypothesis-6.170.15-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:a951de05b61b7c1235a732543dc6c3b105b6c894e736f21cb891449589aaeba7", size = 691031, upload-time = "2026-11-06T09:53:10.201Z" }, - { url = "https://files.pythonhosted.org/packages/e8/3d/f875573e232550be631b6932f93bd6b2234d880891394fe4d70d57e292b7/hypothesis-6.170.15-cp315-abi3.abi3t-win_arm64.whl", hash = "sha256:9dc31166ccb95928c6eb05817684b2dd1c2a3698a6daad0450e5f449e44bb633", size = 689008, upload-time = "2026-11-06T09:54:13.194Z" }, - { url = "https://files.pythonhosted.org/packages/3b/54/ab7c9a7581b0acaeb58850629f4772aab054f2fd6a77bd3264262dfb1156/hypothesis-6.170.15-pp312-pypy312_pp80-macosx_10_12_x86_64.whl", hash = "sha256:45c267cb5bcd7b73b1ca6cedb039de423b8695b34a31cc87c29a7787058e7e59", size = 801399, upload-time = "2026-11-06T09:54:10.562Z" }, - { url = "https://files.pythonhosted.org/packages/fe/a6/a7dfce075d7371c9951e2a69e78d93bff5099d1b7b0ca207497eed68428b/hypothesis-6.170.15-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:3eb9428e0ba92993b61cab0289b8450f469b1e4c56cbdbdeaad258f0fb4f107e", size = 793309, upload-time = "2026-11-06T09:53:07.629Z" }, - { url = "https://files.pythonhosted.org/packages/6f/b4/ce76691a588dca99c73116593b2514af2d0095e7e72d3bcdfb7dcecf2170/hypothesis-6.170.15-pp312-pypy312_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:9c30c911be51aa4fa84706f1d79dcd9ad6b9728207e69667a3fed2d4ab711434", size = 1123240, upload-time = "2026-11-06T09:53:44.286Z" }, - { url = "https://files.pythonhosted.org/packages/52/a7/998ba78de4842158178f6d96eca52ec1c786548b3e08902d527469329c04/hypothesis-6.170.15-pp312-pypy312_pp80-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d2b68004bd5a238320569f7c03322b22815c2c145b1f7bbf52a319662570ee5c", size = 1167454, upload-time = "2026-11-06T09:54:48.426Z" }, - { url = "https://files.pythonhosted.org/packages/03/f5/410ff24a49dd645f651732f45e466cbb73f4bb73d1c54eaa5a07b832b0a2/hypothesis-6.170.15-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:d25e9a3f92e9f824bb110679506ece2b8fd7d093f1fa7d819ca46278a681a1f1", size = 692539, upload-time = "2026-11-06T09:53:30.812Z" }, +sdist = { url = "https://files.pythonhosted.org/packages/60/82/6d728e3b112bc5e4114ea84d1a4c253d8d36b4eb3eb4825e84bf24738345/hypothesis-6.170.23.tar.gz", hash = "sha256:96d966475f85255277d36e94c10b6854c46aa7c768124de79439b8017b9c5809", size = 522822, upload-time = "2026-11-28T00:40:04.731Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ee/2a/363c0462cd31a3a85a0dea8bf7e2e7a577ced9288a5ed130784ad17d823d/hypothesis-6.170.23-cp311-abi3-macosx_10_12_x86_64.whl", hash = "sha256:26518fdd019582426adc07965809d06ddd3cf28118d497c15fcba1a9d7e19aae", size = 802794, upload-time = "2026-11-28T00:38:55.69Z" }, + { url = "https://files.pythonhosted.org/packages/0f/09/39be9aade5a5464ebb6ebe372b421a3a2d964ac5c8d7b87372b5e044f97a/hypothesis-6.170.23-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:9d9651ce7679caf128b8a6d8ecc7b2ac49d14ee0281fc1790a3b1a1dfef45ba1", size = 798102, upload-time = "2026-11-28T00:38:57.597Z" }, + { url = "https://files.pythonhosted.org/packages/a2/19/c1e2cffaa1804dc314dac87041d17354c2f80bf4bf0a84c91c077c4bb017/hypothesis-6.170.23-cp311-abi3-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:0651a9c7543d97502ff94cfba6c1fd8909d266cbe92074caafcfae7842aecd7d", size = 1167768, upload-time = "2026-11-28T00:38:41.736Z" }, + { url = "https://files.pythonhosted.org/packages/ac/99/94a559b8099b701e0899802edbd9fbc28f4a2155ab90cf1aa73f67131bd5/hypothesis-6.170.23-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:4ccac99b3cef81f85c696dc6a0bf23fd48372fd72a99663386948e0dbd53d80d", size = 1128218, upload-time = "2026-11-28T00:39:29.508Z" }, + { url = "https://files.pythonhosted.org/packages/b1/08/8ab42312453ce0d5167603b9afa2f9cb449e2ef67e1ba0896963576983d4/hypothesis-6.170.23-cp311-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:49a8de45a95f3fc833cb199c00c0d218770f4ed1b9058c3e87f63a533561c7dd", size = 1159254, upload-time = "2026-11-28T00:39:02.603Z" }, + { url = "https://files.pythonhosted.org/packages/2c/21/869653826dae504c71df1c86bf799775c982af13525b281792e5cdfc5160/hypothesis-6.170.23-cp311-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:8a61ab12249fc509b7828797bd23edf08135aa7dbdb64c41842a11a5724e7240", size = 1152429, upload-time = "2026-11-28T00:40:00.626Z" }, + { url = "https://files.pythonhosted.org/packages/c7/d7/455f464c700b40fbccf045de01ae9a7eac2be351db972fba01b38f028633/hypothesis-6.170.23-cp311-abi3-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:02cb54270ae307df334bb7962276813e7e1c003811f535220422785eedc8541f", size = 1203385, upload-time = "2026-11-28T00:39:12.106Z" }, + { url = "https://files.pythonhosted.org/packages/b7/8b/0c79dd2e041dfd5d42b0c22af0e0583125f42792bf3f70fefd7d1d67eb56/hypothesis-6.170.23-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4a1554d9d6b0506bfed175419356ea1c117a86b3be83e487cba00d2e2ab59248", size = 1171199, upload-time = "2026-11-28T00:39:08.237Z" }, + { url = "https://files.pythonhosted.org/packages/07/76/f2701605e2f78363a943bce455b795735ea09efc54d481737cdc6747f402/hypothesis-6.170.23-cp311-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:730dd1ebf3598b2e6811f6f08a91a9508a073b0ba7866629e03a1afc508a2ada", size = 1125115, upload-time = "2026-11-28T00:39:27.582Z" }, + { url = "https://files.pythonhosted.org/packages/0c/69/4f8e3774ba6c8b60ff3137b898d0c2a6a2d7f4aa6cff0edd9756c8719a4c/hypothesis-6.170.23-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a48fdad7a052b97b71cfeb821bfa6eb3ae734b9c4ea18dc66f641e2d2a89d130", size = 1303433, upload-time = "2026-11-28T00:38:48.661Z" }, + { url = "https://files.pythonhosted.org/packages/cb/af/7ebac496b69d15b06d10f6f1855994e41d4266d62338245dd10fd62dc42c/hypothesis-6.170.23-cp311-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:dd713f67e0466b77a062ff51c3831bf4d6c9a05c238dac4913dc8fa6a7faa1dd", size = 1432606, upload-time = "2026-11-28T00:39:30.885Z" }, + { url = "https://files.pythonhosted.org/packages/fc/80/5c9e42b0fdd441aec6ac1a160886b79c3e5de2b9955ce75be79e88703e42/hypothesis-6.170.23-cp311-abi3-musllinux_1_2_i686.whl", hash = "sha256:3274bbe7a6c4cd325d8e88f1a32f343b6560463ca5bdf908bd4c71a195a56d9f", size = 1385967, upload-time = "2026-11-28T00:39:20.594Z" }, + { url = "https://files.pythonhosted.org/packages/75/e3/5a30c2e7a99c2cc6916b1e9678dd1f735ea55d2d6ef05d86ed1c54ca2958/hypothesis-6.170.23-cp311-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:0efc9fc41e951fef3b8d167fe838213e0317d16788962569b04ae8dcd96ea6f4", size = 1281988, upload-time = "2026-11-28T00:39:32.424Z" }, + { url = "https://files.pythonhosted.org/packages/32/d6/0e0f1465bd49004642365b1c21648107a04109de41597905846c3201c575/hypothesis-6.170.23-cp311-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:097be930b2b2f6ae12816e4ac7dceff84b14e735e1d4a3eec984f1ac3a8e0d14", size = 1297016, upload-time = "2026-11-28T00:39:44.25Z" }, + { url = "https://files.pythonhosted.org/packages/04/8c/c598e208bcb6f58a29203e0144364cf5748ebbfbbd03003712f4697716fe/hypothesis-6.170.23-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:32d6d501b4634bc507896a33a7f539c64a2030d332d92c1a23d7121dbb757800", size = 1337580, upload-time = "2026-11-28T00:38:39.498Z" }, + { url = "https://files.pythonhosted.org/packages/ff/aa/a16a6e8304636d2bb5f202b3ac75dc878412fcd6bdfdf9e3e8bfca9e6930/hypothesis-6.170.23-cp311-abi3-win32.whl", hash = "sha256:8698157182f16c1a60a8c45210efe0f76ca728b20ab415a3814ea4d206470bdb", size = 690524, upload-time = "2026-11-28T00:39:53.156Z" }, + { url = "https://files.pythonhosted.org/packages/ea/1b/ee07b99a7aa535e74c3037b86269877245c79020c2e5c5acbfb2b0aa0d58/hypothesis-6.170.23-cp311-abi3-win_amd64.whl", hash = "sha256:dbce930a0ff3dbec3fe4730f25cde270d2b67e083bd805d24d9ac73825653385", size = 696093, upload-time = "2026-11-28T00:39:51.258Z" }, + { url = "https://files.pythonhosted.org/packages/9b/f1/458d64883bfb78c524dc24bff0dbd1ffaaec67365e63f3b714250f27426f/hypothesis-6.170.23-cp311-abi3-win_arm64.whl", hash = "sha256:44a02995404645d7db41c8b1860fb8da13a670e3f038f95808ef48073bc931ae", size = 694395, upload-time = "2026-11-28T00:39:37.149Z" }, + { url = "https://files.pythonhosted.org/packages/70/45/275671a5e904e14996f0690fd8bdab898f9b29c1589159c176600534f58d/hypothesis-6.170.23-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:df1a9f3eb601203accf95681dc3a3571f981e138b313452b356f88a62980bf9b", size = 804347, upload-time = "2026-11-28T00:39:52.189Z" }, + { url = "https://files.pythonhosted.org/packages/2a/fe/41d544c8660a1e37d5e0fe542c2047c008226a84c528d60641c09668d0cd/hypothesis-6.170.23-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:557fd0c6f0cf68809a4dfe23d51f73365718d621529a532185ae27a30da61a52", size = 796835, upload-time = "2026-11-28T00:39:00.697Z" }, + { url = "https://files.pythonhosted.org/packages/83/3f/6e28542d28e1cf83d448d9578fd4515688bdf2bfe088d54a2765b2a1ca69/hypothesis-6.170.23-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6e308bab0eb90039a75c0dd0428dffa4b9682215cb196934837fa806c48fa075", size = 1127593, upload-time = "2026-11-28T00:39:06.225Z" }, + { url = "https://files.pythonhosted.org/packages/16/1a/87fe5372aa51034d8ba3a51e5323d13e6ed6d47fb64006ad19d2cc955f33/hypothesis-6.170.23-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f2d70a195a8eeb131e5a0d6f6790a0920c0f8dc16cb1ae34e13e48beac13fff8", size = 1170811, upload-time = "2026-11-28T00:40:01.768Z" }, + { url = "https://files.pythonhosted.org/packages/7b/ad/044545c1141e135644b318bad79822d7439f14e14a8b518cb992c7b87bee/hypothesis-6.170.23-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:8cf8b5e3436580b3182b653fa264bed71b60a22b58c9352dbd84943fa6e3aa1a", size = 1302855, upload-time = "2026-11-28T00:39:11.172Z" }, + { url = "https://files.pythonhosted.org/packages/b8/4c/52dcc0fb8d59d3013d01ab51d5c540f40e50aa28f6cdee464a07db6eb101/hypothesis-6.170.23-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:d401008b79bcb9fb2c15a35d8d54ce140823dc101652ba994d425f32cb36e302", size = 1337162, upload-time = "2026-11-28T00:39:23.657Z" }, + { url = "https://files.pythonhosted.org/packages/98/07/2fcbe06a09bc644743f14a247036edbf7f57adee09f8104099df49ad097d/hypothesis-6.170.23-cp312-cp312-win_amd64.whl", hash = "sha256:1961b416507eeda167c36e486a899c33c8eb0287c54495610a341dad9846dcc7", size = 693588, upload-time = "2026-11-28T00:38:59.659Z" }, + { url = "https://files.pythonhosted.org/packages/7c/97/702f7243743a84476423c41f98a5170d4d7a76dab14e52d235ae1d8032b4/hypothesis-6.170.23-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:24c982773123480e6d0058a29197890267abbb2bec2c117f7c9e5ecfe47ecbf4", size = 804281, upload-time = "2026-11-28T00:39:35.206Z" }, + { url = "https://files.pythonhosted.org/packages/f7/27/0ca30c8119b1ff06443b990f4eea45d92880303aaff00454e1dd4d4ace73/hypothesis-6.170.23-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:eb6329f2544ca06ddfb320826df5b3d578bbf2177c1c76e9079a8bb1cb3fcef1", size = 796869, upload-time = "2026-11-28T00:38:49.709Z" }, + { url = "https://files.pythonhosted.org/packages/bf/48/4cbb643858545e13d7a31f329001af5f2e791df98be5ccb51df2bbea1237/hypothesis-6.170.23-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:69ab463a7cf94043a5c0e54795abc1f4ed74e43b4aec15a40f9da8ad48e930d9", size = 1127484, upload-time = "2026-11-28T00:39:41.425Z" }, + { url = "https://files.pythonhosted.org/packages/23/2a/c3c47dd61d89118d2444a48f27deeaaecfcf7c7eb6784219e23f47275e44/hypothesis-6.170.23-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3e3ed4d417cd154dc95f077db84e5494d2ddd122c231e9172142b52cc73d52a3", size = 1170699, upload-time = "2026-11-28T00:39:01.59Z" }, + { url = "https://files.pythonhosted.org/packages/43/a5/26a04251455082e114637c158be9de25e0be2a59703841fd989a00304598/hypothesis-6.170.23-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:2adb875f3a09706ddc7eac4cd653117a1ea306d7308fa77b92765026f1fb0696", size = 1302679, upload-time = "2026-11-28T00:39:54.47Z" }, + { url = "https://files.pythonhosted.org/packages/c8/b2/e3957831f34931d61bcd48f57cdd281c20b501eab07cfbceef87b22ca33e/hypothesis-6.170.23-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:00f32a00cd29b0f9f3cde1fbea644baf753a28bc9e7e8781c230483fc973da2b", size = 1336985, upload-time = "2026-11-28T00:39:45.279Z" }, + { url = "https://files.pythonhosted.org/packages/18/b8/9ad708af3026cdb87cdda5132182bcc75e789be46b13f4f1386a529e3e64/hypothesis-6.170.23-cp313-cp313-win_amd64.whl", hash = "sha256:7707f5e3c308e7fccc34eff14f5f5f0df1210b3e897e9f4419dde838d2f0f345", size = 693524, upload-time = "2026-11-28T00:39:26.543Z" }, + { url = "https://files.pythonhosted.org/packages/5b/4a/6ad1e6f061b539eecd3f9093e106c0ad872bdbac230448df25e4c7395c8e/hypothesis-6.170.23-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:070c6729c3ffb9861520e3e72fbb70adf7baa117d1348bd9ddc4a8f6df374cd3", size = 804482, upload-time = "2026-11-28T00:38:42.923Z" }, + { url = "https://files.pythonhosted.org/packages/12/40/67a8dbc6ccd04eefc282c290e51efd93df787c9af6abc5a9ddd88a805fa0/hypothesis-6.170.23-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e41f667403ba658d464d1b56778770a1a46e83a2fafd93851cb8e8b6822fccc5", size = 796906, upload-time = "2026-11-28T00:38:56.668Z" }, + { url = "https://files.pythonhosted.org/packages/08/9a/183a8f6d4d8a180d65709c3fb3c7090cc730d75a0d77495c9d6d1df1b611/hypothesis-6.170.23-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:43333d0c93c5ba7aebf5db2b0fd9afee68083ff57f1f2dcc98d431e171d88b86", size = 1128092, upload-time = "2026-11-28T00:38:53.67Z" }, + { url = "https://files.pythonhosted.org/packages/d4/fd/a9c150de8dc1d70396874c72a4524a274b9598497e5f00ae04bf9291d40f/hypothesis-6.170.23-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:27d9dbc44fa1a465ea21705ab36e9135e7d68e694617ccf00ed0e20b6568d416", size = 1171028, upload-time = "2026-11-28T00:40:03.75Z" }, + { url = "https://files.pythonhosted.org/packages/ff/4d/c3dd568843023d40fc3f64a0cb760306ab801f2773c5dd77c6b78cb59f4c/hypothesis-6.170.23-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:21225409241d44fbb8836ee3d279ca387f89c42c4554145299e84d0215f78cf9", size = 1303023, upload-time = "2026-11-28T00:38:43.899Z" }, + { url = "https://files.pythonhosted.org/packages/eb/c3/f605ce27df39d9c2472fd5b64b2091f10e11d688764ed40d5cb1fed8e141/hypothesis-6.170.23-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:36971863d8c37edc06f43f45b318484f795c0885619777f57420d8aa1dd5c18b", size = 1337225, upload-time = "2026-11-28T00:38:58.638Z" }, + { url = "https://files.pythonhosted.org/packages/dd/d9/0e5c5b9cd647e8ccd8e008dbdbb879aff87565a8c954595cabf2e80c3e35/hypothesis-6.170.23-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:055882c3dfb45e5b402248e97f98076dcf853127030a4b744a2b4817e966ecb3", size = 635665, upload-time = "2026-11-28T00:39:42.423Z" }, + { url = "https://files.pythonhosted.org/packages/44/5b/baad6a2eaeff2c98471db1c63100daff241c11f961f69f4d0e106f7a3cdf/hypothesis-6.170.23-cp314-cp314-win_amd64.whl", hash = "sha256:dbf258f4328f340fafbc36cce683b7ce8779e6f3dcc545453764c37ad1130e7e", size = 693423, upload-time = "2026-11-28T00:39:05.169Z" }, + { url = "https://files.pythonhosted.org/packages/3b/48/01b895c961f07249f6df34d47dd156d2ac78b39ad27366cd12361fff7926/hypothesis-6.170.23-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:17c60e7dd089dde65e15e473c2ff877c14a267eb622f1656ec5bd734e0a6256f", size = 802811, upload-time = "2026-11-28T00:38:38.396Z" }, + { url = "https://files.pythonhosted.org/packages/7e/61/cf3bc3e1a739cb5d8b0025e0ec1c89a84b7cd13eabe6c2da2d45cac79faf/hypothesis-6.170.23-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:8c6f3a4adbb4ceafe1f1e2308f04e3d2ff08e0bd3921bc467ab5cf580fa8211b", size = 794931, upload-time = "2026-11-28T00:39:15.565Z" }, + { url = "https://files.pythonhosted.org/packages/36/bd/5aefc4734c1508c4c4781c6eb42817d9c021d2020b603b78bf130bfba1b0/hypothesis-6.170.23-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:eb8d96086eb38b150f117fd615d35ba93ee2c6d7c1d1cd3278a94c4da68a6380", size = 1126432, upload-time = "2026-11-28T00:39:33.367Z" }, + { url = "https://files.pythonhosted.org/packages/80/ed/6b41d7f098e9c44b29ba4bbeb81e2ea83943dc676f1eef40381ea8c3d38f/hypothesis-6.170.23-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:622c18918c5d90b7ee09923a32be78aafc3dd23bd4819f31e6b7038b2b008fb5", size = 1170159, upload-time = "2026-11-28T00:40:02.754Z" }, + { url = "https://files.pythonhosted.org/packages/88/04/ddb3d15d5975dfe95e5d1b8731bc20e023c6c16690b1eefa6aa305006d4e/hypothesis-6.170.23-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:0fe10a73024f0fe15b3a6f1d50ca97ab5729bb5926c1881116a1e7775a779a8b", size = 1301421, upload-time = "2026-11-28T00:38:52.637Z" }, + { url = "https://files.pythonhosted.org/packages/56/14/4277eac2014cfcfa56cb8c386d29058f61d7131aba3ea431ad17be966e14/hypothesis-6.170.23-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:feaea71349835a9d7c0455b02dfd7402f8a3d65764d7b3ae36d6b794f1b0f307", size = 1335822, upload-time = "2026-11-28T00:39:24.639Z" }, + { url = "https://files.pythonhosted.org/packages/30/81/060296a282d2968a32591805a01dadd4c1bffa779d3a5d433a6146678fa6/hypothesis-6.170.23-cp314-cp314t-win_amd64.whl", hash = "sha256:a8a2c5214143a5e80841d112a650eebbef5e6cfb6628f29cd0b3000ffe213769", size = 693398, upload-time = "2026-11-28T00:39:50.199Z" }, + { url = "https://files.pythonhosted.org/packages/db/5f/c2a139396c140a80e0d45c6893f0ca74de5f50e2dec679130140aef0a526/hypothesis-6.170.23-cp315-abi3.abi3t-macosx_10_12_x86_64.whl", hash = "sha256:0ce2f88af4dccefa7c51cf443284abcf1441d261158fd866704aaeb0b020d40e", size = 802384, upload-time = "2026-11-28T00:39:49.19Z" }, + { url = "https://files.pythonhosted.org/packages/81/3f/4e22b56fa25afdb9dd95504829677bbf13475a9990e843d89e7a1bbfcf27/hypothesis-6.170.23-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:0e7c593fc54f0f8c39476b14ce0860ba11fae534c38b3b2ff8434211d5017237", size = 794756, upload-time = "2026-11-28T00:39:07.326Z" }, + { url = "https://files.pythonhosted.org/packages/cd/90/d56c7a99975ef8c55054db012734586f8096094679be00e8fda6adce6fb7/hypothesis-6.170.23-cp315-abi3.abi3t-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:3600fb32fee4eb4a079c550ab769f6c325438e40094b5e04d684d5342d18b2a0", size = 1163369, upload-time = "2026-11-28T00:39:40.498Z" }, + { url = "https://files.pythonhosted.org/packages/92/09/86aba84f2f424eeb4027e223798f0fb99bd5fb2eeeab55b490d5dc231ec6/hypothesis-6.170.23-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2349cc6bb4f7736aaaadfef7d371c05d2a755bf7b1dd2d2d19c67c5bbc340c6b", size = 1125603, upload-time = "2026-11-28T00:39:38.393Z" }, + { url = "https://files.pythonhosted.org/packages/97/79/90d0f5fe3885ee82cce019c97e986efafbbdde138b5f05d9f742f49c57d1/hypothesis-6.170.23-cp315-abi3.abi3t-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:3c9146ef0cbdbb2629dfc97bceeeb9c7dbd5d2f19af45fbbd26e9838ffe2485e", size = 1156467, upload-time = "2026-11-28T00:39:46.551Z" }, + { url = "https://files.pythonhosted.org/packages/b4/a3/b5b1140559b6e2eba1790090800652cbaf6cc8068abf9bf88457fd0d9938/hypothesis-6.170.23-cp315-abi3.abi3t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:a41da9230f896758f34c526ea873b45b02d25132227820a39aa995a63974e4e6", size = 1149893, upload-time = "2026-11-28T00:39:25.612Z" }, + { url = "https://files.pythonhosted.org/packages/3d/53/80c6b2929f8ec3a3a56bc53163965bf20fa3d0bfb5e1864f9f0bf8fdaa1c/hypothesis-6.170.23-cp315-abi3.abi3t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:66fdc86e9028f8a1625140684f3beb3b10f61e94c14922494f4a06ffa6e2f806", size = 1201754, upload-time = "2026-11-28T00:39:14.298Z" }, + { url = "https://files.pythonhosted.org/packages/56/dd/5d71765218fe993e7ad56d4de8045ea7d69ff73399dcf19606460f6f425e/hypothesis-6.170.23-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8005c1011dec0354eac61c3d7062efef81587692796dd2a3d1c7a4b2dad3c992", size = 1169589, upload-time = "2026-11-28T00:39:10.181Z" }, + { url = "https://files.pythonhosted.org/packages/48/bf/5fe51731d15e9ea4d5d41c09d3016781a28f365683d0685fade5aca1a854/hypothesis-6.170.23-cp315-abi3.abi3t-manylinux_2_31_riscv64.whl", hash = "sha256:8be316ff2939659ce259bbc92758fea0dab60cf591d07394bdf42862fd8fc7a2", size = 1121423, upload-time = "2026-11-28T00:38:46.145Z" }, + { url = "https://files.pythonhosted.org/packages/95/53/9a8b95efbd927b2b716fd2a45e920567abd1ade94e4085ca3edd29fc2751/hypothesis-6.170.23-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:60d0b0bcfa41777bd898a932389f3105c22cd50e18fd4273f12d929d243893c9", size = 1300603, upload-time = "2026-11-28T00:39:28.547Z" }, + { url = "https://files.pythonhosted.org/packages/46/f5/d39c22b4ffb31aab0d19bbd6e7dcc18d948a559652d5a5b7eb25f239fb88/hypothesis-6.170.23-cp315-abi3.abi3t-musllinux_1_2_armv7l.whl", hash = "sha256:bc0be420712dc8570252a7c94c16656bceeb7c0a87d3586b85da8c73d9e41053", size = 1429302, upload-time = "2026-11-28T00:39:19.145Z" }, + { url = "https://files.pythonhosted.org/packages/b9/8e/9b0c53c59b841fdbf52367936a33b0830c8cb9ffec8f308dc81a02f05e9c/hypothesis-6.170.23-cp315-abi3.abi3t-musllinux_1_2_i686.whl", hash = "sha256:f4b4ace05cb2cc8b81ed781dc36d8a5ac497912747af5ced2d6fb1b84fa12994", size = 1383782, upload-time = "2026-11-28T00:39:04.056Z" }, + { url = "https://files.pythonhosted.org/packages/a0/c4/51374f5a56cb690f71041d339618dce7478e0c7805b8524932dc05ad1911/hypothesis-6.170.23-cp315-abi3.abi3t-musllinux_1_2_ppc64le.whl", hash = "sha256:eae358f440878562979887fda25b121e6fb2114978308ab7de925804fabfbded", size = 1279153, upload-time = "2026-11-28T00:39:16.677Z" }, + { url = "https://files.pythonhosted.org/packages/00/e2/c21cc02baed84e3f5230720d55b84c9fd202d76f187a037f75b1f9064e7f/hypothesis-6.170.23-cp315-abi3.abi3t-musllinux_1_2_riscv64.whl", hash = "sha256:72c91a466ba254a4e8461b55a57536176c18633ee59f26a6ecaf427cd2fa1714", size = 1294686, upload-time = "2026-11-28T00:38:54.716Z" }, + { url = "https://files.pythonhosted.org/packages/cc/c8/d157cd79685e391d4b222a10a7025be24b45afbd536d1b3bc074ac4b3f80/hypothesis-6.170.23-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:7101f077c18d557537ba466b74affd99076522587760573fa13ab2b868ff37db", size = 1334982, upload-time = "2026-11-28T00:38:40.672Z" }, + { url = "https://files.pythonhosted.org/packages/4c/ee/35b16b60ab0bbb3a27047710578bd549d1c02f0b22b51e86ab1e470511b7/hypothesis-6.170.23-cp315-abi3.abi3t-win32.whl", hash = "sha256:324e6966dcd1b5a7392c3f605ed0212d8779290f4fc0712615694a6cec836a63", size = 687321, upload-time = "2026-11-28T00:38:35.473Z" }, + { url = "https://files.pythonhosted.org/packages/17/a5/813d1a2ed58ae1cf70c7ed81b8da9b1829aeca87f8473bb063e514f036ed/hypothesis-6.170.23-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:d31a74a234873c86ab31f862d4bf39693462da582cf934af9a90b8771e5d2a08", size = 693237, upload-time = "2026-11-28T00:39:13.072Z" }, + { url = "https://files.pythonhosted.org/packages/ee/0c/1281ad74a706be116a5701792f60040462493488ff95daf5433e956cbfc0/hypothesis-6.170.23-cp315-abi3.abi3t-win_arm64.whl", hash = "sha256:39bb790f869c9748c83591d3b3d7355502a2afd658b66f67065253d51b5e2900", size = 691311, upload-time = "2026-11-28T00:39:21.821Z" }, + { url = "https://files.pythonhosted.org/packages/ec/6d/d20c763f6257b895174fe1d210e9e8e5655a63990a2b60e6bf151e7ae282/hypothesis-6.170.23-pp312-pypy312_pp80-macosx_10_12_x86_64.whl", hash = "sha256:d9c31eebbe072eb3b526c338fe72efd93d5d0c9b41e6e44036c0a14000172b56", size = 803603, upload-time = "2026-11-28T00:39:56.473Z" }, + { url = "https://files.pythonhosted.org/packages/a0/5b/046b2e5fff19deeb3a95386aaddd017c8df67a32033b340cd5be627e5b0f/hypothesis-6.170.23-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:8923dfaa0c708a8c3ddf8b64a65d7e9cc998f1884a05317c77f90a9211f157fe", size = 795921, upload-time = "2026-11-28T00:39:43.39Z" }, + { url = "https://files.pythonhosted.org/packages/77/48/6720ee906883633e2eec67ba8015031e09c1552be1370a47b72ddcbed39c/hypothesis-6.170.23-pp312-pypy312_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:a70262c5e6f7f87ab11ed028d3245272572a05734b704b8b72611aecec6a65f1", size = 1126781, upload-time = "2026-11-28T00:39:36.173Z" }, + { url = "https://files.pythonhosted.org/packages/3d/6b/b35d03d670676dc0e78fecb1dc011c9f8621d78f5f7f677994603d173c73/hypothesis-6.170.23-pp312-pypy312_pp80-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2ffa42fca86cd270f0d1e64278f3d189f739c4b3cf04b730685227216e5b3b35", size = 1170733, upload-time = "2026-11-28T00:39:58.601Z" }, + { url = "https://files.pythonhosted.org/packages/02/d0/90c6fbc05860aa1016ffadead569f133b693a7df8c84c01ee0fc9f8f1cdc/hypothesis-6.170.23-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:ce3d5ecad89220469c2932f32bdfcd563912a97285a96bd0b62b7e0968650523", size = 694887, upload-time = "2026-11-28T00:38:44.964Z" }, ] [[package]] @@ -1899,106 +1899,106 @@ wheels = [ [[package]] name = "regex" -version = "2026.11.9" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/61/27/a5afeb952577b84ee5fe48b8b9ce47ae662dbb69cc5b76c28eff98f83b1e/regex-2026.11.9.tar.gz", hash = "sha256:316a70fbd70e999c9664681cb0eb5b4982b2cc0f623c7c86a8a112e1bd4c6277", size = 419513, upload-time = "2026-11-09T00:42:09.786Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1b/81/f9c9857e531301761b612129ca24fc2d6a9f83c5d804510f0a86d97a0ce6/regex-2026.11.9-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:9538d0bc19f87d273c2a5397a08fcd2646d02ace31ba7974483d997e36654dcf", size = 498602, upload-time = "2026-11-09T00:40:00.967Z" }, - { url = "https://files.pythonhosted.org/packages/e5/3b/58288749f3fb7303b1ee293a598813c4d08a440cc14c0c55a8fe4f7723ae/regex-2026.11.9-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:a919f782789b9b3460bc51a1c69125551bb6164a0e401865a037397b219705b1", size = 296962, upload-time = "2026-11-09T00:40:02.404Z" }, - { url = "https://files.pythonhosted.org/packages/13/c6/32671781f2e61f40c76cf81df160ef5471264ba8a5f28cbd342cd4887a8c/regex-2026.11.9-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:2255e173ffb8da59f26ec3529bf7e8531320e71575b27c3fb062747eb3a12e1f", size = 294199, upload-time = "2026-11-09T00:40:03.499Z" }, - { url = "https://files.pythonhosted.org/packages/cc/ba/80e68a4d9a3cbbfd7734744a25e26e42976f50baaec786ba7c420b4855b1/regex-2026.11.9-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1e2513028297550486dffc6e0799f24f194957418b75cd0ac2c7ad484e0d12a2", size = 804924, upload-time = "2026-11-09T00:40:04.54Z" }, - { url = "https://files.pythonhosted.org/packages/9f/57/029cdaaed8616a6088e39e0fb5c4f688e1821470f2004a90ef4738fd91d2/regex-2026.11.9-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:16165b67939c4fbaff46bb0380828d4fdda6936d92861baa47257399459145a4", size = 878334, upload-time = "2026-11-09T00:40:05.807Z" }, - { url = "https://files.pythonhosted.org/packages/62/48/cbbe309d95982fb72a09eb8e31a32ec719de04d061dbacba94ca892a6ae1/regex-2026.11.9-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b7073a7a0134621c5cfcf2c63b55cfd569cd88a6417c08cf829babba200b989d", size = 919365, upload-time = "2026-11-09T00:40:07.474Z" }, - { url = "https://files.pythonhosted.org/packages/46/c2/59c5b6cf4b762d80de04cf60f2d0deba1da2f4172a91c41eaee8933080a8/regex-2026.11.9-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ab4a0c5cd3df4b93841ba4a419a5438b2a4c78a4e418682fc674e3f50d56b857", size = 808826, upload-time = "2026-11-09T00:40:08.864Z" }, - { url = "https://files.pythonhosted.org/packages/e1/7d/18e82a2dc59bbebbea7426d3d5034cb9790230c2826d55ce090e6c8fc38b/regex-2026.11.9-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e3fe4474aeaa34535077bd3cdee6294756e99f4ed498b09712b5f3dc0b2947a5", size = 783421, upload-time = "2026-11-09T00:40:10.376Z" }, - { url = "https://files.pythonhosted.org/packages/40/a3/4c561718974dad242b481c2d9399a2a2b5d29b357cb6bed52427d6c0c2d9/regex-2026.11.9-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b47bd645e6305d22a31dc063635de40796e93e72cfeb9a86108dfa806ce866fa", size = 791492, upload-time = "2026-11-09T00:40:11.582Z" }, - { url = "https://files.pythonhosted.org/packages/fc/70/80a9f43944dd81012c2e10f4ae295d91f8db6929e79b10f1232e00b10d78/regex-2026.11.9-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:ad0795929a24ad49f096c464f0ff7fb4d66488c6f20c2b1da724e2067e3d5c2d", size = 866863, upload-time = "2026-11-09T00:40:13.188Z" }, - { url = "https://files.pythonhosted.org/packages/26/d0/93464b1455c35000058c368fa989f21d09e9fceeb2289d1be4df93ded78f/regex-2026.11.9-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:f1ed6b50f54b8467bb3085fb6d701f3eb77c9ad81071da498cdc7725b4867f92", size = 770521, upload-time = "2026-11-09T00:40:14.703Z" }, - { url = "https://files.pythonhosted.org/packages/1f/5d/34c5aec48033f7929beaad8623e19ad7957b0de7ebffeae96b9689f1fedd/regex-2026.11.9-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:e6f945b6fcbf1a51760ab41b61159dba8bbcf3614ed921bd175d62529be5ec26", size = 861457, upload-time = "2026-11-09T00:40:16.091Z" }, - { url = "https://files.pythonhosted.org/packages/94/59/80c4299ca9422b44738f8559d850e96d09a201334be41499863877980cb9/regex-2026.11.9-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a5ac0114fa49c175803fce562ed243bfaf7f6943edf4b2a01ef82f0f61e7e397", size = 795558, upload-time = "2026-11-09T00:40:17.222Z" }, - { url = "https://files.pythonhosted.org/packages/4c/cc/f14bf9e6e0ed44f29402bd8319ca231f2dce52c76084fc8561abaeda2e45/regex-2026.11.9-cp312-cp312-win32.whl", hash = "sha256:2f1c997fcb7a74006e3c4f09199d9e835bb46eb12c1c909f8b8259627f7b5ec7", size = 269777, upload-time = "2026-11-09T00:40:18.606Z" }, - { url = "https://files.pythonhosted.org/packages/c1/ef/e03271355a802f38f7510e31e006667fc8b95b771058d75a36e2afda61b2/regex-2026.11.9-cp312-cp312-win_amd64.whl", hash = "sha256:ae42ad9825cde4cd374abfce6bc82233b91099170c138b349554813e97da5100", size = 280891, upload-time = "2026-11-09T00:40:19.698Z" }, - { url = "https://files.pythonhosted.org/packages/a3/08/551312e6599ac812b4052b5c9d3b3097b716f853c01e8ae6a150f805345b/regex-2026.11.9-cp312-cp312-win_arm64.whl", hash = "sha256:3c3886844cf8d2ce2b2cddb849eff6c404bfa951c77bd63fb4bd7ed270f135dc", size = 280256, upload-time = "2026-11-09T00:40:20.726Z" }, - { url = "https://files.pythonhosted.org/packages/90/55/7b6278e0babda54fe4b619c13019aef42247de912180777d49afae8eefac/regex-2026.11.9-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:224b73a26a1e64cf87fc8da9ee7a9994f152b92a728a7786b5c002fcebb205b8", size = 498358, upload-time = "2026-11-09T00:40:22.495Z" }, - { url = "https://files.pythonhosted.org/packages/4c/96/e37e54801fcd80fe7d2929708cd0c459aef588bc887da2de58a7c3c963d8/regex-2026.11.9-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:6852035568af30020a538f945863d2dca3d5baadfe9d9387f9d54de2f1b30a45", size = 296847, upload-time = "2026-11-09T00:40:23.623Z" }, - { url = "https://files.pythonhosted.org/packages/f6/69/8bb15a5dcc3f8c9a57b069847fd65552bb7d1de22861e283e0139e5d5c71/regex-2026.11.9-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:24c9479dc1215a1ebc96fedc9a0cd026240209e9b69aa223df411c443bdf1d93", size = 294046, upload-time = "2026-11-09T00:40:25.026Z" }, - { url = "https://files.pythonhosted.org/packages/19/74/b13616c437d4141e9b73ef8f44d2be36058dc83cc1316048a081b73eead7/regex-2026.11.9-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c5e3b575067d381f59cd6896a0126aef5dfb80a16b03594e8fc86bdc9dcf1cec", size = 804872, upload-time = "2026-11-09T00:40:26.115Z" }, - { url = "https://files.pythonhosted.org/packages/45/e4/8a0597242b57ef983f50ce84a2f35ba681e72333ff34aadee2805de2deea/regex-2026.11.9-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:38225e2f77e094c5a118e64af55655192eb16966b1e61ed8f4674ea94bedbb04", size = 878457, upload-time = "2026-11-09T00:40:27.223Z" }, - { url = "https://files.pythonhosted.org/packages/2e/a7/3ed73ae7e9b7ae09f80d09a59ee21fefc4a3e33a08e2b039934e57b86a76/regex-2026.11.9-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b4957fa9142e4850f454e7e76366245677cb917c608d7f8088b0105c9948db2f", size = 919209, upload-time = "2026-11-09T00:40:28.425Z" }, - { url = "https://files.pythonhosted.org/packages/35/3c/d6f2b69b141b3d0aa82d69fbbfe2b38dc49138e3f6843cc763774202d024/regex-2026.11.9-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:32183c31b090e1ee2bbb60898d236addc0029bf04a6def37175c2bb5419dcfb5", size = 808929, upload-time = "2026-11-09T00:40:29.882Z" }, - { url = "https://files.pythonhosted.org/packages/68/68/2fbbb66b68d0babc7260c1538f5d422f9edbbbdf4d6e5c916f8fe7c0fcbc/regex-2026.11.9-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:86b0004630d82a7fa993a40c599d77180622ba356d68dc48eef8f47e8c836853", size = 783522, upload-time = "2026-11-09T00:40:31.095Z" }, - { url = "https://files.pythonhosted.org/packages/8f/fa/50f1b4e85430cb4aba15320eb0a8204e48d175317168771b8c05a00373c5/regex-2026.11.9-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d6bf83cfc92e7f6402cc10b8542fc562d4183929bdf126a0ccea1c15b55a109f", size = 791604, upload-time = "2026-11-09T00:40:33.218Z" }, - { url = "https://files.pythonhosted.org/packages/96/6e/fbf5139423566e051cedd6f71c97bc16fb34653e921b6654e24a0c16df8a/regex-2026.11.9-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:c88a1749323036f3b3f67c32c1df4c6f2889f1ad5508eb3b66032019e0acb14b", size = 866818, upload-time = "2026-11-09T00:40:34.861Z" }, - { url = "https://files.pythonhosted.org/packages/f0/d7/d873103dffac3b4558437dd622edff275f88a0cd32d0bed5175ac0c389b5/regex-2026.11.9-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:0dbed59cc01d38778091845ac229dc24b909bc326b82d3043972b0acd1349bb6", size = 770466, upload-time = "2026-11-09T00:40:36.345Z" }, - { url = "https://files.pythonhosted.org/packages/6c/71/d681e7949e91de573808a0d609a84d99411fad3680d346e436f68528c4fd/regex-2026.11.9-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:d0517aff825aaa7a242ce85938ff4a51fa73633ec14a0b6639f658b29a78e6f2", size = 861497, upload-time = "2026-11-09T00:40:37.572Z" }, - { url = "https://files.pythonhosted.org/packages/5c/17/052721465a9e96a340b73d6bc7bffacd7bd9d57b4ddc38ac95e6671b7882/regex-2026.11.9-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a1919cb74f076c93b3d7344ba8ec930e9aa6d70272801779ba0e9bb48eb12d4f", size = 795612, upload-time = "2026-11-09T00:40:38.81Z" }, - { url = "https://files.pythonhosted.org/packages/7e/ad/f5eeae00983238972bbcd3b31122437f729299d4a7ecd661b07a61448a6f/regex-2026.11.9-cp313-cp313-win32.whl", hash = "sha256:bd66446f042de0b2fdc4870f590eed990285d7c5d677545dc5aa8fd0dcf5f0e9", size = 269754, upload-time = "2026-11-09T00:40:40.004Z" }, - { url = "https://files.pythonhosted.org/packages/f3/e5/27d16943df68676aba97db64e58b10702627eac1b983d96342b80b71f6c1/regex-2026.11.9-cp313-cp313-win_amd64.whl", hash = "sha256:19d36876d5783f157f280e67e51038a63a30630bd069528070d83a711f170e99", size = 280845, upload-time = "2026-11-09T00:40:41.348Z" }, - { url = "https://files.pythonhosted.org/packages/6d/34/74fbef82831900af4da247486576f867e6ffdb531841adc771af5797b213/regex-2026.11.9-cp313-cp313-win_arm64.whl", hash = "sha256:2062558aead9322ce54479b0ac356453d1455a30ec40d16b263b4cb0dcd5fd0d", size = 280234, upload-time = "2026-11-09T00:40:43.225Z" }, - { url = "https://files.pythonhosted.org/packages/ad/76/0931cbbc2faec7eb35e1dc95bb6e3256ddd20d1995dc1474886954436d33/regex-2026.11.9-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:8d8225ae4aec6154a9c895fc5ea7a4cd9347c955432ee3cf277871518b4a78cc", size = 498414, upload-time = "2026-11-09T00:40:44.336Z" }, - { url = "https://files.pythonhosted.org/packages/18/57/e06c598bd5935bce31faae0c20dbb27f7b3551f77c871da1fcc9d5e8806d/regex-2026.11.9-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:2d8f8f23200309b13a48a43379890bcdd34db49dda203445d2c9e1ebc1919419", size = 296843, upload-time = "2026-11-09T00:40:45.828Z" }, - { url = "https://files.pythonhosted.org/packages/e4/bc/8d2e21baca091b2f2bba7b6127cb60395018579736d41958d7398f381e5f/regex-2026.11.9-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:fb91fc79a06d276f7811b840840440c6a35178396bfab288a4814b9a05d08245", size = 294104, upload-time = "2026-11-09T00:40:47.187Z" }, - { url = "https://files.pythonhosted.org/packages/4d/14/561ec95a248d68b55598e80a8a7190fce98f8a1ab8c0aeb2fe46b153bb28/regex-2026.11.9-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7f570129536763bce7bd06a24f555bfad989aca594459a09cd7d51e47b92e0b4", size = 805122, upload-time = "2026-11-09T00:40:48.658Z" }, - { url = "https://files.pythonhosted.org/packages/a5/f0/6398931f37cf3c3e9a1f8af33097ada8c17c7a991791e0b2e1df60f34666/regex-2026.11.9-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:992f562c10b100501d17abad5307cbe5049cecc9afe6f5bb58cc0c49be964a95", size = 878892, upload-time = "2026-11-09T00:40:49.846Z" }, - { url = "https://files.pythonhosted.org/packages/ed/49/eb615960e51bf824a24ef5ad3ea100f72ac5010aab835bd72fc0fbc5b9d2/regex-2026.11.9-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5f571e667b3a0af4a37e231c535bec1237f531433fbeea4efe7196aae04eb734", size = 918562, upload-time = "2026-11-09T00:40:51.008Z" }, - { url = "https://files.pythonhosted.org/packages/88/4e/97c82477691afa0329b51ee801e5002cbf91ceff4864200cf2895833586a/regex-2026.11.9-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8d6cc5be22e9c839547d6ffc88b515845cbf47604c74d293955eea96281adbc", size = 808261, upload-time = "2026-11-09T00:40:52.586Z" }, - { url = "https://files.pythonhosted.org/packages/ab/87/c6b8dba287886b6b535b05cbb860110b84d11b864725cd39a35c7066da2b/regex-2026.11.9-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f026e602009c42175f5d7ab5ae0dc34884b09e5c1bb9c540e37f5f60c330173d", size = 783703, upload-time = "2026-11-09T00:40:53.631Z" }, - { url = "https://files.pythonhosted.org/packages/2f/d5/f9707218634b435d03839d0dd4c43b7b74426c7a010ea786846b36215887/regex-2026.11.9-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8088dcf06e237da99bdf1e802716ad29e9b4103b2b04f8dee87de3d6102a6c03", size = 791919, upload-time = "2026-11-09T00:40:55.058Z" }, - { url = "https://files.pythonhosted.org/packages/68/05/352600c95571b49ed1c7a9a73e9afc76459854439c8b5c1e811b3b81b6d8/regex-2026.11.9-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:063cfc54e91284d0d9808befba1b9624bf230c3d22c6dd32a539f7af81b391a5", size = 867716, upload-time = "2026-11-09T00:40:56.286Z" }, - { url = "https://files.pythonhosted.org/packages/43/c4/ff96ccc1515ed2fae491fd490dab2ea22c5536ae8de59f176eea07c6f886/regex-2026.11.9-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:80c7f5a8236a751b9f0cfd160c68199db71860daa8609ec30ba79862926c6884", size = 770658, upload-time = "2026-11-09T00:40:57.546Z" }, - { url = "https://files.pythonhosted.org/packages/9c/b2/bbbee563872d031cbe160bddac0846195aa4cc9eb2d7d6b61510598c9c3e/regex-2026.11.9-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:590831103234f8b044dde16352234b24a7966ed685a8f5735da48f4044f5cb55", size = 860933, upload-time = "2026-11-09T00:40:59.2Z" }, - { url = "https://files.pythonhosted.org/packages/2c/4c/8d6060820dea2a10b3b026b462fd47986f54c0590deb13f16f1dadd7df27/regex-2026.11.9-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:961fe37a9e52575360599a4099ebb6d983b71a88e4cb44aef24e230adcb592dd", size = 795245, upload-time = "2026-11-09T00:41:00.592Z" }, - { url = "https://files.pythonhosted.org/packages/1b/32/5093383543e5c86b40e4117c0c6ee082715810b65283494aca48dc517d3f/regex-2026.11.9-cp314-cp314-win32.whl", hash = "sha256:4b9f3e8a40e00a8c46a23e780c06444fc19f048c44e0c533186bdd730a57eb92", size = 275220, upload-time = "2026-11-09T00:41:01.735Z" }, - { url = "https://files.pythonhosted.org/packages/4e/d0/5a472f1404c2217c92ebbd98d65a273cc48adc0a1f2948743ed59a873c18/regex-2026.11.9-cp314-cp314-win_amd64.whl", hash = "sha256:4d2bb485c68c8688201e5d56f6a7cd563ad9ee40ad2a700e77a13fceaac3a517", size = 284464, upload-time = "2026-11-09T00:41:02.734Z" }, - { url = "https://files.pythonhosted.org/packages/28/48/4addd74faf7531f713a9e765cadd1ddcb010363924fee94038e289452e5a/regex-2026.11.9-cp314-cp314-win_arm64.whl", hash = "sha256:dd0777e5cfa8508b0c1a903bfeb3b5859c1842c0b01f3ff39064c6bce3297e6b", size = 284279, upload-time = "2026-11-09T00:41:04.021Z" }, - { url = "https://files.pythonhosted.org/packages/ed/81/c88102ab3fa7eee7badc3f1554224d9012a5cd0fc2d40e3af4a4bb10e713/regex-2026.11.9-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:eb7c95df50b4132f938599f39758da9ee7c73ee66a8f40974160f07567e7301c", size = 502240, upload-time = "2026-11-09T00:41:05.561Z" }, - { url = "https://files.pythonhosted.org/packages/3e/da/ba9d89af353c54727086f705fff7b60bc0994191b76f2a560d69d44c612d/regex-2026.11.9-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:18c2e3de5790cd5d1e1437f4805fda7f16b14931f86312d9542d6014434aa107", size = 298869, upload-time = "2026-11-09T00:41:06.884Z" }, - { url = "https://files.pythonhosted.org/packages/8e/13/d9079948364cbd94f693801c9673ed3f97052848380cd1b4271e6061ef4f/regex-2026.11.9-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:8d5b856217efc33802ae7bbd1b5d98c3117dae9dd6a36b75027291e2b79f72cf", size = 296656, upload-time = "2026-11-09T00:41:07.998Z" }, - { url = "https://files.pythonhosted.org/packages/e4/f9/dbadb579d336487bb226ab02686faa0142cc065426826d1d121cc01a59ac/regex-2026.11.9-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:401055fcdbef098c6054e80e52813f7c937f4209c8c727ec4135df6a6f585222", size = 819805, upload-time = "2026-11-09T00:41:09.202Z" }, - { url = "https://files.pythonhosted.org/packages/64/d7/7e433fcdd1075dfce9423accf478a636b4e9a2078311b86a25ee4973df1a/regex-2026.11.9-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e68a02b7ff911d611c43457b029c76d6bbccf3c1a4f7e336e086a3b6afa1d19c", size = 881836, upload-time = "2026-11-09T00:41:10.783Z" }, - { url = "https://files.pythonhosted.org/packages/15/40/89d31d421367742d2854eba4f6a3d9ae1b15630fae9c7c791415c9a9373c/regex-2026.11.9-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:7f854a607c31bc87b64d9ca13a9d25c6fb57f59f802d2fe871c48b205d06f566", size = 924530, upload-time = "2026-11-09T00:41:12.035Z" }, - { url = "https://files.pythonhosted.org/packages/bf/d5/5e16185a5ba2ebbf83ae24935c32e3a3fc25191347f529c06908b267b6f4/regex-2026.11.9-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2d6a2d52cd32a7cdfef4b3e22417eb7bde912a5624128851bb96aef5dc657067", size = 824544, upload-time = "2026-11-09T00:41:13.233Z" }, - { url = "https://files.pythonhosted.org/packages/7b/14/0e753b59a7ffed4d67c50e2674e870293fdf6f7f95ce65352407427687df/regex-2026.11.9-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f4c1141775f79b742d9ad2d33e058cf06e7219030aadff8d4a132450cc7539dd", size = 793572, upload-time = "2026-11-09T00:41:14.551Z" }, - { url = "https://files.pythonhosted.org/packages/4d/6d/39a0e1ad06a26e04eb1fe2e00322c5d334d74c97a94a9dca01fb7e574eda/regex-2026.11.9-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e886209417f98c2b8b817d531e72731c3fb78f990a402759f4a4c7714f9c5415", size = 805935, upload-time = "2026-11-09T00:41:16.034Z" }, - { url = "https://files.pythonhosted.org/packages/8a/99/1667c4ce3af04e661a0eff2008126ceeca874bc52d7f2895e75b86e7d11f/regex-2026.11.9-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:85f327c6645bc0d924ef407d36aca97ed86bc41da28cabd77b347b1771b5eae1", size = 871258, upload-time = "2026-11-09T00:41:17.79Z" }, - { url = "https://files.pythonhosted.org/packages/ea/2d/124b69673327013b19e6cfaf7f59bcd1e801c1ebf893a056e0a0f6e0f84a/regex-2026.11.9-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:9cb9d77c5c9101f1b6aa3d22f679f7a41a5af6ab536bc7290457e9bfc40eeeac", size = 776374, upload-time = "2026-11-09T00:41:18.85Z" }, - { url = "https://files.pythonhosted.org/packages/83/4b/e4d277fe50a30bec2b98bb7c7e055efb33060c984cc41a75cc2d6b4c9e3a/regex-2026.11.9-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:0ac46eb63c366482a268121d873a08014304ea774d349b9bd2340a622b88a3d4", size = 864755, upload-time = "2026-11-09T00:41:20.316Z" }, - { url = "https://files.pythonhosted.org/packages/25/a7/b1626d1a273b29f6104265488a7b82ef22a81f8a1066fd8d91e098887213/regex-2026.11.9-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:9622c0306e0864fa2cce4e5de97b3f0b7cbb86054c781550fceeb9f9c9bec290", size = 811588, upload-time = "2026-11-09T00:41:21.51Z" }, - { url = "https://files.pythonhosted.org/packages/d8/b8/2581a22a535eeaa301f8b3a71614d7bb8c30b821ba9373b991113b8b4c1a/regex-2026.11.9-cp314-cp314t-win32.whl", hash = "sha256:8cd7bda4894077adf35ec41df18d705e0f8028d40445066c870e517c754d78c2", size = 277284, upload-time = "2026-11-09T00:41:22.634Z" }, - { url = "https://files.pythonhosted.org/packages/10/21/a39d46035c96eaf530eabb6b57751c744c317c0af145240d3f1997d9ecc9/regex-2026.11.9-cp314-cp314t-win_amd64.whl", hash = "sha256:19c5affdda6dfe1bb2e5b0775cf5f4e71e664bcde2daafeec635d34d6f9704c8", size = 287062, upload-time = "2026-11-09T00:41:23.634Z" }, - { url = "https://files.pythonhosted.org/packages/20/64/1a9f6a13e365b1b23bd7ac264ceb8ecadbe962d3354a4cb4a303c88a749b/regex-2026.11.9-cp314-cp314t-win_arm64.whl", hash = "sha256:422c3dd2f8ff069c1050d4f4048bc8fa26fa92df09fcedbe13f77c922f5f7dc8", size = 286617, upload-time = "2026-11-09T00:41:25.402Z" }, - { url = "https://files.pythonhosted.org/packages/91/3e/a94fae619c5c72644732b393f241a4dc65e32a47c76a681b819390214d6f/regex-2026.11.9-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:022c80076ecb4a1e967c6ff9feeecfdfc364183281667056d1953cd345b0b9a8", size = 498649, upload-time = "2026-11-09T00:41:26.995Z" }, - { url = "https://files.pythonhosted.org/packages/41/e3/d468930952cc613f7d63ad375ebe9c1e1b850b3a4c87ed411e8db8cfdd62/regex-2026.11.9-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:639d43b0898a2fd99e10eb5736f022c0fe8ee25bf60250061f8720c47a54483d", size = 296832, upload-time = "2026-11-09T00:41:28.351Z" }, - { url = "https://files.pythonhosted.org/packages/ae/ad/b53184107d89fc00a596d4306483a034d68353cb410cf7b19c7ee511cfa0/regex-2026.11.9-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:569ec6f0f774caeef4e0bbc8161aff2b7f07b1051ebcfc9c2c9eccebe7320b06", size = 294370, upload-time = "2026-11-09T00:41:29.497Z" }, - { url = "https://files.pythonhosted.org/packages/b6/79/0fc94e5a21468d15e649c57ac327ea307712a5a1216557f6a7508d16abfb/regex-2026.11.9-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5f209033452abebfa65f0d388b1f6d4f2b4b2791b3a403bc744c03e80e996be9", size = 807071, upload-time = "2026-11-09T00:41:30.753Z" }, - { url = "https://files.pythonhosted.org/packages/83/6e/3006d97b837a876223484206e4d7700798421958de49c081ce280a38d5e4/regex-2026.11.9-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:1dd7fa70f8b4956acb3e34eb9bea1c7ae3d31509abf979393181eaaa0f00e63d", size = 879313, upload-time = "2026-11-09T00:41:32.194Z" }, - { url = "https://files.pythonhosted.org/packages/cb/a9/f033d7aa75457dd3f6fa8f5701c5b4a5c685428bc7582b9c872a3e9e9c55/regex-2026.11.9-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b10639d37913075b553ba9638be170a87f70c32bd9da0655c3093e7ebc4a8065", size = 918900, upload-time = "2026-11-09T00:41:33.717Z" }, - { url = "https://files.pythonhosted.org/packages/55/7e/378e356b11dbd903d61844215bd16e63e0bdf253c4c8e66cd60ed504737e/regex-2026.11.9-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e8e8fd96057e04660a655f2f7fbc9a9eff6ffe2970ff01c0145a0d425f2d1bf6", size = 809955, upload-time = "2026-11-09T00:41:34.98Z" }, - { url = "https://files.pythonhosted.org/packages/28/2f/5d689c2b7b0083a54e47786699a08a2548cf317316b86385ac0646a56a61/regex-2026.11.9-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:adce69b7696dec985977bc65d025c43dd7f2fa780f4f6e1d467d939884d7f918", size = 789193, upload-time = "2026-11-09T00:41:36.85Z" }, - { url = "https://files.pythonhosted.org/packages/d0/f4/231515fefa3051505ff3dd51d1eee987bcf637958d52dd7ae70d2daebe19/regex-2026.11.9-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:346ac3b9664ca04dd9ff7f422a33d87015657b0674a2830d804d78e987cc1f4a", size = 794166, upload-time = "2026-11-09T00:41:38.268Z" }, - { url = "https://files.pythonhosted.org/packages/9e/10/f935d85b0155d0c621113fcef32aa148ef8d078c16907fbda6950c5d3abb/regex-2026.11.9-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:0c816b00198ddca1040fa2657619b1c6b4c861d158cbad9de77d01fdc44550cd", size = 868221, upload-time = "2026-11-09T00:41:39.706Z" }, - { url = "https://files.pythonhosted.org/packages/a0/5b/9e243ee822c1680cd1468520280a8bc96fe7a8b8ca5a7ed7f213fe9da92c/regex-2026.11.9-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:aa62357d0dd25abd66100369828d6e28b50a5c44001a0fd20f95117c4038c648", size = 779357, upload-time = "2026-11-09T00:41:40.966Z" }, - { url = "https://files.pythonhosted.org/packages/12/67/2273b16db6d6a27bbc2a4f61ec9221d06adf3d1dacfbd6d8120f78e4c8ef/regex-2026.11.9-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:d1627410afc3f5a4b0c4d81dd1bdd1ed3de6407eda6d93524e643cf3891126d2", size = 861471, upload-time = "2026-11-09T00:41:42.048Z" }, - { url = "https://files.pythonhosted.org/packages/68/d8/58f8688bcdb9e482be40e25c13e7bb0701c2ce8c4514ce7af7c635877d81/regex-2026.11.9-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:970201018e997ed4a2626ad894b657035397fa91c1c86eff1b0c8cb9eb03d478", size = 797579, upload-time = "2026-11-09T00:41:43.758Z" }, - { url = "https://files.pythonhosted.org/packages/c1/fd/382230164a17f509c155918771817378516a9ee8bd1b54a5ec4d3dacd7c3/regex-2026.11.9-cp315-cp315-win32.whl", hash = "sha256:1f4c9e7edad6ed655c83741413b350db98b1234a4fa8739bc1ed7167e19ce98e", size = 275213, upload-time = "2026-11-09T00:41:45.63Z" }, - { url = "https://files.pythonhosted.org/packages/9d/1f/3b08cdef84fae97450baf8c60c0f86a85c613ddfa7b106df9186069248c0/regex-2026.11.9-cp315-cp315-win_amd64.whl", hash = "sha256:72770400851673eee68e9d6cfc45c18a20736894e3002506a987a244780df36c", size = 284471, upload-time = "2026-11-09T00:41:46.87Z" }, - { url = "https://files.pythonhosted.org/packages/24/ee/ddf3c916425e7de6774df90e9b36ea7be709233f6e617863f9eeaf855211/regex-2026.11.9-cp315-cp315-win_arm64.whl", hash = "sha256:1e8fe618fe5eeceb827db2b49750fad345be0e6145c5c41ed701ee27e081ff9d", size = 284289, upload-time = "2026-11-09T00:41:48.301Z" }, - { url = "https://files.pythonhosted.org/packages/a6/d6/0e0566737f61954b66df56cee68a7412df3fd8f5a9325f08837cc641b9f5/regex-2026.11.9-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:6dc0dd2d31bc0e2301345c3b20f64a6d864218196c7c9ea2b96788e76b964578", size = 502328, upload-time = "2026-11-09T00:41:49.337Z" }, - { url = "https://files.pythonhosted.org/packages/9a/1e/7f95189e75cd26a634c9832b469f620bf45d02a6e2be184a1169ee7af61a/regex-2026.11.9-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:6a1ee54c1e237fee890ef7045951613147fcf77a2c898229de44f165e5650aff", size = 298773, upload-time = "2026-11-09T00:41:50.737Z" }, - { url = "https://files.pythonhosted.org/packages/f5/cc/7e5406a25fe6cf378e770858133b044e451349ef2c1f2977b68dd061a2db/regex-2026.11.9-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:2bebc58114814ed6d78cc3d27b70d4f2dceb8a2e5d23dcc7d831809e86d3bc3c", size = 296831, upload-time = "2026-11-09T00:41:52.067Z" }, - { url = "https://files.pythonhosted.org/packages/f8/5c/6ad943248f553ce669fd2a6ad75ec27476f90a40e0f5173337db7089c13d/regex-2026.11.9-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9bc2cb2aa025b89ebe26c8dc3c1edb1c6b22be9dadea030a89f3a477faf646e8", size = 818469, upload-time = "2026-11-09T00:41:53.192Z" }, - { url = "https://files.pythonhosted.org/packages/a2/b6/be6a30c8bb5bc32fca59e9e6a7ace27fc5f8626b5b11a6ecca9f2d7834c6/regex-2026.11.9-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:499313286c8ae346f19e6af6f78f45c356de293b37540fdea5f4309a5aa59b21", size = 882408, upload-time = "2026-11-09T00:41:54.347Z" }, - { url = "https://files.pythonhosted.org/packages/37/3d/a6fc734740e030e1479ff081c5af669c3543f6f04008c792c5566b30f07a/regex-2026.11.9-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d77014fe27bfc3565a0ef706ced0f7d5471937bce9b7ce38c46deeaa9f4b3963", size = 923235, upload-time = "2026-11-09T00:41:55.551Z" }, - { url = "https://files.pythonhosted.org/packages/ba/7f/c1860577baf5c3acea63fa812b7bb510825b28c44b474db00900e7cb3ab0/regex-2026.11.9-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e4498f31d71819a16b32e1a965bb587c7aaf153848c451d1e384ede77dc6a134", size = 822410, upload-time = "2026-11-09T00:41:56.803Z" }, - { url = "https://files.pythonhosted.org/packages/28/af/692419879b97a63e8342ccbd138329f900af38408f0b080d72a5a5fc9160/regex-2026.11.9-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:04e1c78cba5e3edd5400e9d7319a3036f652faa599bfabbf888fec584a9a4772", size = 795527, upload-time = "2026-11-09T00:41:58.169Z" }, - { url = "https://files.pythonhosted.org/packages/24/53/1ba04321ce8d15d219710e95f03feab54ca6a19ecad329a42efe7c46c873/regex-2026.11.9-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:5774579fca3431bd77518529d1ba54480d075396bdb0533daa0daa4db86e6594", size = 806153, upload-time = "2026-11-09T00:41:59.309Z" }, - { url = "https://files.pythonhosted.org/packages/e5/dc/3933476fab57134867d20d214d57393fbdb82a5a285083633bdf956372d5/regex-2026.11.9-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:34087251368439c8238cbf2bde88a8e89fd865a2a61266a5c64b360414c7fe04", size = 872784, upload-time = "2026-11-09T00:42:00.636Z" }, - { url = "https://files.pythonhosted.org/packages/e9/53/e44fc4efa4de6dd29fc0f2e237f944a392478611d54d1af43e45c7726626/regex-2026.11.9-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:4cb820ff2fdcf610278c74dcfd45857b5177429e30bd0b7d1164855a011cd58d", size = 784277, upload-time = "2026-11-09T00:42:01.72Z" }, - { url = "https://files.pythonhosted.org/packages/fa/a5/a5e6f6b5904712646ed10023b75746d9492616f75f8ad9d8045fd28f04c5/regex-2026.11.9-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:cb152514d21e3a0440e4c30ff2323f3bbc48de3c1d1aaffe0494470cf5566a42", size = 865578, upload-time = "2026-11-09T00:42:03.197Z" }, - { url = "https://files.pythonhosted.org/packages/09/60/73045aa8b48f37e12f18eb6ee5dee9573a31f381f987f1a2d0ea27310537/regex-2026.11.9-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:38cd15cf8407a4220bf387657cbd38d961161d152c08c731fc2e05fb45a00ab9", size = 809333, upload-time = "2026-11-09T00:42:04.407Z" }, - { url = "https://files.pythonhosted.org/packages/71/de/9f668597839d8abb969846be416ed6982a4ba10b83445f241f27752456cb/regex-2026.11.9-cp315-cp315t-win32.whl", hash = "sha256:c68ed3497146b830d27642193612bb6ac51cb70dd73b5f35f07b37cec915b795", size = 277479, upload-time = "2026-11-09T00:42:05.728Z" }, - { url = "https://files.pythonhosted.org/packages/cd/af/af2858db09db8ff0b9f50e67610da2d71517defc62f6eada14a1405c8930/regex-2026.11.9-cp315-cp315t-win_amd64.whl", hash = "sha256:83ee345b9feb7973c408187778fdf2f2498b54a51bc0b92d08b9b7468ddfb5dd", size = 287021, upload-time = "2026-11-09T00:42:07.23Z" }, - { url = "https://files.pythonhosted.org/packages/05/29/f38c146b8e4b9e9d844cd5387ff82b18a35efe34795366a2a98429695584/regex-2026.11.9-cp315-cp315t-win_arm64.whl", hash = "sha256:2fd69109525129c1823765f34d650247bcd20065eb842832b99d3e512dec0ed7", size = 286551, upload-time = "2026-11-09T00:42:08.629Z" }, +version = "2026.11.25" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fa/b8/61d96601b737305a04161da340499cbb3299029d4ea0f9c717bc35977c2b/regex-2026.11.25.tar.gz", hash = "sha256:d3ea8d9698f13f3fd08c65f9bed0bb07bcfff80b61dfa14d86b8cc398f886588", size = 423456, upload-time = "2026-11-26T01:32:26.082Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/50/5d/8d67292bbb872cc70487fc6b49bb556197fc482cac2ae9bee43a80d747ee/regex-2026.11.25-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:f5f083a0d66c129ecbab9ec677ceee7254672f08a7cebda49f172dbb5b96acf4", size = 502237, upload-time = "2026-11-26T01:30:17.215Z" }, + { url = "https://files.pythonhosted.org/packages/84/da/8e19706a7d3f682640d47c9b49d9cd1fae1d14074aa0bdfada62a61ac945/regex-2026.11.25-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ac0ce45ad2deb12c125762bdad5e489d42e83e29f8fd45eca2f08e3a55c60bcc", size = 300096, upload-time = "2026-11-26T01:30:18.688Z" }, + { url = "https://files.pythonhosted.org/packages/41/81/b47cbd606647371eeb6c05bf7eb4e39badcf29450bea9deb6ca2b17807fb/regex-2026.11.25-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:544c87eb49bdef2069561c678ad7ed81998a4f026f9349db9e1cd09dfbb2968f", size = 297320, upload-time = "2026-11-26T01:30:19.934Z" }, + { url = "https://files.pythonhosted.org/packages/7c/af/0233718c6ab7ad6d8790dc2a00f263c46d1e960d1a5a54c963ac5814b5a7/regex-2026.11.25-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:036ae3dd8d501bd3b4daa47b17a2c1e4450b9707bf8e44b0a9b57d25ddd4c1b0", size = 815488, upload-time = "2026-11-26T01:30:21.482Z" }, + { url = "https://files.pythonhosted.org/packages/12/3b/ef3a3615aa8a25cb3fc363df9920bff8acf8090fe51a9c64e238c5b32ed8/regex-2026.11.25-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a623979964d4623c23f488079e38ceb166faba6892c12c8715435b8c378b727f", size = 887854, upload-time = "2026-11-26T01:30:22.781Z" }, + { url = "https://files.pythonhosted.org/packages/20/56/1d70decc9558c056374c609eba89b99b04fce54b8babb1fa96c6e1906cd1/regex-2026.11.25-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:cc985135d666fb73d0c6d5847d98953e10f78d770882ac48ccac29777abd9cf7", size = 926991, upload-time = "2026-11-26T01:30:24.038Z" }, + { url = "https://files.pythonhosted.org/packages/79/a3/8950bf3b900d347cd205ec3f634d6571b6eb3128ad3f37ea6319f75f68ad/regex-2026.11.25-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d3c40add70ae031f1b4922f30c4ecdc32db3adaa80f4c1ea1129fe1f43e881df", size = 820537, upload-time = "2026-11-26T01:30:25.414Z" }, + { url = "https://files.pythonhosted.org/packages/d9/87/ab9aabb0e1955c223e166eb9727c212a99df9831ebd9c45996b134544f24/regex-2026.11.25-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0df60c883951880070720095b047d276818209c7e2c429a87d147478e7ed7e10", size = 791844, upload-time = "2026-11-26T01:30:26.877Z" }, + { url = "https://files.pythonhosted.org/packages/d4/77/3ca85babd0e816ce918b05c8089fd59317adb9b6f434ba6975487089e0cd/regex-2026.11.25-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f134964219841ef2f6a0cc262a8afd7ee97539df3d3d54de6859d45b1b47f4bc", size = 805341, upload-time = "2026-11-26T01:30:28.365Z" }, + { url = "https://files.pythonhosted.org/packages/85/a2/ecb428c9d93d7ec5b3f527bca4368144ecb2daf4c60f2b12c8c254a1d350/regex-2026.11.25-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:c38aa91921224ef128e43764983655543d8c6cd11dc1d2c7912b9f5cdbb6e1a6", size = 875250, upload-time = "2026-11-26T01:30:29.603Z" }, + { url = "https://files.pythonhosted.org/packages/20/28/af10a88c8dddfdd9b5da0ca66a0789c52c80eb88031ac4415f6cc1e9cb3f/regex-2026.11.25-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:0cbe655d0760f0c35b3bc96b735958482299e38628c34c7f984e37ee646c0f3b", size = 779896, upload-time = "2026-11-26T01:30:30.835Z" }, + { url = "https://files.pythonhosted.org/packages/35/e8/158e6adf07acad926802d2f0e555cb2d02cec16a293949a33bd0f82e03a3/regex-2026.11.25-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:4a1741e7c48ce011ab9902c56dfe3d22bfe4d157c1ff70809f2191db2330144f", size = 867646, upload-time = "2026-11-26T01:30:32.412Z" }, + { url = "https://files.pythonhosted.org/packages/0b/d9/0152a2e72e12200331be7d75f719e1fce93684934ab176a0cedd58405df5/regex-2026.11.25-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ea59e34dafc84af1747280ea7fd0e8d6ecb6be5cbfd85009cdeead2ae4faa8ee", size = 807636, upload-time = "2026-11-26T01:30:33.574Z" }, + { url = "https://files.pythonhosted.org/packages/a8/68/00356ffee767825152c8962df5e37718f7983cd1c98896b8d0a6d1298155/regex-2026.11.25-cp312-cp312-win32.whl", hash = "sha256:62e262fa38e97bfaab449ff0386988e1b316110ab421345331bcd64df2c5aa4c", size = 271276, upload-time = "2026-11-26T01:30:34.756Z" }, + { url = "https://files.pythonhosted.org/packages/8c/91/2252ad1447a25bececd919d4c58437f485013c3e9fb1a0357a59a8055c6f/regex-2026.11.25-cp312-cp312-win_amd64.whl", hash = "sha256:d9c71646bbdea21925a31a710ea0b0c52d5fe92d18870f59561619e3b118b13c", size = 282134, upload-time = "2026-11-26T01:30:35.884Z" }, + { url = "https://files.pythonhosted.org/packages/d7/9e/bc71006d345461b21fc0f9ca068e32eea3cdb77782510c8e1683083ac03d/regex-2026.11.25-cp312-cp312-win_arm64.whl", hash = "sha256:63657f12028add3eb6424ac46060b67e80e84ee23ff03ff1a169d6bd4be1e0d1", size = 282511, upload-time = "2026-11-26T01:30:36.995Z" }, + { url = "https://files.pythonhosted.org/packages/e2/3b/2bb2067f1a7992e0ee3a46b746a14a072c05246445b2f45c8beda9b3e014/regex-2026.11.25-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:fd5308c9dacb99ea0512106ded59992f271c6e0f2b7dea505df5ee0906f27321", size = 501991, upload-time = "2026-11-26T01:30:38.426Z" }, + { url = "https://files.pythonhosted.org/packages/5b/f0/10fbbc8ec428a4930c0ec0ff8c51b3e4d82901f98530f90e855d3381e225/regex-2026.11.25-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:aa00a255e068d61e205485c2413bfa62e36555dd1d246c02fe7d382b91a61a76", size = 299977, upload-time = "2026-11-26T01:30:39.61Z" }, + { url = "https://files.pythonhosted.org/packages/37/39/ae48fae5f7a2576b829dee35e231c9d48e51357f37780989b02601a0174e/regex-2026.11.25-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e8f3c8b122c5ba50de9469c4aeb77ca0b12ea20cc7162a463eb9b0028b20c916", size = 297125, upload-time = "2026-11-26T01:30:40.688Z" }, + { url = "https://files.pythonhosted.org/packages/80/48/5b7fb515b274fba2b13e6a4f6f35b8b8bdd0e46c88b4a3fac08b2cd3d848/regex-2026.11.25-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fe6822dc36d11f59cd5cdb4544491c2a62842ec7a929904304da5a71ff7e0ed0", size = 815569, upload-time = "2026-11-26T01:30:41.77Z" }, + { url = "https://files.pythonhosted.org/packages/19/fa/b4474edfd24755bcb71d269868b8598ad3b3724e92df95cd9f7fcf46e330/regex-2026.11.25-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ded3e3fb03e5d3f355e481d0cbd56c01ecdeb504f850fee3044e5c1c449d72a9", size = 887716, upload-time = "2026-11-26T01:30:43.254Z" }, + { url = "https://files.pythonhosted.org/packages/c3/4c/ae4fcc548746f3fc296e23da976da74fb69a7f97c0d8ab7b08de827495f0/regex-2026.11.25-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:172a9e24d11f83b9b7c117d649d3aca945654c9f0e7b82bc58432e1587153961", size = 927061, upload-time = "2026-11-26T01:30:44.47Z" }, + { url = "https://files.pythonhosted.org/packages/ae/98/c701e18db4ab2ba29032704d222095ac8190e4bffc8a52ba47a074e84da9/regex-2026.11.25-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2e15e2991c4bcb5e52cbdd4660c60fc73d805671aa70b4cf5800167ed5e1caf9", size = 820557, upload-time = "2026-11-26T01:30:45.893Z" }, + { url = "https://files.pythonhosted.org/packages/36/af/31deacb4ac2df4ebed5b5c42f186d662f028a9a7ee1ab1e6680677c99162/regex-2026.11.25-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:53c52450e5e92fceb23a4f10ecac4de31bf026fa41769c69db2e493c5b17989a", size = 791995, upload-time = "2026-11-26T01:30:47.415Z" }, + { url = "https://files.pythonhosted.org/packages/44/a2/be39859fa7818b60bcc77bc0aa28baf69cedcb35f0574f6f3a810160ac68/regex-2026.11.25-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:55e5af78bfa1d45613451cfcf71340561b3f46ba12f6bd69bbe97e03018d51b2", size = 805418, upload-time = "2026-11-26T01:30:48.594Z" }, + { url = "https://files.pythonhosted.org/packages/a2/46/cd363650307484133ba4086f1a2047afa021ba1e710e81ca44b8d7e41b36/regex-2026.11.25-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:b3c1116c7bc61a7144583089332ce91b33337cad3aebfd50ced117f45328e2f4", size = 875332, upload-time = "2026-11-26T01:30:50.077Z" }, + { url = "https://files.pythonhosted.org/packages/dd/03/7018f56eae2f7fc02ff310580a80355e861bddf53ab99ed73cbf658b8699/regex-2026.11.25-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:9d0a5a25ede7a05c716e57459d592f1e4ffc40b1bacc164b8b74084bde313a7a", size = 780015, upload-time = "2026-11-26T01:30:52.133Z" }, + { url = "https://files.pythonhosted.org/packages/c3/85/aac6fe44e5803d423d81cfa9e1a28b5d94511494bc0577d1b6928c3d2128/regex-2026.11.25-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:b4b068f0c1e69f04c69c2c7c047f94d8343a5b1ba90512b43068ac192a3e1765", size = 867706, upload-time = "2026-11-26T01:30:53.439Z" }, + { url = "https://files.pythonhosted.org/packages/d6/2f/e4644a0f61e9e1a984817dd63ecf67a230ed4c6c85a966f5f325765058b5/regex-2026.11.25-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:8ab0e6f9657f7460c886af5e0781372cee243705c31fab29dc43379860853902", size = 807696, upload-time = "2026-11-26T01:30:54.638Z" }, + { url = "https://files.pythonhosted.org/packages/da/4e/d1a7fe057b332393e5bf91a2d72511fe6f970bd084952f6c7f5c89e81e2a/regex-2026.11.25-cp313-cp313-win32.whl", hash = "sha256:f07cf9bfecf966443b8b570a7a65e97ff5352c8a804256facb2145ff8e09d95d", size = 271265, upload-time = "2026-11-26T01:30:55.727Z" }, + { url = "https://files.pythonhosted.org/packages/6d/9e/e7c8bf7ff8db4315eff70304aa414901f9318d102ab48d294ff7c70e9989/regex-2026.11.25-cp313-cp313-win_amd64.whl", hash = "sha256:58f352a5eb5d490bf33899bcf0c9a494c462c2361803f0233a36e407807eb6ca", size = 282121, upload-time = "2026-11-26T01:30:56.836Z" }, + { url = "https://files.pythonhosted.org/packages/19/84/84a3b2846b672dea6020e7c5a6f6bad961c5dd6fc3783aa081125df73454/regex-2026.11.25-cp313-cp313-win_arm64.whl", hash = "sha256:f8b7aa413685fe1c4c2c435bbdf6530d8e5970dd7d90a39c48a828030c7aaac8", size = 282492, upload-time = "2026-11-26T01:30:57.938Z" }, + { url = "https://files.pythonhosted.org/packages/00/41/2e6beb12c2a048122db27c677f431be58a60a7abf1c3d9d22d4dcd381ccc/regex-2026.11.25-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:551fafbe6eea758decf5d092d17d337dda4dacafcd9a5217718c9b6de5aaaaaa", size = 502003, upload-time = "2026-11-26T01:30:59.353Z" }, + { url = "https://files.pythonhosted.org/packages/6a/e2/9db015c0ac28d4fb4d919004efc0d9408c0120f5cd0bcfbb6136993d7f71/regex-2026.11.25-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:2fae87c56eb07b595bcc9a0b5a769bf2ce28255ac69274d92caff5851bd78d6c", size = 299951, upload-time = "2026-11-26T01:31:00.421Z" }, + { url = "https://files.pythonhosted.org/packages/81/d3/f3af4fdc2f5b9dc83f60c40264e1460aa8dbe74b37d2c2ca65b8056b7d6c/regex-2026.11.25-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:390db23deb9b207af2f995866f6547754fea5509a5708f7cf03a451e7213e32d", size = 297166, upload-time = "2026-11-26T01:31:01.955Z" }, + { url = "https://files.pythonhosted.org/packages/39/7a/11cbffde5e2b66f8626e754205906cdee1f104138b5a7472c6901165bff1/regex-2026.11.25-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2761609703da9991302e5bfa055e9443c355674442e20c2f1fe6ed9cd5974e5d", size = 816410, upload-time = "2026-11-26T01:31:03.135Z" }, + { url = "https://files.pythonhosted.org/packages/ce/40/bcb11c540903da1d312f8bbfb510cb5ad7d87323791129382d3de2570b94/regex-2026.11.25-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9e20b85219d89d07359d800e2b77038e6c0998e34b7de23acf218f39acc18ca7", size = 888151, upload-time = "2026-11-26T01:31:04.36Z" }, + { url = "https://files.pythonhosted.org/packages/0d/bd/fd7f03e6cba57bbe692d4f8af9002d3ba772e9b8af60bf3f210c92631505/regex-2026.11.25-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:30e9b4acf05340c6546988aa2f89407271fa3817b94cc7347c8c3753b88e288c", size = 926257, upload-time = "2026-11-26T01:31:06.049Z" }, + { url = "https://files.pythonhosted.org/packages/71/95/8fd9d21e786b9e27efdff0155ee7ca4c237585d1f44ef90b4d46666c27dd/regex-2026.11.25-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9e9179544aefc7ec0db23a54b0f9eb9afc9a45110deeac024f16d2efd8b2e79b", size = 819741, upload-time = "2026-11-26T01:31:07.468Z" }, + { url = "https://files.pythonhosted.org/packages/f1/9e/377eaae1acd64e5ce4df1523fd930e82ef23f6aabb18e21572c348d64b23/regex-2026.11.25-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7af60e7494bdffceaf3d8ded53241058d97912bb495b0d06d87060dfcb84bdf4", size = 792981, upload-time = "2026-11-26T01:31:09.208Z" }, + { url = "https://files.pythonhosted.org/packages/68/78/6845abddb6e5664353be42ef3fb102f663c978114d67129d4b1380ca6264/regex-2026.11.25-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7497344c407e69eee788618e55a67281705c10a3da122b29bd0d6ad2e11e3d17", size = 805856, upload-time = "2026-11-26T01:31:10.532Z" }, + { url = "https://files.pythonhosted.org/packages/99/5b/9ae988869fe3dc405b960f49c7c6847c7459ff5737aca8f70892af675c24/regex-2026.11.25-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:d7d7f795cee31a68df89de39bada55784d5f4186d12485d7b689547c01922e7c", size = 876128, upload-time = "2026-11-26T01:31:12.249Z" }, + { url = "https://files.pythonhosted.org/packages/a7/d6/a7efff54410f18fd0d3df6ae25a1adc278da90eff3ce0e3c5c4320bd1cdf/regex-2026.11.25-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:5eb2476890382d036eb66926bd5bf6607084507d2fad62beb3776866053d9fe6", size = 780685, upload-time = "2026-11-26T01:31:14.085Z" }, + { url = "https://files.pythonhosted.org/packages/92/a5/54050a412428b39d70848d09c7bc48aea61fda998510e17244e5fce98177/regex-2026.11.25-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:f126ce7c1207058aed2cd875ab242867cb4f2bef06f49af69431af0a77e0ff51", size = 867582, upload-time = "2026-11-26T01:31:15.564Z" }, + { url = "https://files.pythonhosted.org/packages/6d/15/923eb2b95587a390d84a5da48cb90a98b70f3259d2b4c2ebf68921859e83/regex-2026.11.25-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f23936a1667efc970c907e2ce762f39e72c188c55bc508ee67969a650527f416", size = 807221, upload-time = "2026-11-26T01:31:16.851Z" }, + { url = "https://files.pythonhosted.org/packages/3d/60/1ede4972c1c2f2edd7004dc8ef022c4b4f8fd6e7ad4a8ffc2fb9c74a14f8/regex-2026.11.25-cp314-cp314-win32.whl", hash = "sha256:6f076dccd11c41c14064229eb3c2e1f1fb711782f558777194e9ab917bc64fe6", size = 276831, upload-time = "2026-11-26T01:31:18.095Z" }, + { url = "https://files.pythonhosted.org/packages/68/e6/e4bc6ca4aa77961a93de8c6ecd24d22ea3e78dcf991aa5a62c369ab92406/regex-2026.11.25-cp314-cp314-win_amd64.whl", hash = "sha256:5a1e00b4c20f891c73f2d7876466386a6d0265bc6a07a44cd91b39fe6079f880", size = 285836, upload-time = "2026-11-26T01:31:19.356Z" }, + { url = "https://files.pythonhosted.org/packages/0c/dd/03d4dcf50c50234b26d549f6fd409e3cc0112ef4e9383106843847310028/regex-2026.11.25-cp314-cp314-win_arm64.whl", hash = "sha256:9069362b3e3ad61f2a38e7df7c94d71f49fd48c101dcb3e442497c176932fd40", size = 286679, upload-time = "2026-11-26T01:31:20.608Z" }, + { url = "https://files.pythonhosted.org/packages/02/69/eb5911f3269975c739838a5c76904dfdc6773b747b941b1d9155ba7e3c68/regex-2026.11.25-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:0ae36434bd171d7d138a5b9607ab03568f3ef39bd7e608017c41b5785a3b94af", size = 506219, upload-time = "2026-11-26T01:31:21.651Z" }, + { url = "https://files.pythonhosted.org/packages/1e/02/8c76f05a9a64e99131f78ea8d64d5c08c31281acd50a525fe75448cd51e6/regex-2026.11.25-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:70df56deca24d25e3dc3d0559d2cbfc058225205f786413ed2a8f33c77127035", size = 302208, upload-time = "2026-11-26T01:31:22.849Z" }, + { url = "https://files.pythonhosted.org/packages/9e/ac/93605804f0a9e223124b3cfed99f975d3613e7859a3538620cd2e7f194e8/regex-2026.11.25-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7ecfb3fe9d1ba9123747e0593f300129b77a2270453eecfb80c5f9f33d0ba6de", size = 299831, upload-time = "2026-11-26T01:31:23.927Z" }, + { url = "https://files.pythonhosted.org/packages/e5/59/09b596fe63d0f71351a5abaa7f211b72a7b95d11246bff6913424dcbc4e1/regex-2026.11.25-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c40c3ddf08d4c7d73f49305ac82f9c5e573ffae2271bb8e6e17c9e45e892abf5", size = 828981, upload-time = "2026-11-26T01:31:25.146Z" }, + { url = "https://files.pythonhosted.org/packages/fa/07/a875974d15fabb2d9d059744c10741d1a4659bed2b41138b3abd7a4172c2/regex-2026.11.25-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c3a5b2f6a5fbdbf8be027b2c62d67a67fce46acdde362ee00cdc7394e6031063", size = 894060, upload-time = "2026-11-26T01:31:26.938Z" }, + { url = "https://files.pythonhosted.org/packages/59/c0/50fec91fb6e2061f02a31f00379ce09fe0d8d9c18a659fd421669d9601d7/regex-2026.11.25-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:70ecb2a84eea54ee60a06b17b0a7a3ca6891ea34d49cdb8d34e8140299636acd", size = 933774, upload-time = "2026-11-26T01:31:28.161Z" }, + { url = "https://files.pythonhosted.org/packages/92/2d/247fc7d8f03f5d50214d4299bb1d1423db926f1993dbd6fb13cce2f2aec5/regex-2026.11.25-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:41e8af4901110956eef9dd3aaaeb827a93d6a4a2def130f210c14f479bf94186", size = 836023, upload-time = "2026-11-26T01:31:29.789Z" }, + { url = "https://files.pythonhosted.org/packages/a2/bf/72147d0da881e2ca9b2783c228a9857f0a91c3f97840d493fad33ee02e88/regex-2026.11.25-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5b9e701281509047881d411b9fa84c5ca49207f0d1c2099f80f19244ee13df92", size = 801212, upload-time = "2026-11-26T01:31:31.24Z" }, + { url = "https://files.pythonhosted.org/packages/60/a0/a584979a136bb2d1d91b5915a233e3426cb207c7c98c4b2199b968591794/regex-2026.11.25-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:55c6d6e8e07cc90282046f30b4983aa9ffb47c8a35687ef6dbd02128190dcd70", size = 820281, upload-time = "2026-11-26T01:31:32.511Z" }, + { url = "https://files.pythonhosted.org/packages/37/75/339a185c251d935cf9bc7918a31be6e5cab720617dfad47d18af9ad730bf/regex-2026.11.25-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:9c210b085aabc41b2b6440b198822656f6453c059b7c9a8679955fb2d9c956fa", size = 881259, upload-time = "2026-11-26T01:31:33.743Z" }, + { url = "https://files.pythonhosted.org/packages/dd/b5/1092299befe796478ffd63f0b11468c3b16defbe603bca6e0d72d6be066f/regex-2026.11.25-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:ca1138b5d6a14e4d403d979fdeddbfbca4f61cdc148ab5a350696a64e9e67b2a", size = 790588, upload-time = "2026-11-26T01:31:35.131Z" }, + { url = "https://files.pythonhosted.org/packages/de/14/612c0add475c3bff8112310218411ce23c8ca8b7f4e9ef245b3ee687ebe6/regex-2026.11.25-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:55e51870b2c9c886ff35b6ba9b6c347cac637395daf7725549920b45d6594e04", size = 875055, upload-time = "2026-11-26T01:31:36.564Z" }, + { url = "https://files.pythonhosted.org/packages/71/28/008c0e1e22ca65b7ab4f9e9f0c14f38ab92e0ec816b6261b7730b07dda8a/regex-2026.11.25-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3035b65568abb6d5984e137ce96d2e4fe98847cfabec09d7de5529c4afe2d436", size = 821973, upload-time = "2026-11-26T01:31:37.766Z" }, + { url = "https://files.pythonhosted.org/packages/35/db/56a7e025d4a2da4f8eb5535d9484ab3b27be96996cc4f3ebefb34c3aa0fe/regex-2026.11.25-cp314-cp314t-win32.whl", hash = "sha256:cc93755167512431dd371faa87c7b7109bbb583cf4720e05ecd4b81fea84fa26", size = 279043, upload-time = "2026-11-26T01:31:38.868Z" }, + { url = "https://files.pythonhosted.org/packages/b3/8d/f6b9c7a57201253c91f1f2708f4559dc06edc262e877f145e46266414395/regex-2026.11.25-cp314-cp314t-win_amd64.whl", hash = "sha256:ca8a21c1e66e72cc4d21c9ab12629ad3f696b8d8f4d70654294d1e219ef653e5", size = 288388, upload-time = "2026-11-26T01:31:40.226Z" }, + { url = "https://files.pythonhosted.org/packages/b4/cc/b5925de4b2abc783fc17c76b0b3d55d95a5cefa9e748c019cbca2954e6ab/regex-2026.11.25-cp314-cp314t-win_arm64.whl", hash = "sha256:a443e6160c1f04738b6979a1a8983c578c2b53ca1c98e1fc2a39b3988a07aef3", size = 288899, upload-time = "2026-11-26T01:31:41.439Z" }, + { url = "https://files.pythonhosted.org/packages/7d/bb/4586a378d4f205eead50acbf8d5550bf7beab78a52fdd805d97fe788ed42/regex-2026.11.25-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:edc38e9c4f5645245bf18ebd56888fbf9653f063693c9e62ed8676e6326bd666", size = 502180, upload-time = "2026-11-26T01:31:42.6Z" }, + { url = "https://files.pythonhosted.org/packages/98/28/c6c224924ee4d135c7140fc312bd5040773c9c4d9c11cb960279a9bd5f22/regex-2026.11.25-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:cff6170b5df5ca2ea1f3a9e04eec1e1371da35f6a8696a64c8f89ac275b402a3", size = 299948, upload-time = "2026-11-26T01:31:43.714Z" }, + { url = "https://files.pythonhosted.org/packages/16/7e/729b169d63779232d75fe3eae704a445d9da625015ea0bfd4264f8343f3d/regex-2026.11.25-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:0cdcd5a496f0d237a6b72b3ddedbe977a5389285899323aa9996889bc65f9ac2", size = 297386, upload-time = "2026-11-26T01:31:44.869Z" }, + { url = "https://files.pythonhosted.org/packages/46/cc/d5c1fee2bfdbd60f76232fa0bc65bf0644c4e691570bf32fc0509a6be7dd/regex-2026.11.25-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c5c7b014a56f67a91d421f6ee67583973d76ab4c2eda777ea597bc937b21e6e0", size = 818408, upload-time = "2026-11-26T01:31:46.453Z" }, + { url = "https://files.pythonhosted.org/packages/53/07/7eb8b833bc8b031f164993d6612d7ebc563f8802c6a76e00ec5f3aca41b7/regex-2026.11.25-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9907c02eef3602a8917c16ae40b8ff7a089ebbfaf0ed3f1e8c73351806a78a2f", size = 888562, upload-time = "2026-11-26T01:31:47.632Z" }, + { url = "https://files.pythonhosted.org/packages/48/77/652947b497c13a3865bf38864b824dd475f0ffde32b404060e4fdd207a8d/regex-2026.11.25-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:de9dc164e9937dc7b7228dbc6113adb7bec5ce5b6ce150ea576a3024e8708843", size = 926884, upload-time = "2026-11-26T01:31:48.885Z" }, + { url = "https://files.pythonhosted.org/packages/72/1e/04516fe93f9ee7afbc10dd3217bc33b71a0cc017dd1b1987d71ea2c43e94/regex-2026.11.25-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:925b78c3f4c2e39cf51d432150b6fc9467894ecc95f8a3ea1103fa5280bec08e", size = 821928, upload-time = "2026-11-26T01:31:50.152Z" }, + { url = "https://files.pythonhosted.org/packages/00/a5/418124d21b6028087f78694bfc302932579ef5f95446ce465f549b77fbdd/regex-2026.11.25-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8ade7b854a64f60b383248ae1a71991d578f3da388cde4cc9719936e00cd974a", size = 796051, upload-time = "2026-11-26T01:31:51.644Z" }, + { url = "https://files.pythonhosted.org/packages/46/77/8ff20d3bb8b821dc6c6c3b35d17c8fbe220864d190c769b3e035edec754c/regex-2026.11.25-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:6311692b3a004966b179316ee7ed2eae0814897efe77c9c61a5c63bef53012fd", size = 807698, upload-time = "2026-11-26T01:31:53.197Z" }, + { url = "https://files.pythonhosted.org/packages/42/d5/307076742814cb7103bc1110e1c828ed9c43c3b2b52e1a43fd20b20e51ef/regex-2026.11.25-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:e0027c0aa9622bd30de8ab918f9fba713dfda714fdd4f59b476f22d58bc0ad2d", size = 876484, upload-time = "2026-11-26T01:31:54.851Z" }, + { url = "https://files.pythonhosted.org/packages/0a/64/2a7371e7d640c683a8da4f3687588ba8a338164e4c14f0dcc143c57efd3a/regex-2026.11.25-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:2c965bb604d1a0b41afc13e17dc08bf1a7e60cccf96ba7cb35d28627aa64d5eb", size = 787039, upload-time = "2026-11-26T01:31:56.915Z" }, + { url = "https://files.pythonhosted.org/packages/c2/ef/f07f125c4f9505298dd9d8234d072c69a4b212c42ad3ffc311b9d1def845/regex-2026.11.25-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:f61f961d158c3ead28f95ae7adb92027c37da2f14bed3b4887c7623fcba759ff", size = 867899, upload-time = "2026-11-26T01:31:58.175Z" }, + { url = "https://files.pythonhosted.org/packages/3c/c6/9979aa9ea18b33343e52428b5efa220c6501f696436ed692acc9d474e4f1/regex-2026.11.25-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:4fa638c71088f8576ae56045f468c1f6ee7ef4e39d93cd81723eb390aee015df", size = 810429, upload-time = "2026-11-26T01:31:59.581Z" }, + { url = "https://files.pythonhosted.org/packages/d7/66/0cb1b1d9975ac9259e2bd42c7d32a1e3888dd4cf76d38706d8acda0546cd/regex-2026.11.25-cp315-cp315-win32.whl", hash = "sha256:350b61e6e623ada1e7ecd1c4fe9b5f62739520d631dd18f260f220580b19a80f", size = 276839, upload-time = "2026-11-26T01:32:00.92Z" }, + { url = "https://files.pythonhosted.org/packages/3f/ec/3601195c0a0dc6f412af9e7c92d4152fc66ca421518c85708f65f6b8b0dc/regex-2026.11.25-cp315-cp315-win_amd64.whl", hash = "sha256:32ff2775978074ab8f8545d3bd06d5db431573c84b1f8af05c94547b71fe0f21", size = 285840, upload-time = "2026-11-26T01:32:02.076Z" }, + { url = "https://files.pythonhosted.org/packages/7a/5d/348132cc3065df3c0e04805aa3ac71bcd77c8911db435b0db2039487d3c0/regex-2026.11.25-cp315-cp315-win_arm64.whl", hash = "sha256:0115f4c16874c33ca151825796f9072e8479a15ca478b037f7a66274fb5b49bb", size = 286692, upload-time = "2026-11-26T01:32:03.287Z" }, + { url = "https://files.pythonhosted.org/packages/fb/37/525b9d63d95663028464237c762492b7c7d7699358c969ac5722f74ca38c/regex-2026.11.25-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:9f012919f1e5a5a3626b8fad585a1df87fde28484e9304d1eae3193939c6cd02", size = 506358, upload-time = "2026-11-26T01:32:04.458Z" }, + { url = "https://files.pythonhosted.org/packages/bb/6a/1b6724a3955c2a32360d4d86608109bdbc41e656bd99cc271d5437f1c6ee/regex-2026.11.25-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:107c35771878cf1cbc8de852fad98c31f0a57b9d4d556253a6a9b1f46eb3e910", size = 302152, upload-time = "2026-11-26T01:32:05.674Z" }, + { url = "https://files.pythonhosted.org/packages/60/66/d6ebbd8046bbf1b71f897cd7aa8700d881f267ba0faec5ffadda0aa22a13/regex-2026.11.25-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:46621191673997662fa8a83fe992c607a026740271de73ca7e2b501793a1746d", size = 300047, upload-time = "2026-11-26T01:32:06.764Z" }, + { url = "https://files.pythonhosted.org/packages/60/c7/7db16e6b666415d06a493a961efcf2e17b88ec6b34b6cfe54ab0b103e3af/regex-2026.11.25-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ce6066a055664c8475b85ab46b74adeaffb6281c83ef6f50df079ac86ebe1bbd", size = 831183, upload-time = "2026-11-26T01:32:08.031Z" }, + { url = "https://files.pythonhosted.org/packages/dc/14/7750b84346e0dbae46d0cbe80a39d226ea7b313be47f9104ced3c4fa702d/regex-2026.11.25-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2362337c8e770f9953e4fcacd497ede2266034d05f39b1924df31b531b50dcae", size = 895067, upload-time = "2026-11-26T01:32:09.318Z" }, + { url = "https://files.pythonhosted.org/packages/9b/cf/e57ca1e7deb854c78e21f8982e3aef30bfecfab1f22c93a7cee868f654bc/regex-2026.11.25-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:477c12d6aeb1c9bc64cff1d12930d0ac602e29102874b33ba866f7c851e1753b", size = 934108, upload-time = "2026-11-26T01:32:10.835Z" }, + { url = "https://files.pythonhosted.org/packages/22/b4/66442d66711af81d6dd3bc67c9f837aa6856125fef9d775920b711195b0e/regex-2026.11.25-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:926dfacdb973c502b55da4c29623cd0cb2fd5227b4cd75291c3a0b22c0cc7183", size = 836651, upload-time = "2026-11-26T01:32:12.05Z" }, + { url = "https://files.pythonhosted.org/packages/a9/e3/a1738abfcd2b950b647322be48f82c7f1a0bc7f4cd9b87aa1c749ae48c73/regex-2026.11.25-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0106ef9a24711b55c16eaccbfc424d569171a33e49c87b76c6ed953491b5e10e", size = 805051, upload-time = "2026-11-26T01:32:13.196Z" }, + { url = "https://files.pythonhosted.org/packages/c6/ce/051aeba96fe1f4d2305dfa03799f4cd86d61641124a78a761d7714b5928c/regex-2026.11.25-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:3d5a2bc8e35ce4ef1bab2a5c883bb15ab94dcbc8c2a1f46746e85d5f94aaf586", size = 819448, upload-time = "2026-11-26T01:32:14.678Z" }, + { url = "https://files.pythonhosted.org/packages/40/66/386ae86cf326bf35e147bca85f6e3a7c28a339ec82fddab1f283c5b5e9d2/regex-2026.11.25-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:3fcadb67603da90bc3924e14eab9c13498fe438772b0ce43c425b261ab8bb779", size = 883541, upload-time = "2026-11-26T01:32:16.371Z" }, + { url = "https://files.pythonhosted.org/packages/50/d1/fac677940c93437f792affad140305f96c45cbfa1cd3f48f948ad1493616/regex-2026.11.25-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:2beed38818535e4f2c93e809819decf0768f2290ebb3ba71aa83e0aef8a08120", size = 796567, upload-time = "2026-11-26T01:32:17.761Z" }, + { url = "https://files.pythonhosted.org/packages/27/ba/457d67d03e11328efd3013bdbd43312e997102856f1121ea39ea6b1a4455/regex-2026.11.25-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:b6011ac3f986faa86c6c946e46c7c2f895e3db0ce2ee13d39eb611051468e774", size = 876446, upload-time = "2026-11-26T01:32:18.987Z" }, + { url = "https://files.pythonhosted.org/packages/1a/df/75e2931ae575516ca5d60bf79b4427b01531cd558c6d342c84f0b5a35965/regex-2026.11.25-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:25ff1f5932bf9b7f730d7645e5f1b805c5af1b035dd2463ff4d2790db144cdd1", size = 821924, upload-time = "2026-11-26T01:32:20.402Z" }, + { url = "https://files.pythonhosted.org/packages/e9/ba/1905e09be996db95e7fc06b1570f519a41bd68e77a1b677d0db36bdddf84/regex-2026.11.25-cp315-cp315t-win32.whl", hash = "sha256:a21de09d9b11d61ffa254d3b6a3d2386f2b3ebd9b1c67841fe31da758953bf31", size = 278969, upload-time = "2026-11-26T01:32:21.989Z" }, + { url = "https://files.pythonhosted.org/packages/d5/48/cd408af338a7c7f4bb568fa142ba2b2abe678c68099ce2a6ff09c92473a2/regex-2026.11.25-cp315-cp315t-win_amd64.whl", hash = "sha256:b8092f2ac3e23455826df939804bb2187d5f5d5e3e3e1256542f31971d442970", size = 288461, upload-time = "2026-11-26T01:32:23.502Z" }, + { url = "https://files.pythonhosted.org/packages/8e/5e/a1867fd9136d150f3b79c2dae681b42ad2fbad1db1121802328320dd7edf/regex-2026.11.25-cp315-cp315t-win_arm64.whl", hash = "sha256:2b7c11b0b87784e8788e57a327ca42a46b9c872e1149fb76139faab08d856eaf", size = 288930, upload-time = "2026-11-26T01:32:24.96Z" }, ] [[package]] @@ -2160,27 +2160,27 @@ wheels = [ [[package]] name = "ruff" -version = "0.17.5" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/86/cc/7b71512eb8b49926efb887cc66c74dd993642943c29eba51a877f6b85692/ruff-0.17.5.tar.gz", hash = "sha256:625e57d80cd43352d12ea81690f3eac46cddc8c0f35026d137fb0f157f94592e", size = 5368382, upload-time = "2026-11-12T17:54:55.04Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d4/f2/61df414cb4338617290a9023ad09486e207fb9a6d09357a7be34f2e369a4/ruff-0.17.5-py3-none-linux_armv6l.whl", hash = "sha256:d511dd302982e46a285528942fa6557d57730edc4bdb9def95e86a2603d77396", size = 10231309, upload-time = "2026-11-12T17:54:09.314Z" }, - { url = "https://files.pythonhosted.org/packages/d1/72/8ed970f3361f7c8d3f8e1b3b1af27cf086bc4b3a6b62ec20e21a1aaaaff5/ruff-0.17.5-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:b72fbc232e328bdbb9cdddf4f1aedcd61bd1aa64d75fc012114b4add0bd7f26b", size = 10250018, upload-time = "2026-11-12T17:54:11.983Z" }, - { url = "https://files.pythonhosted.org/packages/dc/4b/8b10f6c9d0a18413301ae8dd2af9d180a81bb738b1b731d944a37404c523/ruff-0.17.5-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6f0db748508f04a04e3fbebcc636a5c8b3bd76274f8ed28f497c44d75c2ea2d7", size = 9504737, upload-time = "2026-11-12T17:54:14.567Z" }, - { url = "https://files.pythonhosted.org/packages/b7/ea/1b3afa3943239dede7a0755ea139bdb51879f0f3f96f92894081d5c7d2e5/ruff-0.17.5-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6f6a7b138edf9cc402ca736a59d9525e6d766e5395760b72e7e146e6251ac963", size = 10168006, upload-time = "2026-11-12T17:54:17.195Z" }, - { url = "https://files.pythonhosted.org/packages/31/08/ee641daa45f83792f91274b65796cb011f1065f588911bfa3909ad9e31e7/ruff-0.17.5-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e52622ecf3a0df9d03e796fe3eed4aa085adda65520db7e0619cbd2192a97342", size = 10043751, upload-time = "2026-11-12T17:54:19.815Z" }, - { url = "https://files.pythonhosted.org/packages/f8/cf/1c59fdb42d0b5671ad5b160636fab4005ee28db72cb06aef6e3f3c04f377/ruff-0.17.5-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:54c0f67d1be11b55d12c184a819fc229f5eee3ef45c16c4fcad41258e83b4882", size = 10690562, upload-time = "2026-11-12T17:54:22.789Z" }, - { url = "https://files.pythonhosted.org/packages/49/c5/578074716173fb0c1591e9648a9f85c469888d9530cb35b89b757dc1208b/ruff-0.17.5-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:dd0dfe7c6fe5a447fce467c58e69893be1d9a7e4378f5b9906432da33d94a97f", size = 11338465, upload-time = "2026-11-12T17:54:25.523Z" }, - { url = "https://files.pythonhosted.org/packages/aa/b9/d6428bcf5ed88f4dc1d6e3417ee350236ed36e7a35f9477b727c00e437bf/ruff-0.17.5-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ec4ecf40fb4d6e1265b009dbe551727920926fc0f769070c452d6d84b422a74d", size = 10895501, upload-time = "2026-11-12T17:54:28.441Z" }, - { url = "https://files.pythonhosted.org/packages/f2/8a/1e29c0c3785ae7e5cd0d54ee8717a08867ef71545796340be4c653c57e24/ruff-0.17.5-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:40ca8afaac309b41a5b2e09e4e7beb1f824826b93c25697c4d74f573324fba4e", size = 10613231, upload-time = "2026-11-12T17:54:30.862Z" }, - { url = "https://files.pythonhosted.org/packages/32/b6/88944350c14bb90651014d678ad554e233ae2a79c14ad52101845f93d15b/ruff-0.17.5-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:8e85601bd6d9b6c3e3b95c0e0dccdbac1d23c6bcef006d187fbcddaf8225a5df", size = 10562789, upload-time = "2026-11-12T17:54:33.869Z" }, - { url = "https://files.pythonhosted.org/packages/6f/fd/2792e955b0bf54295cdcdddc4bb3f380c0790d7e60e789f528a9e6e48a31/ruff-0.17.5-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:f93d2b7d449ed9545304f6923699ca20d13c675b69f258481709a08ae61076db", size = 10069824, upload-time = "2026-11-12T17:54:36.663Z" }, - { url = "https://files.pythonhosted.org/packages/07/9c/d7cad341b4c19237948a6dd1fcea1c9c39c9d08b70f22f0e157d1236ebd6/ruff-0.17.5-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:0e5c125c5b31dc8efc948d41357496a4c4a312977565ccba740030efdff83580", size = 10038961, upload-time = "2026-11-12T17:54:39.452Z" }, - { url = "https://files.pythonhosted.org/packages/cc/a1/9cd0d4c371ddc70267d3bd557e718e2bdfb94c25e49d25605edfabb764bd/ruff-0.17.5-py3-none-musllinux_1_2_i686.whl", hash = "sha256:50dfc3c6b3ebd0a932f11dfd579bd42234b0b7137e68940eb6abdbfdb9d69697", size = 10385012, upload-time = "2026-11-12T17:54:41.808Z" }, - { url = "https://files.pythonhosted.org/packages/8f/a9/35f078ce98d4df318328ea5270382b5b65e680f7953b3db54f8e009c420c/ruff-0.17.5-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:86bd1f3b83c25f9b8055c6e796f0685b39d3127ce947322098c3108cf82fd586", size = 10793672, upload-time = "2026-11-12T17:54:44.342Z" }, - { url = "https://files.pythonhosted.org/packages/2c/a5/2e136dede2a88aaaf54498bbbdc81bc810f788ef6ef01efb97037d73cd1d/ruff-0.17.5-py3-none-win32.whl", hash = "sha256:e1546609b2ad73f1d6c5c076881b788672b7b3cc3283981182cbdbb6524ed88a", size = 9929908, upload-time = "2026-11-12T17:54:47.067Z" }, - { url = "https://files.pythonhosted.org/packages/ec/8c/e4db9ae1e0ee233c04df007ab6d0d42f799ae9abd95d352b6092ee7bc4bf/ruff-0.17.5-py3-none-win_amd64.whl", hash = "sha256:aa415d57c244299279901d776607fee3df7831c2a7435433fbfacde8632c6550", size = 10275454, upload-time = "2026-11-12T17:54:49.401Z" }, - { url = "https://files.pythonhosted.org/packages/e6/65/a1648bc1550e7683bf7bf1e2ce2485c9f8535cbca6cca9ec7b73cc12fb8e/ruff-0.17.5-py3-none-win_arm64.whl", hash = "sha256:64a6fd668a336df959c522991de33e9e3c8be463afc0c9ac8f029f9d19ef756e", size = 9849020, upload-time = "2026-11-12T17:54:52.055Z" }, +version = "0.17.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/df/8e/6929d337aa5380aafc7355f3149f3ccfe55cba5fdd34a045697ebaceb5a0/ruff-0.17.6.tar.gz", hash = "sha256:2b04276561331300325040bdca21460770029ec574d4c479099e39e8ad1ed43c", size = 5374388, upload-time = "2026-11-19T15:56:27.106Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/5d/38ef6310c22cacb094e9ae0ff7964062e04ffeecb45ee296894c2b1acc54/ruff-0.17.6-py3-none-linux_armv6l.whl", hash = "sha256:084d9c8f5ec718e7eba007dba339e7cb4f7571d2f267558ae080bf428fb6a69b", size = 10174693, upload-time = "2026-11-19T15:55:52.414Z" }, + { url = "https://files.pythonhosted.org/packages/a2/ed/fd35261049920a4888ef7c787a5c27089502077a4910f6ca8f1213157d6d/ruff-0.17.6-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:9d44ef2140402043fd6f689ef541858b80883a8b0a02e38539ef0614ebe57d0c", size = 10221650, upload-time = "2026-11-19T15:55:54.962Z" }, + { url = "https://files.pythonhosted.org/packages/ba/d4/c31391b36c729cd9fafa65b7a52a58850b99afb2b65da6be4263a53302f2/ruff-0.17.6-py3-none-macosx_11_0_arm64.whl", hash = "sha256:9fbddc08577592e283c265d865e0182de6e33db185494db7b06290d989d888e5", size = 9580986, upload-time = "2026-11-19T15:55:57.391Z" }, + { url = "https://files.pythonhosted.org/packages/eb/11/f3032684dcb3a676d7924545153d76fb56f76753e038f2ea650b99c71bdf/ruff-0.17.6-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:435241c61af5909a022f76219d3d1bf24730dc1bf0acabb5ddf4b569ab3cbb30", size = 10271368, upload-time = "2026-11-19T15:55:59.654Z" }, + { url = "https://files.pythonhosted.org/packages/08/30/c1e024eeb5bae99ae78c6b896ed108f64c9c845a03b56eaeff098e99b6e6/ruff-0.17.6-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d006bbb2945edb17b0ce6a0c1b5f5a8d81ba11dbac294a0a925effa22ce34feb", size = 9981564, upload-time = "2026-11-19T15:56:01.807Z" }, + { url = "https://files.pythonhosted.org/packages/7d/a5/da3e0c2d4bf02b3ca6c1d7fa4bb04d0081e340b1dd03c4f83b1bec3e15c1/ruff-0.17.6-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:fd661702202a89c00a4c9d0339008805fa5876bfa1c57e165495c2e62230dfbf", size = 10641991, upload-time = "2026-11-19T15:56:03.981Z" }, + { url = "https://files.pythonhosted.org/packages/4d/c1/6d7f981e86201c9db457cca99fd2c09b77574ebab37dff3e9239b218603c/ruff-0.17.6-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6a12c50a33936dc00db2be21ba25fb168a8b95c55eda2a3ac85005af69885e4b", size = 11403484, upload-time = "2026-11-19T15:56:05.778Z" }, + { url = "https://files.pythonhosted.org/packages/c3/92/8182f07b94998541d5f8f38f53da465aa28062afce24ecc398f45bfc62f1/ruff-0.17.6-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b5aba93b3db4b70c5697e4fee6e0d5b9c8452a9a3a03679611cadc25915a2173", size = 10892316, upload-time = "2026-11-19T15:56:08.016Z" }, + { url = "https://files.pythonhosted.org/packages/be/48/3df7d81249fd69ee6a49519b149fb5d11e13118fd7d0e8d65329a237087b/ruff-0.17.6-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aa3b08254a732acba246891089a152c47c5733dc36b8ecb76ce8602f8326e5e4", size = 10645279, upload-time = "2026-11-19T15:56:09.785Z" }, + { url = "https://files.pythonhosted.org/packages/71/80/4d232281544345d7beb98d1d32c24dae804ed360780a6f7753738b81225e/ruff-0.17.6-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:0692088e6b33455572fb18465e891b443f196e98dc1986825685c77ff6f4c5ac", size = 10534501, upload-time = "2026-11-19T15:56:11.718Z" }, + { url = "https://files.pythonhosted.org/packages/98/0a/b477f075a4a94eb541bf1c759a3e72b2a3d6390af7a13a5be0887229f67c/ruff-0.17.6-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:fb589e032806bb942e4fb526f30b80a1a64112147ed9f1d38cc3de2e255b6f45", size = 10136036, upload-time = "2026-11-19T15:56:13.779Z" }, + { url = "https://files.pythonhosted.org/packages/f1/d8/cf32fbfeb1fcda1470fb5c3bee50c69ee6bca257d487ec1eb17a0387edb4/ruff-0.17.6-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:1939b3d701c7b6981b7cf93473de5bf88b129b9ba84efaed5154cc517c44634d", size = 9969640, upload-time = "2026-11-19T15:56:15.738Z" }, + { url = "https://files.pythonhosted.org/packages/a7/22/bb9f9752f7fcdfdc8b9c51576cc142bb377ade745290e35085173963c7be/ruff-0.17.6-py3-none-musllinux_1_2_i686.whl", hash = "sha256:1a0bea6aa1216e0ec4cd35d3dbccec0d772a7c2aad28ec9c6e82571dff2c20b0", size = 10389427, upload-time = "2026-11-19T15:56:17.617Z" }, + { url = "https://files.pythonhosted.org/packages/81/c7/e09d220818ab146b736d62e0676dad215215d7de0884bbdad9fa075dc7d2/ruff-0.17.6-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:3db61f5015600543a581b07fa7f6f64afa0eeedefe16034cadd88c4074087582", size = 10760296, upload-time = "2026-11-19T15:56:19.463Z" }, + { url = "https://files.pythonhosted.org/packages/2e/09/28329441dfa2c463e2d377a69d4ebbe4d51665e9dbd49fb421f3bc80d775/ruff-0.17.6-py3-none-win32.whl", hash = "sha256:c2f4af6670b7a0501904e881bb3f1f24bd0d964dec1eedbd85f0eb73786e1128", size = 9966266, upload-time = "2026-11-19T15:56:21.581Z" }, + { url = "https://files.pythonhosted.org/packages/4b/9d/18ba9730addfc7554c70d6f171fb8dc2c08e774d9fb2b98e7946ef845c59/ruff-0.17.6-py3-none-win_amd64.whl", hash = "sha256:9cd2fd9923e9806b8b6b67a3469e2258e84bd4d21e45d5a1a690afdfb9c8e57d", size = 10365847, upload-time = "2026-11-19T15:56:23.582Z" }, + { url = "https://files.pythonhosted.org/packages/70/8a/59c33e2a64a4f9672f7f842a0dc522915cfbbaffd13d37d0cec57d1c5c5d/ruff-0.17.6-py3-none-win_arm64.whl", hash = "sha256:d8b14e1473dc86ab9069cf7a2ba5041dc012f59110201844ed04cfddf07055a0", size = 9926224, upload-time = "2026-11-19T15:56:25.269Z" }, ] [[package]] @@ -2409,11 +2409,11 @@ wheels = [ [[package]] name = "types-regex" -version = "2026.11.9.20261110" +version = "2026.11.25.20261127" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/63/4f/3b60e524ae059ad151160756f8029eaeef804f627fa23c23c62d063389df/types_regex-2026.11.9.20261110.tar.gz", hash = "sha256:b3f459f43eabbe541b4f550252233e5b6689fc1e2bccba528e8731536acace00", size = 14400, upload-time = "2026-11-10T08:54:13.597Z" } +sdist = { url = "https://files.pythonhosted.org/packages/94/93/7df09fdaa5b34e9bf5bd6ec8787f5dc8035b5d1183b7217ef5ace815bdd7/types_regex-2026.11.25.20261127.tar.gz", hash = "sha256:d3af64aaab09e0db9651c8e5a06693ee2b39ee3c92ba188f0bf1ea9fad1fb636", size = 14647, upload-time = "2026-11-27T10:13:39.154Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/58/47/23427ff7c9fdf6055b8b5eb951959c783f0cbddb8e2294be7e45b63a4dc9/types_regex-2026.11.9.20261110-py3-none-any.whl", hash = "sha256:b5effea974bdc751b9c544cb0ecae60b2337da0653bad9698cb63d45e1956d47", size = 11211, upload-time = "2026-11-10T08:54:12.516Z" }, + { url = "https://files.pythonhosted.org/packages/a8/51/2f25db022c8c1b3882655665e4bcc85b33638e1d9d44b72c61d87116869e/types_regex-2026.11.25.20261127-py3-none-any.whl", hash = "sha256:9cd942da2996e65225c963d9812734f7cb45f979577d11576452c8212d8e065f", size = 11235, upload-time = "2026-11-27T10:13:38.131Z" }, ] [[package]] From 1f555abc9561b4df25d8bc06950579536377751f Mon Sep 17 00:00:00 2001 From: Max Irgiznov <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:49:49 +0100 Subject: [PATCH 2/4] Release v0.16.1 (#363) Prepare the signed stable release from protected main at a2ca5b4 following promotion #361. Development publication 0.17.0.dev154 passed the TestPyPI build, publication, provenance and installation checks. The release carries the version and build epoch, public GitLab example pins, migration guidance, changelog, contributor credit for #354 and the prepublication plan archive. The next development line remains 0.17.0. Stable TestPyPI and PyPI publication, the annotated Git tag, GitHub Release and immutable receipt are verified by the release workflow after the protected squash merge. Tracked release issues: #351, #352, #353, #355, #356 and #358. The release workflow owns issue reconciliation after receipt readback. The focused release suite passed 139 tests. The operator and integration contract suite passed 76 tests. Local plan lifecycle, diff and secret checks passed. --- .release-metadata.json | 17 +- .release-source-date-epoch | 2 +- .release-version | 2 +- CHANGELOG.md | 34 ++++ PLANS.md | 157 +--------------- changelog.d/346.maintenance.md | 1 - changelog.d/350.security.md | 1 - changelog.d/351.bugfix.md | 1 - changelog.d/352.feature.md | 1 - changelog.d/353.feature.md | 1 - changelog.d/354.contributor.md | 1 - changelog.d/355.bugfix.md | 1 - changelog.d/355.maintenance.md | 1 - changelog.d/356.maintenance.md | 1 - changelog.d/356.security.md | 4 - changelog.d/358.bugfix.md | 1 - docs/codex/ENGINEERING_WORKFLOW_STATE.yaml | 2 +- docs/compatibility.md | 22 +-- docs/configuration.md | 9 +- docs/engineering/execution_history/README.md | 1 + ...ntributor-intake-and-incremental-review.md | 174 ++++++++++++++++++ .../execution_history/plans/README.md | 1 + docs/gitlab.md | 11 +- examples/gitlab/README.md | 4 +- examples/gitlab/ocr-review.gitlab-ci.yml | 6 +- 25 files changed, 250 insertions(+), 206 deletions(-) delete mode 100644 changelog.d/346.maintenance.md delete mode 100644 changelog.d/350.security.md delete mode 100644 changelog.d/351.bugfix.md delete mode 100644 changelog.d/352.feature.md delete mode 100644 changelog.d/353.feature.md delete mode 100644 changelog.d/354.contributor.md delete mode 100644 changelog.d/355.bugfix.md delete mode 100644 changelog.d/355.maintenance.md delete mode 100644 changelog.d/356.maintenance.md delete mode 100644 changelog.d/356.security.md delete mode 100644 changelog.d/358.bugfix.md create mode 100644 docs/engineering/execution_history/plans/2026-12-01-toolkit-0-16-1-contributor-intake-and-incremental-review.md diff --git a/.release-metadata.json b/.release-metadata.json index 0325b8be..94a305f3 100644 --- a/.release-metadata.json +++ b/.release-metadata.json @@ -1,15 +1,12 @@ { "schema_version": "ocr-toolkit.release-authorization/v1", - "version": "0.16.0", + "version": "0.16.1", "issues": [ - 335, - 336, - 337, - 338, - 339, - 340, - 341, - 342, - 343 + 351, + 352, + 353, + 355, + 356, + 358 ] } diff --git a/.release-source-date-epoch b/.release-source-date-epoch index 2cc47dce..a8da39b4 100644 --- a/.release-source-date-epoch +++ b/.release-source-date-epoch @@ -1 +1 @@ -1796068357 +1796159248 diff --git a/.release-version b/.release-version index 04a373ef..2a0970ca 100644 --- a/.release-version +++ b/.release-version @@ -1 +1 @@ -0.16.0 +0.16.1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 27d6649a..1805a286 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,37 @@ +## 0.16.1 - 2026-12-01 + +### 🚀 Features + +- `ocr-ci review --local --incremental` now shows how many groups qualified for reuse and counts why other groups need fresh review in the terminal and local report. ([#352](https://github.com/xeonvs/open-code-review-toolkit/issues/352)) +- After independent Markdown or JSON edits, `ocr-ci review --local --incremental` can reuse unchanged groups. It verifies source reads and repeats supported searches, diff reads and built-in evidence queries before reusing a group. ([#353](https://github.com/xeonvs/open-code-review-toolkit/issues/353)) + +### 🐛 Bug Fixes + +- Accept `GIT_EDITOR` and `GIT_SEQUENCE_EDITOR` in incremental local review qualification, and name any rejected Git setting in the fallback message. ([#351](https://github.com/xeonvs/open-code-review-toolkit/issues/351)) +- Keep mixed GitLab and local reviews running when OCR reports tracked paths excluded by `.gitignore` alongside a changed submodule pointer. Only eligible files count as completed review work, and the repository summary still reports partial coverage. ([#355](https://github.com/xeonvs/open-code-review-toolkit/issues/355)) +- Publication DLP keeps findings that quote supported ISO date ranges, dated local Markdown anchors and power-of-two size assignments. Phone numbers and sensitive material elsewhere in the finding still prevent publication. ([#358](https://github.com/xeonvs/open-code-review-toolkit/issues/358)) + +### 🛠 Maintenance + +- Update the locked Hypothesis, Ruff, regex stubs, certifi, regex, httpx2, and httpcore2 versions from the reviewed Dependabot updates in PRs #346–349. ([#346](https://github.com/xeonvs/open-code-review-toolkit/issues/346)) +- Recommend checksum-verified Open Code Review 1.14.6 for local and GitLab reviews. ([#355](https://github.com/xeonvs/open-code-review-toolkit/issues/355)) +- Separate draft and ready pull-request checks and prepare protected `dev` intake, with reduced fork CI storage and release notification bound to the verified publication attempt. ([#356](https://github.com/xeonvs/open-code-review-toolkit/issues/356)) + +### Security + +- Update the pinned GitHub Actions, including Scorecard's upstream security fixes. Require SHA-256 verification of the uv release archive in CI and use uv 0.13.10 for CI and the local dependency audit. [GHSA-vjvj-3m3f-fgmm](https://github.com/astral-sh/uv/security/advisories/GHSA-vjvj-3m3f-fgmm) ([#350](https://github.com/xeonvs/open-code-review-toolkit/issues/350)) +- Pin the GitLab example’s official Python 3.12 slim image to a reviewed Docker Hub manifest digest. The example requires a `linux/amd64` runner for its OCR binary. + + - Require fresh, verified coverage before GitLab auto-approval and preserve earlier findings during incomplete reviews. Check external tool data before model delivery and review text before publication. + - **Migration for federated installations** — For each tool in `OCR_MCP_SERVERS_JSON`, review and supply an operator-authored `description` and closed `input_schema`, then change the registry’s `version` from 2 to 3. Identity-only installations need no external registry. + + ([#356](https://github.com/xeonvs/open-code-review-toolkit/issues/356)) + +### Contributors + +- Thanks to @ahmedpdf445-stack for [fixing incremental local review when Git editor settings are present](https://github.com/xeonvs/open-code-review-toolkit/pull/354). ([#354](https://github.com/xeonvs/open-code-review-toolkit/issues/354)) + + ## 0.16.0 - 2026-11-30 ### 🚀 Features diff --git a/PLANS.md b/PLANS.md index fb6894ac..ecc5b3e7 100644 --- a/PLANS.md +++ b/PLANS.md @@ -1,162 +1,8 @@ # Execution Plans -## Active Plan: Toolkit 0.16.1 — contributor intake and incremental review - -plan_schema_version: 2 -Status: active -Release classification: release-required -Target release: 0.16.1 -Next development marker: 0.17.0 -Last Updated: 2026-12-01 - -### Goal - -Deliver the full selected patch release through protected external intake on `dev`, maintainer promotion to `main`, and the existing signed release and receipt process. - -### Plan Origin - -direct_execution - -### Requested Scope - -Review the new contributor's entire repository history, fix incremental qualification and extend safe reuse, integrate the pending dependency and OCR updates, harden contributor CI, update contribution rules for agent-assisted submissions and credit accepted work in the release. - -### Requirement Traceability - -| Requirement | Outcome | Queue | Status | -| --- | --- | --- | --- | -| REQ-001 | Inspect external submissions and observed GitHub disclosure surfaces | WQ-01 | done | -| REQ-002 | Protect dev intake and isolate privileged publication | WQ-02 | in_progress | -| REQ-003 | Qualify #351/#354 and implement #352–353 | WQ-03 | done | -| REQ-004 | Review #346–350 and qualify #355 | WQ-04 | done | -| REQ-005 | Document contribution rules and conditional release credit | WQ-02, WQ-05 | done | -| REQ-006 | Deliver and reconcile 0.16.1 | WQ-06, WQ-08 | pending | -| REQ-007 | Retain proven technical literals during publication and increase default test coverage (#358) | WQ-07 | complete | - -### Explicit Non-Goals - -Prepare protected dev intake and retarget both existing PRs before merge or publication. Keep the contributor’s #354 changes and attribution in the original PR. - -### Constraints - -Inspect fork revisions as data locally. Keep private evidence, credentials, operator inputs and unredacted logs outside public artifacts. Preserve contributor attribution and the stable release authorizer. Review real effective permissions after changes. Keep security reports on the private reporting route. - -### Inputs And Sources - -Use the live [contributor PR](https://github.com/xeonvs/open-code-review-toolkit/pull/354), [CI failure](https://github.com/xeonvs/open-code-review-toolkit/actions/runs/46632932603/job/142597665154), [qualification issue](https://github.com/xeonvs/open-code-review-toolkit/issues/355), all eleven workflows, GitHub Actions settings, rulesets, environments and the repository's development, local review, compatibility and release guides. - -For AI-assisted intake, the September policy study documents substantial variation in disclosure requirements. The October Linux Foundation survey identifies disclosure and contributor responsibility as common practices. GitHub's July workflow holds illustrate why maintainers inspect proposed execution before approval. Adopt a short disclosure and actual verification evidence, with the same security review for all authors. [Policy study](https://arxiv.org/abs/2609.07542), [Linux Foundation research](https://www.linuxfoundation.org/hubfs/Research%20Reports/Navigating-Open-Source-Software-Development-in-the-Generative-AI-Era.pdf), [GitHub July update](https://github.blog/changelog/2026-07-28-github-actions-holds-potentially-malicious-workflows-for-approval/). - -### User Decisions And Answers - -Prepare the full maintainer-owned implementation on `maintainer/0.16.1-intake`, review successive changes incrementally and open a draft. Use an existing issue when available; the issue owns the synthetic case and the PR links it and reports actual validation. Keep suspected vulnerabilities on the private reporting route. - -The owner selected protected `dev → main`, the full release composition, revised contributor rules and a conditional acknowledgment section. Include all currently open maintenance PRs, independently of the human contributor's work. - -REQ-002/004 include the external contribution supply-chain threat model, Docker Hub consumption, mandatory pre-push freshness review and maintainer/Dependabot ownership. At merge the maintainer checks the author and source branch in GitHub and reviews every dependency-related change, including additions, renames/deletions, lock sources, action references and installers. Exercise an ordinary fork PR, a fork changing a pin, a spoofed bot label/name, genuine Dependabot and maintainer updates. WQ-04 includes qualifying and pinning the official Python manifest used by the GitLab example and verifying the supported Linux image and installed toolkit in that environment. Keep monthly refresh ownership explicit; the configured uv and github-actions ecosystems do not update a GitLab YAML image digest. - -The contributor guide and PR template now request material AI disclosure, human verification, existing-PR checks and source attribution. Keep intake open. If overlapping submissions become a problem here, GitHub supports a per-user limit on simultaneous external PRs without granting write access to bypass it. [GitHub June update](https://github.blog/changelog/2026-06-17-limit-open-pull-requests-for-users-without-write-access/). - -### Completed Baseline State - -Current protected main is c5750fd, the v0.16.0 release merge. GitHub reports that release immutable. Remote dev and the new milestone did not exist at inspection. The contributor authored one repository PR (#354) and zero issues across all states. #351–353 belong to the maintainer, #355 to Actions and #346–350 to Dependabot. - -At b93ec7d the three changed files cover local opt-in qualification, its tests and the bugfix fragment. The change accepts two editor settings, still falls back for other unsupported settings and prints their names to stderr. Values are omitted, but arbitrary inherited names can contain private text or control characters and the output has no count or byte bound. Use a closed vocabulary of useful known names plus a generic bounded fallback. Verify the two editor commands never run during qualification or review; prefer removing the unnecessary editor values from the incremental child environment. The follow-up 4b395cbe changes only the unused test binding. - -### Current Work Queue - -| Item | Work and exit evidence | Requirements | Status | -| --- | --- | --- | --- | -| WQ-01 | Inventory submissions, review immutable diff, logs, token permissions, artifacts, CI triggers and settings. Record limits below. | REQ-001 | done | -| WQ-02 | Target the maintainer bootstrap and external PR at protected dev; promote reviewed dev to main. Restrict both publishing environments to branch main only and verify the external Trusted Publishers. Scope site dispatch credentials to the trusted main workflow/environment. Configure approval for all outside collaborators. Set up native GitHub protections and required Build/CodeQL checks on dev. At merge the maintainer verifies external PRs target dev and main receives repository-owned promotions and release PRs. Account explicitly for maintenance bots and bootstrap. Verify the intended review and retargeting paths before retargeting #354. Synchronize contribution guide and template with rollout. | REQ-002, REQ-005 | in_progress | -| WQ-03 | Retarget and review #354 at the new merge base, retain author credit, replace premature issue closing keywords, address diagnostic bounds. #352 uses closed per-group reason counts with overlapping reasons and no paths/arguments. #353 extends file-level reuse to unchanged non-Python blobs and replays bounded deterministic searches on immutable inputs; qualify only complete equivalent observations including dependencies, result order, truncation and failures. Recheck uncertain groups. | REQ-003 | done | -| WQ-04 | Integrate development tooling #346, certifi #347, regex #348, httpx2 #349 and six action updates #350. Check upstream commit identities, permissions, cache defaults and artifact changes before updating action pins. Reconcile overlapping lock changes and test the combined tree. For #355 inspect upstream gitignore/preview semantics, verify exact assets, Linux and applicable native handoffs and consumer behavior before promotion to OCR 1.14.6. | REQ-004 | done | -| WQ-05 | Add conditional Towncrier Contributors category, maintainer-reviewed public handle and accepted PR link once per contributor. Verify populated and empty releases, canonical changelog section and final comparison link. | REQ-005 | done | -| WQ-06 | After WQ-08 passes on the final development head and the maintainer authorizes release, merge the protected promotion, verify TestPyPI on the resulting push to main, then prepare the signed release/v0.16.1 PR and reconcile published artifacts. | REQ-006 | pending | -| WQ-07 | Qualify publication-only DLP handling for date ranges, dated headings and size assignments, retain phone and credential rejection, and integrate #359 through the twelve protected checks. | REQ-007 | complete | -| WQ-08 | Complete private corrective review, verify native OCR and installed-wheel behavior, run the full quality and secret gates on the final development range, and record review findings and their disposition in the private corrective PR before requesting release authorization. | REQ-006 | in_progress | - -### Locked Decisions - -Keep #354 open against its original fork head. The maintainer posted [two requested adjustments](https://github.com/xeonvs/open-code-review-toolkit/pull/354#issuecomment-7310075633). When protected dev is ready, change the existing PR base, inspect the new merge diff, require fresh checks and review, and squash into dev with attribution. Open a separate repository-owned dev-to-main promotion PR. Use non-closing issue references in its body and squash message. - -Exercise the base-change event in CI. Default pull_request activity types omit edited. Require observed runs bound to the new dev base and head; a rerun of an old main-target event cannot establish this. [GitHub base change behavior](https://docs.github.com/en/pull-requests/how-tos/create-pull-requests/changing-the-base-branch-of-a-pull-request). - -Protect the long-lived dev ref from automatic deletion. Repository merge commits are enabled. Main retains signed linear history, strict checks and squash/rebase restrictions. Create a maintainer sync branch at the current dev tip, merge main into it with a signed commit, and merge its reviewed PR into dev with a merge commit so the latest main becomes its ancestor after a squash promotion and release-marker changes. Test two consecutive promotion cycles and verify that the second contains only its intended tree changes. Keep this configuration decision in the bootstrap review. - -Fork validation uses GitHub-hosted pull_request jobs with SHA-pinned actions, read-only effective tokens, no environment, no publisher secrets or OIDC. Allow classification, tests, lint/types, SAST, dependency review/audit, CodeQL PR analysis and distribution build/install smoke after head review. Read the Gitleaks policy and version selector from the protected base. Keep package build local to the job for external PRs; disable unnecessary fork artifact uploads, including scanner reports, or validate and redact any retained public output. Rebuild reviewed source for publication. Reserve Release, TestPyPI, site dispatch, Scorecard publication, maintenance and qualification writes for trusted triggers. No privileged execution of fork code through pull_request_target or workflow_run. - -### Verification - -Verify a bare dev push starts no publisher. With a dev-to-main promotion open, push a fresh reviewed commit to dev and inspect the resulting PR synchronization jobs for effective permissions and exclusion of publishing OIDC and site credentials. Use a fork PR to verify dev CI and actual runner permission banners, maintainer retargeting of external main-targeted PRs, eligible dev promotion, changed-head reapproval, and dev exclusion from both registry environments. Check release authorization on its existing protected path. Verify the actual current PR target, source repository and revision in GitHub before merge. Verify admin bypass is limited and auditable. Allow the sole maintainer to promote via a reviewed PR without creating an impossible self-approval requirement. Require maintainer review of external changes, especially workflows, runnable build/test scripts, dependencies and CODEOWNERS. - -For #351–353 exercise installed incremental review across successive heads, an editor setting, a disallowed key, bounded diagnostics, changed and unchanged search results, deleted and newly matching files, failed/incomplete calls, changed policy and the issue's 23-file/two-change case. Compare findings with fresh full review. Run focused tests, quality, Gitleaks, dependency audit, aggregate security and own-tool review, installed package smoke and the release contracts named in docs/release.md. Versioned dependency CI and hosted ruleset checks must cover the exact promotion tree. - -### Latest Validation Results - -The maintainer intake work is tracked in [#356](https://github.com/xeonvs/open-code-review-toolkit/issues/356). The external contribution stays in #354. The contribution guide and forms now put reusable synthetic evidence on the issue; the PR records implementation, verification and attribution. Maintainers own the shared release plan and credit accepted work through Towncrier. - -The maintainer branch integrates #346–350, qualifies OCR 1.14.6 with official assets and exercises the installed wheel on Linux amd64 using the pinned GitLab Python image. Empty and populated Towncrier previews verified conditional contributor credit. Publication and the hosted intake transition remain pending. A real self-review of c5750fd..d37c88d completed all 21 selected files and identified documentation corrections. Two incremental attempts on the first commit failed before a model response when using the staged executable. With governed MCP enabled, official OCR 1.14.6 exercised a complete fresh review and recorded the reason, with one completed gateway call and no reused files. - -The managed worktree scan rejected the resolvable maintainer checkout before allocating a scan ID or SARIF. Independent reviewers inspected contributor intake, publisher recovery, site notification, secrets, cache and artifact permissions, and traced incremental playback against OCR 1.14.6. The owner accepted this limitation for the draft only. Review findings on partial observations, native input ordering, narrowed groups, private argument storage and dependency selection are tracked through implementation and regression checks. - -The owner selected native GitHub branch rules and a maintainer decision at merge. Retarget external work after both branches have the intended protections and the publication secrets have been isolated. - -The contributor replied and updated #354 to 26080da. Static review on that revision confirmed both editor keys are removed from the incremental child environment and the diagnostic uses a bounded fixed vocabulary. Keep the existing PR open for protected dev intake and review the retargeted candidate. - -All eleven main-required checks passed on 26080da. The maintainer [acknowledged both corrections](https://github.com/xeonvs/open-code-review-toolkit/pull/354#issuecomment-7311647605) and retained the PR for protected dev intake. - -After updating the installed Darwin OCR to 1.14.6 and granting outbound access, two actual ChatGPT incremental reviews completed in a disposable repository. The first saved one qualified file. After editing that file the second correctly performed fresh review and saved its new baseline. The local development firewall binds its allowance to an executable path and subsequently blocked another session copy. Maintainer self-review on this host uses the installed OCR path. A controlled provider exercised reuse of 21 of 23 files in a separate official-binary test. - -The approved 4b395cbe rerun completed with all 17 checks successful, including quality and both platform matrices. All five revised workflow log archives, the revised unpacked wheel/sdist and the SARIF artifact passed the redacted signature scan. Revised job banners again showed only read permissions. The SARIF contained zero results. These observations supersede the initial approval state below. The maintainer's comment is public; branch protections, remote settings and the PR base are still at their original values. - -At b93ec7d all five workflows ran on pull_request, attempt 2. Attempt 1 lists zero jobs. Six test jobs, build, scanners and dependency review passed. Quality stopped on Ruff RUF059 before mypy. At 4b395cbe Ruff passes on the exact revised test file; all five new workflows initially returned action_required. Local diff whitespace validation passed. A manual static review covered the changed files and supporting environment handoff. The managed diff scan rejected the resolvable worktree before creating a scan ID. Repeat it on the assembled release range before merge. - -All five observed job-log archives showed read-only token permissions, including SecurityEvents read for CodeQL. Redacted Gitleaks scans found no matches in the downloaded logs, SARIF and unpacked wheel/sdist streams. SARIF contained zero results. These observations cover recorded output and known detectors. Runner network traffic and private cache contents were not observed. - -Live metadata showed a public repository, no registered repository runners, default read token, Actions PR approvals disabled, mandatory SHA pinning, verified creators broadly allowed and approval only for first-time contributors. No repository Actions variables or environment secrets/variables were listed. A repository-level site dispatch secret exists. Main caches include setup-uv and Gitleaks; assume fork jobs can read base caches. No #354 merge cache was listed. Inspect cache producers and inputs, disable fork restore/save where unnecessary, and keep private packages, home directories and credentials out of every base cache. Review implicit setup-uv defaults in quality, build and security jobs. [GitHub cache scopes](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching). - -The active main ruleset requires PRs, signatures, strict checks and thread resolution, but zero approving reviews, no mandatory CODEOWNERS and a PR-only admin bypass. Its check list omits the Ubuntu 3.13 matrix job documented as blocking. Align it with intended gates. Only the owner appeared in the collaborator inventory. Both publication environments currently allow all protected branches. The notifier reads trusted metadata and a public receipt without checking out triggering source; strengthen the match between receipt run/attempt and publication, with the documented recovery path covered. Open secret-scanning and Dependabot alerts were zero. Four open Scorecard alerts concern CI tests, SAST, code review and branch protection; reconcile against live configuration after rollout. - -### Risks And Recovery - -Protect dev before admitting any external code. A PR from dev in the same repository has a different trust context from a fork and may reference repository secrets. Restrict sensitive credentials first. Retain the protected-main path for bootstrap and recovery. If dev filters, scope isolation or branch protections fail, keep intake pending, correct trusted policy, and repeat affected checks. Never copy a fork build artifact into a privileged publishing job. Re-read PR heads and settings on resume. - -### Resume Point - -Review the corrective range from its protected development base to the fix head. Before promotion, validate the entire release diff from protected main to the final dev head and record both SHAs. WQ-08 gates release promotion. Keep the validation record with the private corrective PR until coordinated disclosure. - -The maintainer bootstrap merged into protected `dev` in #357. All three environments select only `main`. The site dispatch credential is environment-scoped and the repository Actions secret list is empty. The fork workflow approval policy covers all external contributors. All twelve required checks passed on #354 at `75bedaf` against `ef5f376`. GitHub attributed its verified squash commit `feafbf7` to @ahmedpdf445-stack. - -#359 merged the #358 fix and its regression tests into protected `dev` at -`f65053e`. This is the base of the private corrective PR. Keep the milestone -and release issues open through release verification. Obtain explicit release -authorization after the corrective work lands on `dev`. - -### Plan Fidelity Check - -REQ-001–007 cover the selected inputs, full release scope, public contributor guidance, CI isolation, verification and attribution. Queue items identify owners and acceptance evidence at each boundary. - -### Reconciliation Check - -The hosted settings above describe the observed pre-rollout state. The current intake target is protected `dev`. No release authorization or external delivery has occurred. - -### Closure Gate - -Archive in the protected release PR after promotion, development publication, current required checks, signed release markers, release notes, authorized issues and indexes are reconciled. Preserve pending external facts. - -### Post-Close Delivery - -Verify stable registry artifacts, supported Python installs, provenance, annotated tag, immutable release and receipt readback. Confirm tracked issue and milestone closure only after the release workflow records the receipt. - -### Handoff Notes - -Use bare issue references in promotion and release text. Preserve contributors' public attribution across squash or maintainer revisions. Raw logs and profile investigation are unnecessary in release notes. - -If #354 ships, the proposed Contributors entry is “Thanks to @ahmedpdf445-stack for fixing incremental local review when Git editor settings are present ([#354](https://github.com/xeonvs/open-code-review-toolkit/pull/354)).” Verify the handle, contribution and final merged change when preparing the release. - ## Recently Completed +- [x] 2026-12-01: Completed Toolkit 0.16.1 — contributor intake and incremental review; [full archived plan](docs/engineering/execution_history/plans/2026-12-01-toolkit-0-16-1-contributor-intake-and-incremental-review.md). - [x] 2026-11-30: Completed Toolkit 0.16.0 — GitLab telemetry and local review recovery; [full archived plan](docs/engineering/execution_history/plans/2026-11-30-toolkit-0-16-0-gitlab-telemetry-and-local-review-recovery.md). - [x] 2026-11-28: Completed Toolkit 0.15.2 — CI outcome DLP, OCR qualification, Analysis and local telemetry; [full archived plan](docs/engineering/execution_history/plans/2026-11-28-toolkit-0-15-2-ci-outcome-dlp-ocr-qualification-analysis-and-local-telemetry.md). - [x] 2026-11-16: Completed Toolkit 0.15.1 — evidence diagnostics and rejection cleanup; [full archived plan](docs/engineering/execution_history/plans/2026-11-16-toolkit-0-15-1-evidence-diagnostics-and-rejection-cleanup.md). @@ -166,4 +12,3 @@ If #354 ships, the proposed Contributors entry is “Thanks to @ahmedpdf445-stac - [x] 2026-11-06: Completed Internal engineering cycle corrections; [full archived plan](docs/engineering/execution_history/plans/2026-11-06-internal-engineering-cycle-corrections.md). - [x] 2026-11-06: Completed Toolkit 0.14.6 — OCR 1.13.6, DLP precision and efficient delivery; [full archived plan](docs/engineering/execution_history/plans/2026-11-06-toolkit-0-14-6-ocr-1-13-6-dlp-precision-and-efficient-delivery.md). - [x] 2026-11-04: Completed Toolkit 0.14.5 — DLP precision, OCR qualification and maintenance quality; [full archived plan](docs/engineering/execution_history/plans/2026-11-04-toolkit-0-14-5-dlp-precision-ocr-qualification-and-maintenance-quality.md). -- [x] 2026-10-31: Completed Toolkit 0.14.4 systematic DLP corrections and diagram source validation; [full archived plan](docs/engineering/execution_history/plans/2026-10-31-toolkit-0-14-4-systematic-dlp-corrections-and-diagram-source-validation.md). diff --git a/changelog.d/346.maintenance.md b/changelog.d/346.maintenance.md deleted file mode 100644 index 6e108a9e..00000000 --- a/changelog.d/346.maintenance.md +++ /dev/null @@ -1 +0,0 @@ -Update the locked Hypothesis, Ruff, regex stubs, certifi, regex, httpx2, and httpcore2 versions from the reviewed Dependabot updates in PRs #346–349. diff --git a/changelog.d/350.security.md b/changelog.d/350.security.md deleted file mode 100644 index 7fe3d8b3..00000000 --- a/changelog.d/350.security.md +++ /dev/null @@ -1 +0,0 @@ -Update the pinned GitHub Actions, including Scorecard's upstream security fixes. Require SHA-256 verification of the uv release archive in CI and use uv 0.13.10 for CI and the local dependency audit. [GHSA-vjvj-3m3f-fgmm](https://github.com/astral-sh/uv/security/advisories/GHSA-vjvj-3m3f-fgmm) diff --git a/changelog.d/351.bugfix.md b/changelog.d/351.bugfix.md deleted file mode 100644 index 00a2c814..00000000 --- a/changelog.d/351.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -Accept `GIT_EDITOR` and `GIT_SEQUENCE_EDITOR` in incremental local review qualification, and name any rejected Git setting in the fallback message. diff --git a/changelog.d/352.feature.md b/changelog.d/352.feature.md deleted file mode 100644 index a217a06e..00000000 --- a/changelog.d/352.feature.md +++ /dev/null @@ -1 +0,0 @@ -`ocr-ci review --local --incremental` now shows how many groups qualified for reuse and counts why other groups need fresh review in the terminal and local report. diff --git a/changelog.d/353.feature.md b/changelog.d/353.feature.md deleted file mode 100644 index 9f5e02e3..00000000 --- a/changelog.d/353.feature.md +++ /dev/null @@ -1 +0,0 @@ -After independent Markdown or JSON edits, `ocr-ci review --local --incremental` can reuse unchanged groups. It verifies source reads and repeats supported searches, diff reads and built-in evidence queries before reusing a group. diff --git a/changelog.d/354.contributor.md b/changelog.d/354.contributor.md deleted file mode 100644 index 097e8e05..00000000 --- a/changelog.d/354.contributor.md +++ /dev/null @@ -1 +0,0 @@ -Thanks to @ahmedpdf445-stack for fixing incremental local review when Git editor settings are present. diff --git a/changelog.d/355.bugfix.md b/changelog.d/355.bugfix.md deleted file mode 100644 index 92981136..00000000 --- a/changelog.d/355.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -Keep mixed GitLab and local reviews running when OCR reports tracked paths excluded by `.gitignore` alongside a changed submodule pointer. Only eligible files count as completed review work, and the repository summary still reports partial coverage. diff --git a/changelog.d/355.maintenance.md b/changelog.d/355.maintenance.md deleted file mode 100644 index e9718b20..00000000 --- a/changelog.d/355.maintenance.md +++ /dev/null @@ -1 +0,0 @@ -Recommend checksum-verified Open Code Review 1.14.6 for local and GitLab reviews. diff --git a/changelog.d/356.maintenance.md b/changelog.d/356.maintenance.md deleted file mode 100644 index c6a4b07d..00000000 --- a/changelog.d/356.maintenance.md +++ /dev/null @@ -1 +0,0 @@ -Separate draft and ready pull-request checks and prepare protected `dev` intake, with reduced fork CI storage and release notification bound to the verified publication attempt. diff --git a/changelog.d/356.security.md b/changelog.d/356.security.md deleted file mode 100644 index 5ba49e4a..00000000 --- a/changelog.d/356.security.md +++ /dev/null @@ -1,4 +0,0 @@ -Pin the GitLab example’s official Python 3.12 slim image to a reviewed Docker Hub manifest digest. The example requires a `linux/amd64` runner for its OCR binary. - -- Require fresh, verified coverage before GitLab auto-approval and preserve earlier findings during incomplete reviews. Check external tool data before model delivery and review text before publication. -- **Migration for federated installations** — For each tool in `OCR_MCP_SERVERS_JSON`, review and supply an operator-authored `description` and closed `input_schema`, then change the registry’s `version` from 2 to 3. Identity-only installations need no external registry. diff --git a/changelog.d/358.bugfix.md b/changelog.d/358.bugfix.md deleted file mode 100644 index 978cceb9..00000000 --- a/changelog.d/358.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -Publication DLP keeps findings that quote supported ISO date ranges, dated local Markdown anchors and power-of-two size assignments. Phone numbers and sensitive material elsewhere in the finding still prevent publication. diff --git a/docs/codex/ENGINEERING_WORKFLOW_STATE.yaml b/docs/codex/ENGINEERING_WORKFLOW_STATE.yaml index 5c7c4908..31192278 100644 --- a/docs/codex/ENGINEERING_WORKFLOW_STATE.yaml +++ b/docs/codex/ENGINEERING_WORKFLOW_STATE.yaml @@ -32,7 +32,7 @@ plan_archive_indexes: - docs/engineering/execution_history/README.md - docs/engineering/README.md - docs/README.md -active_plan: PLANS.md +active_plan: null runtime_agent_config_managed: true instruction_contract_version: 3 planning_contract_version: 2 diff --git a/docs/compatibility.md b/docs/compatibility.md index 7770c02b..fce359fb 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -8,17 +8,17 @@ requires its own qualification before installation. ## Upgrading the toolkit and OCR -Upgrade the wheel in the toolkit virtual environment and check its installed version. +Upgrade the wheel in the toolkit virtual environment and check its installed +version. Use the support manifest from that toolkit release to select the +matching OCR binary. ```sh python -m pip install --upgrade --only-binary=:all: open-code-review-toolkit ocr-ci --version ``` -Toolkit 0.16.0 uses OCR 1.14.5. The 1.14.6 instructions below apply to builds containing the 0.16.1 qualification. Match the manifest from the installed toolkit release before changing the binary. - -On Linux amd64, verify the -download in a private directory before installing the executable: +On Linux amd64, verify the download in a private directory before installing +the executable. ```sh ( @@ -32,13 +32,11 @@ download in a private directory before installing the executable: ) ``` -Put `$HOME/.local/bin` on `PATH`. For another platform -use the matching asset and SHA-256 in the same release entry. After installing -the wheel, check `ocr --version` and run `ocr-ci preflight --local` in the -configured local environment or `ocr-ci preflight` in GitLab CI. Preflight -rejects the former 1.13.x binary. The GitLab example verifies both downloads; -use the example from the tag matching the installed toolkit. -[OCR 1.14.6 release assets](https://github.com/alibaba/open-code-review/releases/tag/v1.14.6) +Put `$HOME/.local/bin` on `PATH`. For another platform use the matching asset and +SHA-256 in the same release entry. Check `ocr --version` and run +`ocr-ci preflight --local` in the configured local environment or +`ocr-ci preflight` in GitLab CI. Use the GitLab example from the same toolkit +release tag to verify the downloads in CI. [OCR 1.14.6 release assets](https://github.com/alibaba/open-code-review/releases/tag/v1.14.6) ## Changes in OCR 1.13.11 through 1.14.6 diff --git a/docs/configuration.md b/docs/configuration.md index 22499e4e..95d5b788 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -34,7 +34,7 @@ These are the complete supported toolkit-owned runtime inputs. `Required` is sco | `OCR_LLM_REASONING_EFFORT` | Operator / configure and preflight | No | Unset (no overlay) | Case-insensitive `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max`; explicit `none` is sent, not omitted. Nonempty values require an OpenAI protocol. | | `OCR_ANTHROPIC_DISABLE_THINKING` | Operator / `ocr-ci configure` | No | `false` | With the Anthropic protocol, exact `true` adds `thinking.type=disabled`. | | `OCR_REVIEW_LANGUAGE` | Operator / shared language resolver | No | `English` | Allowed language label or BCP-47 tag used for the review. | -| `OCR_ANALYSIS` | Operator / review runner | No | `false` | Requires the new wheel and qualified OCR binary in the [paired upgrade instructions](compatibility.md#upgrading-the-toolkit-and-ocr). The preceding release’s GitLab pipeline ignores this setting. Enable a separate Behavior/Impact investigation on the reviewed range in GitLab or local review. It is private by default. GitLab publication requires the explicit `ocr-ci post --include-analysis` flag. | +| `OCR_ANALYSIS` | Operator / review runner | No | `false` | Enable a separate Behavior/Impact investigation on the reviewed range in GitLab or local review. It is private by default. GitLab publication requires the explicit `ocr-ci post --include-analysis` flag. | | `OCR_ANALYSIS_MAX_TOKENS_BUDGET` | Operator / review runner | No | `0` | Soft token budget for the additional investigation. Supply a non-negative decimal integer up to 9223372036854775807. Zero is unlimited. An explicitly blank value fails validation, including when Analysis is off. The main review has its own budget. | | `OCR_REVIEW_EFFORT` | Operator / `ocr-ci configure` | No | `medium` | Closed OCR quality preset: `low`, `medium`, or `high`; maps to one, two, or three review rounds. | | `OCR_REVIEW_DIAGRAM_MODE` | Operator / review and posting | No | `on` | Unset selects the default. Exact `on`, `off`, `spoiler`, or `local`; blank/unknown fails before acquisition. GitLab requests expanded/collapsed output with `on`/`spoiler`; standalone requests only `local`. See [optional diagrams](diagrams.md). | @@ -245,7 +245,12 @@ guides OCR to read available intent before considering useful allowlisted tools. References in MR text remain untrusted data; they do not authorize tools or cause automatic acquisition. Configured tools may remain unused. -`OCR_MCP_SERVERS_JSON` accepts only the closed version-3 registry. Server and tool names use ASCII letters, digits, underscore or hyphen, begin with a letter, and cannot contain `__`; aliases cannot collide with toolkit tools. Each tool policy requires an operator-authored `description` and closed `input_schema`; the gateway exposes and validates those values instead of the upstream's live description or input schema. Declare a root object and one explicit type per schema node. Every object schema must set `additionalProperties: false`. For arrays, supply an item schema or set `items: false` to allow only an empty array. Argument schemas reject `allOf`, `anyOf`, `oneOf` and `prefixItems`. Use ASCII IDNA A-labels for internationalized hosts in HTTPS endpoints and resource origins. Each tool policy defaults to `assurance: "advisory"`; use explicit `review_read` only after the operator has established that the declared fields and data classes are a bounded read whose successful use may remain approval-eligible. This assurance is operator policy, not a server annotation. Registry v2 is rejected rather than reinterpreted; migrate each selected tool by reviewing and adding its operator-owned interface fields, then set `version` to `3`. +`OCR_MCP_SERVERS_JSON` accepts only the closed version-3 registry. Server and tool names use ASCII letters, digits, underscore or hyphen, begin with a letter, and cannot contain `__`; aliases cannot collide with toolkit tools. Each tool policy requires an operator-authored `description` and closed `input_schema`; the gateway exposes and validates those values instead of the upstream's live description or input schema. Declare a root object and one explicit type per schema node. Every object schema must set `additionalProperties: false`. For arrays, supply an item schema or set `items: false` to allow only an empty array. Argument schemas reject `allOf`, `anyOf`, `oneOf` and `prefixItems`. Use ASCII IDNA A-labels for internationalized hosts in HTTPS endpoints and resource origins. Each tool policy defaults to `assurance: "advisory"`; use explicit `review_read` only after the operator has established that the declared fields and data classes are a bounded read whose successful use may remain approval-eligible. This assurance is operator policy, not a server annotation. + +To migrate a v2 registry, add those two fields to each allowlisted tool, set +`version` to `3`, and roll out the registry with the new toolkit and qualified +OCR binary. A v2 registry is rejected before review. Identity-only GitLab +deployments without external MCP tools can leave `OCR_MCP_SERVERS_JSON` unset. A GitLab-MR external server therefore looks like: diff --git a/docs/engineering/execution_history/README.md b/docs/engineering/execution_history/README.md index a4ecc31b..ec5cc080 100644 --- a/docs/engineering/execution_history/README.md +++ b/docs/engineering/execution_history/README.md @@ -14,6 +14,7 @@ | Stable tag | Primary archived plan | Related context in the same archive | | --- | --- | --- | +| `v0.16.1` | [Contributor intake and incremental review](plans/2026-12-01-toolkit-0-16-1-contributor-intake-and-incremental-review.md) | #351–353, #355–356 and #358. Protected promotion #361 and TestPyPI development build `0.17.0.dev154` passed. This prepublication snapshot records the handoff for stable publication, immutable receipt verification and issue reconciliation. | | `v0.16.0` | [GitLab telemetry and local review recovery](plans/2026-11-30-toolkit-0-16-0-gitlab-telemetry-and-local-review-recovery.md) | #335–343. Feature #344 and the TestPyPI development build passed. This prepublication snapshot records the handoff for stable publication, immutable receipt verification and issue reconciliation. | | `v0.15.2` | [CI outcome DLP, OCR qualification, Analysis and local telemetry](plans/2026-11-28-toolkit-0-15-2-ci-outcome-dlp-ocr-qualification-analysis-and-local-telemetry.md) | #324–330, #332 and #333. Includes the local GitLab telemetry CLI and revision-scoped review history from #331. | | `v0.15.1` | [Evidence diagnostics and rejection cleanup](plans/2026-11-16-toolkit-0-15-1-evidence-diagnostics-and-rejection-cleanup.md) | #321; distinct missing/zero evidence telemetry, closed CI cause/count facts and failure-safe rejection disposal. Protected feature #322 and development TestPyPI verified; stable markers, pins, notes and checked archive/reset prepared. Stable publication, immutable receipt readback and issue/milestone closure remain required Post-Close Delivery; this archive is a prepublication snapshot. | diff --git a/docs/engineering/execution_history/plans/2026-12-01-toolkit-0-16-1-contributor-intake-and-incremental-review.md b/docs/engineering/execution_history/plans/2026-12-01-toolkit-0-16-1-contributor-intake-and-incremental-review.md new file mode 100644 index 00000000..689b4ecc --- /dev/null +++ b/docs/engineering/execution_history/plans/2026-12-01-toolkit-0-16-1-contributor-intake-and-incremental-review.md @@ -0,0 +1,174 @@ +# Execution Plans + +## Active Plan: Toolkit 0.16.1 — contributor intake and incremental review + +plan_schema_version: 2 +Status: done +Release classification: release-required +Target release: 0.16.1 +Next development marker: 0.17.0 +Last Updated: 2026-12-01 + +### Goal + +Deliver the full selected patch release through protected external intake on `dev`, maintainer promotion to `main`, and the existing signed release and receipt process. + +### Plan Origin + +direct_execution + +### Requested Scope + +Review the new contributor's entire repository history, fix incremental qualification and extend safe reuse, integrate the pending dependency and OCR updates, harden contributor CI, update contribution rules for agent-assisted submissions and credit accepted work in the release. + +### Requirement Traceability + +| Requirement | Outcome | Queue | Status | +| --- | --- | --- | --- | +| REQ-001 | Inspect external submissions and observed GitHub disclosure surfaces | WQ-01 | done | +| REQ-002 | Protect dev intake and isolate privileged publication | WQ-02 | done | +| REQ-003 | Qualify #351/#354 and implement #352–353 | WQ-03 | done | +| REQ-004 | Review #346–350 and qualify #355 | WQ-04 | done | +| REQ-005 | Document contribution rules and conditional release credit | WQ-02, WQ-05 | done | +| REQ-006 | Complete the repository handoff for 0.16.1 and identify the required external delivery | WQ-06, WQ-08 | done | +| REQ-007 | Retain proven technical literals during publication and increase default test coverage (#358) | WQ-07 | done | + +### Explicit Non-Goals + +Keep the contributor’s changes and attribution in the original #354. Use issue links for reusable synthetic cases and the private reporting route for suspected vulnerabilities. + +### Constraints + +Inspect fork revisions as data locally. Keep private evidence, credentials, operator inputs and unredacted logs outside public artifacts. Preserve contributor attribution and the stable release authorizer. Review real effective permissions after changes. Keep security reports on the private reporting route. + +### Inputs And Sources + +Use the live [contributor PR](https://github.com/xeonvs/open-code-review-toolkit/pull/354), [CI failure](https://github.com/xeonvs/open-code-review-toolkit/actions/runs/46632932603/job/142597665154), [qualification issue](https://github.com/xeonvs/open-code-review-toolkit/issues/355), all eleven workflows, GitHub Actions settings, rulesets, environments and the repository's development, local review, compatibility and release guides. + +For AI-assisted intake, the September policy study documents substantial variation in disclosure requirements. The October Linux Foundation survey identifies disclosure and contributor responsibility as common practices. GitHub's July workflow holds illustrate why maintainers inspect proposed execution before approval. Adopt a short disclosure and actual verification evidence, with the same security review for all authors. [Policy study](https://arxiv.org/abs/2609.07542), [Linux Foundation research](https://www.linuxfoundation.org/hubfs/Research%20Reports/Navigating-Open-Source-Software-Development-in-the-Generative-AI-Era.pdf), [GitHub July update](https://github.blog/changelog/2026-07-28-github-actions-holds-potentially-malicious-workflows-for-approval/). + +### User Decisions And Answers + +Prepare the full maintainer-owned implementation on `maintainer/0.16.1-intake`, review successive changes incrementally and open a draft. Use an existing issue when available; the issue owns the synthetic case and the PR links it and reports actual validation. Keep suspected vulnerabilities on the private reporting route. + +The owner selected protected `dev → main`, the full release composition, revised contributor rules and a conditional acknowledgment section. Include all currently open maintenance PRs, independently of the human contributor's work. + +REQ-002/004 include the external contribution supply-chain threat model, Docker Hub consumption, mandatory pre-push freshness review and maintainer/Dependabot ownership. At merge the maintainer checks the author and source branch in GitHub and reviews every dependency-related change, including additions, renames/deletions, lock sources, action references and installers. Exercise an ordinary fork PR, a fork changing a pin, a spoofed bot label/name, genuine Dependabot and maintainer updates. WQ-04 includes qualifying and pinning the official Python manifest used by the GitLab example and verifying the supported Linux image and installed toolkit in that environment. Keep monthly refresh ownership explicit; the configured uv and github-actions ecosystems do not update a GitLab YAML image digest. + +The contributor guide and PR template now request material AI disclosure, human verification, existing-PR checks and source attribution. Keep intake open. If overlapping submissions become a problem here, GitHub supports a per-user limit on simultaneous external PRs without granting write access to bypass it. [GitHub June update](https://github.blog/changelog/2026-06-17-limit-open-pull-requests-for-users-without-write-access/). + +### Completed Baseline State + +At baseline, protected `main` was `c5750fd`, the v0.16.0 release merge. GitHub reported that release immutable. Remote dev and the new milestone did not exist at inspection. The contributor authored one repository PR (#354) and zero issues across all states. #351–353 belong to the maintainer, #355 to Actions and #346–350 to Dependabot. + +At b93ec7d the three changed files cover local opt-in qualification, its tests and the bugfix fragment. The change accepts two editor settings, still falls back for other unsupported settings and prints their names to stderr. Values are omitted, but arbitrary inherited names can contain private text or control characters and the output has no count or byte bound. Use a closed vocabulary of useful known names plus a generic bounded fallback. Verify the two editor commands never run during qualification or review; prefer removing the unnecessary editor values from the incremental child environment. The follow-up 4b395cbe changes only the unused test binding. + +### Current Work Queue + +| Item | Work and exit evidence | Requirements | Status | +| --- | --- | --- | --- | +| WQ-01 | Inventory submissions, review immutable diff, logs, token permissions, artifacts, CI triggers and settings. Record limits below. | REQ-001 | done | +| WQ-02 | Target the maintainer bootstrap and external PR at protected dev; promote reviewed dev to main. Restrict both publishing environments to branch main only and verify the external Trusted Publishers. Scope site dispatch credentials to the trusted main workflow/environment. Configure approval for all outside collaborators. Set up native GitHub protections and required Build/CodeQL checks on dev. At merge the maintainer verifies external PRs target dev and main receives repository-owned promotions and release PRs. Account explicitly for maintenance bots and bootstrap. Verify the intended review and retargeting paths before retargeting #354. Synchronize contribution guide and template with rollout. | REQ-002, REQ-005 | done | +| WQ-03 | Retarget and review #354 at the new merge base, retain author credit, replace premature issue closing keywords, address diagnostic bounds. #352 uses closed per-group reason counts with overlapping reasons and no paths/arguments. #353 extends file-level reuse to unchanged non-Python blobs and replays bounded deterministic searches on immutable inputs; qualify only complete equivalent observations including dependencies, result order, truncation and failures. Recheck uncertain groups. | REQ-003 | done | +| WQ-04 | Integrate development tooling #346, certifi #347, regex #348, httpx2 #349 and six action updates #350. Check upstream commit identities, permissions, cache defaults and artifact changes before updating action pins. Reconcile overlapping lock changes and test the combined tree. For #355 inspect upstream gitignore/preview semantics, verify exact assets, Linux and applicable native handoffs and consumer behavior before promotion to OCR 1.14.6. | REQ-004 | done | +| WQ-05 | Add conditional Towncrier Contributors category, maintainer-reviewed public handle and accepted PR link once per contributor. Verify populated and empty releases, canonical changelog section and final comparison link. | REQ-005 | done | +| WQ-06 | Merge the reviewed protected promotion after WQ-08, verify the resulting development build on TestPyPI, and prepare the signed release/v0.16.1 pull request and checked archive. Stable publication and external reconciliation are Post-Close Delivery. | REQ-006 | done | +| WQ-07 | Qualify publication-only DLP handling for date ranges, dated headings and size assignments, retain phone and credential rejection, and integrate #359 through the twelve protected checks. | REQ-007 | done | +| WQ-08 | Complete corrective review, verify native OCR and installed-wheel behavior, and run quality and secret gates on the final development range. Preserve the private review evidence through the coordinated disclosure boundary. | REQ-006 | done | + +### Locked Decisions + +The maintainer retained #354 against its original fork head and posted [two requested adjustments](https://github.com/xeonvs/open-code-review-toolkit/pull/354#issuecomment-7310075633). After protected dev was ready, the maintainer retargeted the existing PR, required fresh checks, and retained authorship through the dev squash merge. The repository-owned dev-to-main promotion used non-closing issue references. + +Exercise the base-change event in CI. Default pull_request activity types omit edited. Require observed runs bound to the new dev base and head; a rerun of an old main-target event cannot establish this. [GitHub base change behavior](https://docs.github.com/en/pull-requests/how-tos/create-pull-requests/changing-the-base-branch-of-a-pull-request). + +Protect the long-lived dev ref from automatic deletion. Repository merge commits are enabled. Main retains signed linear history, strict checks and squash/rebase restrictions. Create a maintainer sync branch at the current dev tip, merge main into it with a signed commit, and merge its reviewed PR into dev with a merge commit so the latest main becomes its ancestor after a squash promotion and release-marker changes. Test two consecutive promotion cycles and verify that the second contains only its intended tree changes. Keep this configuration decision in the bootstrap review. + +Fork validation uses GitHub-hosted pull_request jobs with SHA-pinned actions, read-only effective tokens, no environment, no publisher secrets or OIDC. Allow classification, tests, lint/types, SAST, dependency review/audit, CodeQL PR analysis and distribution build/install smoke after head review. Read the Gitleaks policy and version selector from the protected base. Keep package build local to the job for external PRs; disable unnecessary fork artifact uploads, including scanner reports, or validate and redact any retained public output. Rebuild reviewed source for publication. Reserve Release, TestPyPI, site dispatch, Scorecard publication, maintenance and qualification writes for trusted triggers. No privileged execution of fork code through pull_request_target or workflow_run. + +### Verification + +Verify a bare dev push starts no publisher. With a dev-to-main promotion open, push a fresh reviewed commit to dev and inspect the resulting PR synchronization jobs for effective permissions and exclusion of publishing OIDC and site credentials. Use a fork PR to verify dev CI and actual runner permission banners, maintainer retargeting of external main-targeted PRs, eligible dev promotion, changed-head reapproval, and dev exclusion from both registry environments. Check release authorization on its existing protected path. Verify the actual current PR target, source repository and revision in GitHub before merge. Verify admin bypass is limited and auditable. Allow the sole maintainer to promote via a reviewed PR without creating an impossible self-approval requirement. Require maintainer review of external changes, especially workflows, runnable build/test scripts, dependencies and CODEOWNERS. + +For #351–353 exercise installed incremental review across successive heads, an editor setting, a disallowed key, bounded diagnostics, changed and unchanged search results, deleted and newly matching files, failed/incomplete calls, changed policy and the issue's 23-file/two-change case. Compare findings with fresh full review. Run focused tests, quality, Gitleaks, dependency audit, aggregate security and own-tool review, installed package smoke and the release contracts named in docs/release.md. Versioned dependency CI and hosted ruleset checks must cover the exact promotion tree. + +### Latest Validation Results + +The maintainer intake work is tracked in [#356](https://github.com/xeonvs/open-code-review-toolkit/issues/356). The external contribution stays in #354. The contribution guide and forms now put reusable synthetic evidence on the issue; the PR records implementation, verification and attribution. Maintainers own the shared release plan and credit accepted work through Towncrier. + +The maintainer branch integrates #346–350, qualifies OCR 1.14.6 with official assets and exercises the installed wheel on Linux amd64 using the pinned GitLab Python image. Empty and populated Towncrier previews verified conditional contributor credit. This baseline preceded the hosted intake transition and the protected promotion. A real self-review of c5750fd..d37c88d completed all 21 selected files and identified documentation corrections. Two incremental attempts on the first commit failed before a model response when using the staged executable. With governed MCP enabled, official OCR 1.14.6 exercised a complete fresh review and recorded the reason, with one completed gateway call and no reused files. + +The managed worktree scan rejected the resolvable maintainer checkout before allocating a scan ID or SARIF. Independent reviewers inspected contributor intake, publisher recovery, site notification, secrets, cache and artifact permissions, and traced incremental playback against OCR 1.14.6. The owner accepted this limitation for the draft only. Review findings on partial observations, native input ordering, narrowed groups, private argument storage and dependency selection are tracked through implementation and regression checks. + +The owner selected native GitHub branch rules and a maintainer decision at merge. Both branch protections and isolation of publication credentials preceded external intake on `dev`. + +The contributor replied and updated #354 to 26080da. Static review on that revision confirmed both editor keys are removed from the incremental child environment and the diagnostic uses a bounded fixed vocabulary. The existing PR remained open at that stage for protected dev intake. + +All eleven main-required checks passed on 26080da. The maintainer [acknowledged both corrections](https://github.com/xeonvs/open-code-review-toolkit/pull/354#issuecomment-7311647605) and retained the PR for protected dev intake. + +After updating the installed Darwin OCR to 1.14.6 and granting outbound access, two actual ChatGPT incremental reviews completed in a disposable repository. The first saved one qualified file. After editing that file the second correctly performed fresh review and saved its new baseline. The local development firewall binds its allowance to an executable path and subsequently blocked another session copy. Maintainer self-review on this host uses the installed OCR path. A controlled provider exercised reuse of 21 of 23 files in a separate official-binary test. + +The approved 4b395cbe rerun completed with all 17 checks successful, including quality and both platform matrices. All five revised workflow log archives, the revised unpacked wheel/sdist and the SARIF artifact passed the redacted signature scan. Revised job banners again showed only read permissions. The SARIF contained zero results. These observations supersede the initial approval state below. The maintainer's public comment preceded the later protection changes and retargeting. + +At b93ec7d all five workflows ran on pull_request, attempt 2. Attempt 1 lists zero jobs. Six test jobs, build, scanners and dependency review passed. Quality stopped on Ruff RUF059 before mypy. At 4b395cbe Ruff passes on the exact revised test file; all five new workflows initially returned action_required. Local diff whitespace validation passed. A manual static review covered the changed files and supporting environment handoff. The managed diff scan rejected the resolvable worktree before creating a scan ID. This attempt produced no managed scan evidence. + +All five observed job-log archives showed read-only token permissions, including SecurityEvents read for CodeQL. Redacted Gitleaks scans found no matches in the downloaded logs, SARIF and unpacked wheel/sdist streams. SARIF contained zero results. These observations cover recorded output and known detectors. Runner network traffic and private cache contents were not observed. + +Before rollout, live metadata showed a public repository, no registered repository runners, default read token, Actions PR approvals disabled, mandatory SHA pinning, verified creators broadly allowed and approval only for first-time contributors. No repository Actions variables or environment secrets/variables were listed. A repository-level site dispatch secret existed. Main caches include setup-uv and Gitleaks; assume fork jobs can read base caches. No #354 merge cache was listed. Inspect cache producers and inputs, disable fork restore/save where unnecessary, and keep private packages, home directories and credentials out of every base cache. Review implicit setup-uv defaults in quality, build and security jobs. [GitHub cache scopes](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching). + +Before rollout, the main ruleset required PRs, signatures, strict checks and thread resolution, with zero approving reviews, no mandatory CODEOWNERS and a PR-only admin bypass. Its check list omitted the Ubuntu 3.13 matrix job documented as blocking. Only the owner appeared in the collaborator inventory. Both publication environments allowed all protected branches. The notifier reads trusted metadata and a public receipt without checking out triggering source; strengthen the match between receipt run/attempt and publication, with the documented recovery path covered. Open secret-scanning and Dependabot alerts were zero. Four open Scorecard alerts concern CI tests, SAST, code review and branch protection; reconcile against live configuration after rollout. + +On 2026-12-01, the maintainer bootstrap merged into protected `dev` at `ef5f376`. GitHub readback showed a PR gate and required status checks on `dev`. The branch policy for each of the TestPyPI, PyPI and site-notification environments selects only `main`. The site dispatch credential is environment-scoped, the repository Actions secret list is empty, and fork workflows require maintainer approval. [Maintainer bootstrap #357](https://github.com/xeonvs/open-code-review-toolkit/pull/357). + +The retargeted contributor PR passed all twelve required checks at `75bedaf` against `ef5f376`. GitHub attributed verified squash commit `feafbf7` to @ahmedpdf445-stack. The #358 regression fix reached protected `dev` at `f65053e` through #359. [Contributor PR #354](https://github.com/xeonvs/open-code-review-toolkit/pull/354), [DLP correction #359](https://github.com/xeonvs/open-code-review-toolkit/pull/359). + +The corrective PR passed protected checks at `ba80c66` and merged into `dev` as `4e82db1`. Its recorded local gate passed 6,809 tests and 364 subtests, with 11 optional skips and 90.03% coverage. Both distribution formats passed isolated installation and runtime MCP smoke. Gitleaks passed on the patch range and tree, and the locked dependency audit reported no known vulnerabilities. [Corrective PR #360](https://github.com/xeonvs/open-code-review-toolkit/pull/360). + +The test-only OCR follow-up passed protected checks at `d2ce8ee` and merged into `dev` as `65ed3d0`. It verifies rejection when the protected base's OCR 1.14.5 preview omits a tracked ignored file and checks the explicit gitignore exclusion and production manifest with qualified OCR 1.14.6. Its recorded local validation passed all 78 gitlink tests with the qualified OCR executable, plus Ruff, Gitleaks and dependency audit. [Trusted-base OCR checks #362](https://github.com/xeonvs/open-code-review-toolkit/pull/362). + +All seventeen hosted PR checks passed on #360, #362 and #361. Protected promotion #361 used `65ed3d0` and merged as `a2ca5b4` on top of `c5750fd`. The promoted tree matched `65ed3d0` exactly as `d3631431dcecd4f200a7a8355a8e66e94289eae2`. [Promotion PR #361](https://github.com/xeonvs/open-code-review-toolkit/pull/361). + +The TestPyPI development workflow on `a2ca5b4` completed all four jobs, including Trusted Publishing and verification of the exact published wheel and source distribution. TestPyPI readback listed both files for `0.17.0.dev154`. [Development build 154](https://github.com/xeonvs/open-code-review-toolkit/actions/runs/46745358005). + +The extracted release notes credit the accepted contributor once under Contributors and end with the v0.16.0 to v0.16.1 comparison. The authorization metadata lists all six open release issues. The candidate uses the protected promotion commit timestamp as its deterministic source epoch and retains the existing next development line. + +### Risks And Recovery + +Protect dev before admitting any external code. A PR from dev in the same repository has a different trust context from a fork and may reference repository secrets. Restrict sensitive credentials first. Retain the protected-main path for bootstrap and recovery. If dev filters, scope isolation or branch protections fail, keep intake pending, correct trusted policy, and repeat affected checks. Never copy a fork build artifact into a privileged publishing job. Re-read PR heads and settings on resume. + +### Resume Point + +No repository implementation remains. This archive records the prepublication handoff. + +### Plan Fidelity Check + +REQ-001 through REQ-007 cover the selected inputs, release preparation, contributor guidance and attribution, CI isolation, incremental qualification, DLP and corrective review. Their queue items and validation evidence identify the relevant boundary and revision. Stable publication and external verification retain an explicit delivery stage. + +### Reconciliation Check + +Protected intake, contributor attribution and the exact dev-to-main promotion agree with the recorded GitHub evidence. The release issue set is #351, #352, #353, #355, #356 and #358. Tracked issues and the milestone remain open for receipt-backed closure. + +### Closure Gate + +The protected promotion and verified TestPyPI development build cover the accepted implementation. The release PR carries the stable and next development markers, reproducible build epoch, tracked issue authorization, generated notes, qualified GitLab example and checked archive. + +### Post-Close Delivery + +Protected release-PR checks and signed squash merge, stable publication and independent external reconciliation are outside the closed repository plan. The Release workflow verifies the stable TestPyPI and PyPI artifacts, supported Python installs, provenance, annotated tag, immutable GitHub Release and receipt before issue closure. The operator reads back exact external delivery, verifies issue and milestone closure, and reconciles protected branches and temporary resources. + +### Handoff Notes + +No in-scope work remains. The contributor attribution is preserved in #354 and the generated changelog. + +## Recently Completed + +- [x] 2026-11-30: Completed Toolkit 0.16.0 — GitLab telemetry and local review recovery; [full archived plan](docs/engineering/execution_history/plans/2026-11-30-toolkit-0-16-0-gitlab-telemetry-and-local-review-recovery.md). +- [x] 2026-11-28: Completed Toolkit 0.15.2 — CI outcome DLP, OCR qualification, Analysis and local telemetry; [full archived plan](docs/engineering/execution_history/plans/2026-11-28-toolkit-0-15-2-ci-outcome-dlp-ocr-qualification-analysis-and-local-telemetry.md). +- [x] 2026-11-16: Completed Toolkit 0.15.1 — evidence diagnostics and rejection cleanup; [full archived plan](docs/engineering/execution_history/plans/2026-11-16-toolkit-0-15-1-evidence-diagnostics-and-rejection-cleanup.md). +- [x] 2026-11-16: Completed Toolkit 0.15.0 — complete evidence, .NET and numeric DLP; [full archived plan](docs/engineering/execution_history/plans/2026-11-16-toolkit-0-15-0-complete-evidence-net-and-numeric-dlp.md). +- [x] 2026-11-12: Completed Toolkit 0.14.8 — OCR 1.13.8, provider HTTP and first integration; [full archived plan](docs/engineering/execution_history/plans/2026-11-12-toolkit-0-14-8-ocr-1-13-8-provider-http-and-first-integration.md). +- [x] 2026-11-10: Completed Toolkit 0.14.7 — OCR 1.13.7, recoverable diagrams and private diagnostics; [full archived plan](docs/engineering/execution_history/plans/2026-11-10-toolkit-0-14-7-ocr-1-13-7-recoverable-diagrams-and-private-diagnostics.md). +- [x] 2026-11-06: Completed Internal engineering cycle corrections; [full archived plan](docs/engineering/execution_history/plans/2026-11-06-internal-engineering-cycle-corrections.md). +- [x] 2026-11-06: Completed Toolkit 0.14.6 — OCR 1.13.6, DLP precision and efficient delivery; [full archived plan](docs/engineering/execution_history/plans/2026-11-06-toolkit-0-14-6-ocr-1-13-6-dlp-precision-and-efficient-delivery.md). +- [x] 2026-11-04: Completed Toolkit 0.14.5 — DLP precision, OCR qualification and maintenance quality; [full archived plan](docs/engineering/execution_history/plans/2026-11-04-toolkit-0-14-5-dlp-precision-ocr-qualification-and-maintenance-quality.md). +- [x] 2026-10-31: Completed Toolkit 0.14.4 systematic DLP corrections and diagram source validation; [full archived plan](docs/engineering/execution_history/plans/2026-10-31-toolkit-0-14-4-systematic-dlp-corrections-and-diagram-source-validation.md). diff --git a/docs/engineering/execution_history/plans/README.md b/docs/engineering/execution_history/plans/README.md index 3c29d3ad..c97bf69f 100644 --- a/docs/engineering/execution_history/plans/README.md +++ b/docs/engineering/execution_history/plans/README.md @@ -20,4 +20,5 @@ Each new repository plan archived through the engineering-workflow lifecycle is - [2026-11-16-toolkit-0-15-1-evidence-diagnostics-and-rejection-cleanup.md](2026-11-16-toolkit-0-15-1-evidence-diagnostics-and-rejection-cleanup.md) - [2026-11-28-toolkit-0-15-2-ci-outcome-dlp-ocr-qualification-analysis-and-local-telemetry.md](2026-11-28-toolkit-0-15-2-ci-outcome-dlp-ocr-qualification-analysis-and-local-telemetry.md) - [2026-11-30-toolkit-0-16-0-gitlab-telemetry-and-local-review-recovery.md](2026-11-30-toolkit-0-16-0-gitlab-telemetry-and-local-review-recovery.md) +- [2026-12-01-toolkit-0-16-1-contributor-intake-and-incremental-review.md](2026-12-01-toolkit-0-16-1-contributor-intake-and-incremental-review.md) diff --git a/docs/gitlab.md b/docs/gitlab.md index a4e34101..a93f5a48 100644 --- a/docs/gitlab.md +++ b/docs/gitlab.md @@ -6,7 +6,12 @@ GitLab is the toolkit's first forge provider. The provider layer owns GitLab API Install `open-code-review-toolkit` from PyPI and install Open Code Review separately. Use the exact recommended OCR version and asset checksum from the [compatibility manifest](../compatibility/ocr-support.json); the toolkit package never downloads OCR. -Start with the [complete checksum-pinned pipeline](../examples/gitlab/ocr-review.gitlab-ci.yml), then choose a mode from the same toolkit release tag. The default identity-only mode requires no external registry. If you enable federation, use the registry format and mode file from the tag named by `OCR_TOOLKIT_VERSION` in the linked pipeline. To adopt the operator-authored v3 recipe, take both files from a release tag that ships it. See the [GitLab mode matrix](../examples/gitlab/README.md). The pipeline keeps the repository's lint/test stage ahead of AI review, verifies the release runtime lock and toolkit wheel, installs hash-locked binary dependencies followed by the wheel, checks dependency consistency, runs preflight and configuration, performs one production `ocr-ci review`, and makes `ocr-ci post` the sole GitLab write boundary. The rules pack adds Jinja, conventional Ansible-role templates, and Twig to the recommended OCR file selection; project exclusions still win. +Start with the [complete checksum-pinned pipeline](../examples/gitlab/ocr-review.gitlab-ci.yml), then choose a mode from the same toolkit release tag. The pipeline keeps the repository's lint/test stage ahead of AI review, verifies the release runtime lock and toolkit wheel, installs hash-locked binary dependencies followed by the wheel, checks dependency consistency, runs preflight and configuration, performs one production `ocr-ci review`, and makes `ocr-ci post` the sole GitLab write boundary. The rules pack adds Jinja, conventional Ansible-role templates, and Twig to the recommended OCR file selection; project exclusions still win. + +Use the install and mode files from the tag named by `OCR_TOOLKIT_VERSION`. +The default identity-only mode needs no external registry. If you already use +governed federation, migrate its registry and tool declarations when you update +the pipeline. [Registry v3 migration](configuration.md#governed-mcp-federation-and-trust-boundary) · [GitLab mode matrix](../examples/gitlab/README.md) Use a `linux/amd64` runner with an executor that honors the GitLab `image:` setting, such as the Docker executor. The job starts the official Python image at a pinned Docker Hub manifest digest and installs the Linux amd64 OCR @@ -14,10 +19,6 @@ binary. ## Required configuration -Behavior/Impact Analysis requires the wheel and qualified binary described in -the [paired upgrade instructions](compatibility.md#upgrading-the-toolkit-and-ocr). -Use the example from the matching release tag once published. The preceding -release’s example still pins the older wheel and ignores the Analysis setting. Set `OCR_ANALYSIS=true` on the ordinary review job to investigate the same MR diff alongside the main review. Set `OCR_ANALYSIS_MAX_TOKENS_BUDGET` to cap the investigation separately. By default the result stays in the private job JSON. The example uploads no report artifact. To show the investigation to MR readers, add one flag to the existing post command in that job: diff --git a/examples/gitlab/README.md b/examples/gitlab/README.md index 99501892..c21205be 100644 --- a/examples/gitlab/README.md +++ b/examples/gitlab/README.md @@ -44,7 +44,9 @@ pipeline timing and merge-policy implications. It does not replace manual readin | Enriched discussions | [`modes/enriched-discussions.gitlab-ci.yml`](modes/enriched-discussions.gitlab-ci.yml) | Metadata plus protected-policy GitLab discussions and remediation threads | GitLab reads before OCR | Explicitly disabled in the recipe | | Governed MCP federation | [`modes/direct-mcp.gitlab-ci.yml`](modes/direct-mcp.gitlab-ci.yml) | Metadata plus model-selected, gateway-admitted tool results | Authorized HTTPS upstream through the bounded gateway | Used advisory tools are comment-only; unused services and successful `review_read` use are not independent blockers | -Use the mode files from the same Git tag as the checksum-pinned wheel. The governed MCP recipe requires a wheel that accepts the operator-authored registry interface. +Use the mode files from the same Git tag as the checksum-pinned wheel. The +governed MCP recipe requires the operator-authored registry interface. +[Registry v3 migration](../../docs/configuration.md#governed-mcp-federation-and-trust-boundary) The default `auto` profile can use `off`, `metadata`, `enriched`, and configured federation for a single MR targeting an unprotected branch; its Rules and context policy come from the protected default branch P, while the actual diff and target stay separate. It never adds an approval for that unprotected target. The explicit `unprotected` recipe retains the earlier limited profile: only `off` or `metadata`, Rules at the exact captured target SHA as untrusted guidance, no accepted decisions or structured guidance, and no enriched context or external federation. Its limitation line does not make a complete result incomplete. A protected target keeps normal behavior in either profile. diff --git a/examples/gitlab/ocr-review.gitlab-ci.yml b/examples/gitlab/ocr-review.gitlab-ci.yml index b0d4ff09..935ec74e 100644 --- a/examples/gitlab/ocr-review.gitlab-ci.yml +++ b/examples/gitlab/ocr-review.gitlab-ci.yml @@ -6,10 +6,10 @@ default: image: docker.io/library/python:3.12-slim@sha256:5b5fe805d367f8f5a359ded6ab2652b7f9a206453ee6ee789c0045ba6ec15016 variables: - OCR_VERSION: "v1.14.5" - OCR_TOOLKIT_VERSION: "0.16.0" + OCR_VERSION: "v1.14.6" + OCR_TOOLKIT_VERSION: "0.16.1" OCR_TOOLKIT_CHECKSUMS_URL: "https://github.com/xeonvs/open-code-review-toolkit/releases/download/v${OCR_TOOLKIT_VERSION}/SHA256SUMS" - OCR_SHA256: "4bfb9142dda07c38e120c83ceeaed3e86697aa401e57d683df063a5b7c5d64d4" + OCR_SHA256: "a91fea039d7070f8155e8bdaac3b8324e97104fb510ac0fa97de40e622ee3fff" OCR_POST_MODE: "draft" OCR_STRICT_POSTING: "true" # Default-on receipt-bound approval; governed federation still applies receipt gates. From da768adf55b40d584fa52a2c068228f70c111fff Mon Sep 17 00:00:00 2001 From: Max Irgiznov <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:16:00 +0100 Subject: [PATCH 3/4] Restore protected stable publishing and reduce redundant CI (#366) Related to #364. This protected workflow repair restores publication for the release source approved in #363 and incorporates the CI reductions prepared in #365. - Start stable publication explicitly from protected main. Validate the original PR, squash parent, signature, tree, required checks and tracked release issues using the policy preceding the release PR. Pin the PR metadata read to the GitHub REST version that supplies the merge identity. - Before a historical rebuild may publish, verify its wheel, sdist and runtime lock against the original GitHub-hosted release workflow attestations on main. Keep both registry environments, OIDC, four supported Python minors, immutable release and receipt checks. - Remove release and site workflows triggered by ordinary PR closures. Group scheduled minor and patch runtime updates and document how to reconcile superseded bot proposals before promotion. - Avoid allocating the two advisory macOS jobs on classified internal docs-only PRs and direct dev-to-main promotions. Keep all four required Linux identities and allow manual full-platform qualification. Body-edit changes to required checks remain tracked in #364 pending hosted acceptance. The two earlier publication attempts stopped before registry writes. The original signed artifact bytes verified against the approved release merge. After this repair merges, dispatch release.yml on main with the original identities, verify both registries and the immutable receipt, and sync main into dev via a protected merge. --- .github/dependabot.yml | 4 + .github/workflows/ci.yml | 45 ++++++-- .github/workflows/release.yml | 125 ++++++++++------------ .github/workflows/site-release-notify.yml | 17 +-- changelog.d/364.maintenance.md | 1 + docs/codex/TASKS_BACKLOG.md | 10 ++ docs/contributor-intake.md | 14 ++- docs/development.md | 22 ++-- docs/release.md | 24 +++-- tests/test_docs_only_ci.py | 79 +++++++++++++- tests/test_quality_script.py | 13 ++- tests/test_release_authorization.py | 90 ++++++++++++---- tests/test_release_receipt.py | 62 +++++++++++ tests/test_site_release_notify.py | 13 ++- tests/test_testpypi_preview.py | 40 ++++--- 15 files changed, 407 insertions(+), 152 deletions(-) create mode 100644 changelog.d/364.maintenance.md diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 9bd2596a..49d5369a 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -12,6 +12,10 @@ updates: development-tooling: dependency-type: development patterns: ["*"] + runtime-maintenance: + applies-to: version-updates + dependency-type: production + update-types: [minor, patch] labels: [dependencies, python] commit-message: prefix: deps diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bc5d6ab2..b23de81f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,6 +20,7 @@ jobs: timeout-minutes: 5 outputs: docs_only: ${{ steps.paths.outputs.docs_only }} + skip_macos: ${{ steps.paths.outputs.skip_macos }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -30,17 +31,36 @@ jobs: env: BASE: ${{ github.event.pull_request.base.sha }} HEAD: ${{ github.event.pull_request.head.sha }} + BASE_REF: ${{ github.event.pull_request.base.ref }} + HEAD_REF: ${{ github.event.pull_request.head.ref }} + HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }} run: | result=docs_only=false + skip_macos=false trusted_script="$RUNNER_TEMP/docs_only.py" if git show "${BASE}:scripts/docs_only.py" > "$trusted_script"; then if output=$(env -u GITHUB_OUTPUT python "$trusted_script" --base "$BASE" --head "$HEAD"); then case "$output" in - docs_only=true|docs_only=false) result="$output" ;; + docs_only=true|docs_only=false) + result="$output" + if [ -n "$HEAD_REPO" ] && [ "$HEAD_REPO" = "$GITHUB_REPOSITORY" ]; then + if [ "$result" = docs_only=true ]; then + skip_macos=true + elif [ "$BASE_REF" = main ] && [ "$HEAD_REF" = dev ]; then + # Only exit 1 proves a nonempty delta for this direct promotion. + if git --no-replace-objects diff --quiet --no-ext-diff --no-textconv "$BASE" "$HEAD" --; then + : + elif [ "$?" -eq 1 ]; then + skip_macos=true + fi + fi + fi + ;; esac fi fi echo "$result" >> "$GITHUB_OUTPUT" + echo "skip_macos=$skip_macos" >> "$GITHUB_OUTPUT" test-python312: name: >- @@ -82,18 +102,21 @@ jobs: ${{ github.event_name != 'pull_request' && format('manual-test-{0}-py{1}', matrix.os, matrix.python) || github.event.pull_request.draft && 'draft-deferred-test-matrix' || format('test-{0}-py{1}', matrix.os, matrix.python) }} if: ${{ !cancelled() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }} - continue-on-error: ${{ matrix.advisory }} + continue-on-error: ${{ matrix.os == 'macos-latest' }} env: UV_PYTHON: ${{ matrix.python }} strategy: fail-fast: false matrix: - include: - - { os: ubuntu-latest, python: "3.13", coverage: false, advisory: false } - - { os: ubuntu-latest, python: "3.14", coverage: true, advisory: false } - - { os: ubuntu-latest, python: "3.15", coverage: false, advisory: false } - - { os: macos-latest, python: "3.12", coverage: false, advisory: true } - - { os: macos-latest, python: "3.14", coverage: false, advisory: true } + os: >- + ${{ fromJSON(github.event_name == 'pull_request' && needs.classify.result == 'success' && + needs.classify.outputs.skip_macos == 'true' && '["ubuntu-latest"]' || + '["ubuntu-latest","macos-latest"]') }} + python: ["3.12", "3.13", "3.14", "3.15"] + exclude: + - { os: ubuntu-latest, python: "3.12" } + - { os: macos-latest, python: "3.13" } + - { os: macos-latest, python: "3.15" } runs-on: ${{ matrix.os }} timeout-minutes: 30 steps: @@ -104,7 +127,7 @@ jobs: persist-credentials: false - name: Install qualified OCR for native coverage id: native-ocr - if: ${{ needs.classify.outputs.docs_only != 'true' && matrix.coverage }} + if: ${{ needs.classify.outputs.docs_only != 'true' && matrix.os == 'ubuntu-latest' && matrix.python == '3.14' }} env: PR_BASE: ${{ github.event.pull_request.base.sha }} shell: bash @@ -173,10 +196,10 @@ jobs: - if: needs.classify.outputs.docs_only != 'true' run: uv sync --locked --python "${{ matrix.python }}" - name: Test - if: ${{ needs.classify.outputs.docs_only != 'true' && !matrix.coverage }} + if: ${{ needs.classify.outputs.docs_only != 'true' && (matrix.os != 'ubuntu-latest' || matrix.python != '3.14') }} run: uv run --no-sync pytest -q --ignore=tests/test_installed_policy_e2e.py - name: Test with boundary coverage gates - if: ${{ needs.classify.outputs.docs_only != 'true' && matrix.coverage }} + if: ${{ needs.classify.outputs.docs_only != 'true' && matrix.os == 'ubuntu-latest' && matrix.python == '3.14' }} env: OCR_FEDERATION_QUALIFY_BINARY: ${{ steps.native-ocr.outputs.binary }} OCR_GITLINK_QUALIFY_BINARY: ${{ steps.native-ocr.outputs.binary }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8cb9f5bb..0be89cd3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,9 +1,6 @@ name: Release on: - pull_request: - types: [closed] - branches: [main] workflow_dispatch: inputs: pull-request-number: @@ -31,39 +28,23 @@ permissions: contents: read concurrency: - group: production-release + # Match authorize.if so skipped dispatches cannot replace a pending release. + group: >- + ${{ + github.event_name == 'workflow_dispatch' && + github.event.repository.private == false && + github.ref == 'refs/heads/main' && + 'production-release' || format('release-ignored-{0}', github.run_id) + }} cancel-in-progress: false jobs: - classify: - name: classify-release-trigger - runs-on: ubuntu-latest - timeout-minutes: 2 - outputs: - release: ${{ steps.classify.outputs.release }} - steps: - - id: classify - env: - EVENT_NAME: ${{ github.event_name }} - PR_MERGED: ${{ github.event.pull_request.merged }} - PR_HEAD_REF: ${{ github.event.pull_request.head.ref }} - run: | - release=false - if [ "${EVENT_NAME}" = workflow_dispatch ]; then - release=true - elif [ "${PR_MERGED}" = true ] && [[ "${PR_HEAD_REF}" == release/v* ]]; then - release=true - fi - echo "release=${release}" >> "${GITHUB_OUTPUT}" - authorize: name: authorize-release - needs: classify if: >- + github.event_name == 'workflow_dispatch' && github.event.repository.private == false && - github.ref == 'refs/heads/main' && - (github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && - needs.classify.outputs.release == 'true' + github.ref == 'refs/heads/main' runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -83,16 +64,14 @@ jobs: tree: ${{ steps.authorize.outputs.tree }} version: ${{ steps.authorize.outputs.version }} steps: - - name: Load the pinned main history for recovery - if: github.event_name == 'workflow_dispatch' + - name: Load the pinned main history uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.sha }} path: dispatch-main fetch-depth: 0 persist-credentials: false - - name: Verify the historical recovery policy reference before checkout - if: github.event_name == 'workflow_dispatch' + - name: Verify the protected release policy reference before checkout env: GH_TOKEN: ${{ github.token }} PR_NUMBER: ${{ inputs['pull-request-number'] }} @@ -102,6 +81,10 @@ jobs: BASE: ${{ inputs['reviewed-base'] }} shell: bash run: | + if [[ "${GITHUB_REF}" != refs/heads/main ]]; then + echo "release dispatch must run from refs/heads/main" >&2 + exit 1 + fi [[ "${PR_NUMBER}" =~ ^[1-9][0-9]*$ && "${VERSION}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] [[ "${MERGE}" =~ ^[0-9a-f]{40}$ && "${HEAD}" =~ ^[0-9a-f]{40}$ && "${BASE}" =~ ^[0-9a-f]{40}$ ]] [[ "${GITHUB_SHA}" =~ ^[0-9a-f]{40}$ ]] @@ -116,55 +99,46 @@ jobs: curl --fail --silent --show-error --proto '=https' \ --connect-timeout 10 --max-time 30 --max-filesize 1048576 \ --header 'Accept: application/vnd.github+json' \ - --header 'X-GitHub-Api-Version: 2026-03-10' \ + --header "X-GitHub-Api-Version: $1" \ --oauth2-bearer "${GH_TOKEN}" \ - "https://api.github.com/repos/${GITHUB_REPOSITORY}/$1" + "https://api.github.com/repos/${GITHUB_REPOSITORY}/$2" } - read_github_metadata "pulls/${PR_NUMBER}" | + # Pull request responses in 2026-03-10 omit merge_commit_sha. + if ! read_github_metadata 2022-11-28 "pulls/${PR_NUMBER}" | jq -e --arg repo "${GITHUB_REPOSITORY}" --argjson number "${PR_NUMBER}" \ --arg version "${VERSION}" --arg head "${HEAD}" --arg merge "${MERGE}" --arg base "${BASE}" ' .number == $number and .merged == true and .merge_commit_sha == $merge and .base.repo.full_name == $repo and .base.ref == "main" and .base.sha == $base and .head.repo.full_name == $repo and .head.ref == ("release/v" + $version) and .head.sha == $head and .title == ("Release v" + $version) - ' >/dev/null - read_github_metadata "git/commits/${MERGE}" | + ' >/dev/null; then + echo "release pull request does not match the requested identities" >&2 + exit 1 + fi + if ! read_github_metadata 2026-03-10 "git/commits/${MERGE}" | jq -e --arg merge "${MERGE}" --arg base "${BASE}" ' .sha == $merge and (.parents | length) == 1 and .parents[0].sha == $base - ' >/dev/null + ' >/dev/null; then + echo "release merge is not a squash of the requested protected base" >&2 + exit 1 + fi - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: # Authorization code must come from protected policy that predates the # release PR. Candidate head and merge commits are inspected only as data. - ref: ${{ github.event.pull_request.base.sha || inputs['reviewed-base'] }} + ref: ${{ inputs['reviewed-base'] }} persist-credentials: false - id: authorize env: GH_TOKEN: ${{ github.token }} - EVENT_NAME: ${{ github.event_name }} - EVENT_PR_NUMBER: ${{ github.event.pull_request.number }} - EVENT_BASE_SHA: ${{ github.event.pull_request.base.sha }} - INPUT_PR_NUMBER: ${{ inputs['pull-request-number'] }} - INPUT_VERSION: ${{ inputs.version }} - INPUT_COMMIT: ${{ inputs['merge-commit'] }} - INPUT_HEAD: ${{ inputs['reviewed-head'] }} - INPUT_BASE: ${{ inputs['reviewed-base'] }} + PR_NUMBER: ${{ inputs['pull-request-number'] }} + REQUESTED_VERSION: ${{ inputs.version }} + REQUESTED_COMMIT: ${{ inputs['merge-commit'] }} + REQUESTED_HEAD: ${{ inputs['reviewed-head'] }} + REQUESTED_BASE: ${{ inputs['reviewed-base'] }} REPOSITORY: ${{ github.repository }} run: | - if [ "${EVENT_NAME}" = workflow_dispatch ]; then - PR_NUMBER=${INPUT_PR_NUMBER} - REQUESTED_VERSION=${INPUT_VERSION} - REQUESTED_COMMIT=${INPUT_COMMIT} - REQUESTED_HEAD=${INPUT_HEAD} - REQUESTED_BASE=${INPUT_BASE} - else - PR_NUMBER=${EVENT_PR_NUMBER} - REQUESTED_VERSION= - REQUESTED_COMMIT= - REQUESTED_HEAD= - REQUESTED_BASE=${EVENT_BASE_SHA} - fi - test "$(scripts/bounded_github_api.sh \ + test "$(GITHUB_API_VERSION=2022-11-28 scripts/bounded_github_api.sh \ "repos/${REPOSITORY}/pulls/${PR_NUMBER}" /tmp/release-pr.json)" = 200 HEAD_SHA=$(jq -r .head.sha /tmp/release-pr.json) MERGE_SHA=$(jq -r .merge_commit_sha /tmp/release-pr.json) @@ -340,6 +314,21 @@ jobs: encoding="utf-8", ) PY + - name: Verify original source attestations before publication + if: github.sha != needs.authorize.outputs.commit + env: + GH_TOKEN: ${{ github.token }} + EXPECTED_COMMIT: ${{ needs.authorize.outputs.commit }} + shell: bash + run: | + for artifact in dist/* runtime-requirements.txt; do + gh attestation verify "${artifact}" \ + --repo "${GITHUB_REPOSITORY}" \ + --signer-workflow "${GITHUB_REPOSITORY}/.github/workflows/release.yml" \ + --source-digest "${EXPECTED_COMMIT}" \ + --source-ref refs/heads/main \ + --deny-self-hosted-runners + done - name: Load protected v0.11.1 PyPI recovery policy if: github.event_name == 'workflow_dispatch' && inputs.version == '0.11.1' uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -408,6 +397,7 @@ jobs: classify testpypi https://test.pypi.org/simple/open-code-review-toolkit/ /tmp/testpypi-index.json classify pypi https://pypi.org/simple/open-code-review-toolkit/ /tmp/pypi-index.json - uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + if: github.sha == needs.authorize.outputs.commit with: subject-path: | dist/* @@ -426,7 +416,7 @@ jobs: publish-testpypi: name: publish-testpypi needs: build - if: needs.build.outputs.testpypi-state == 'publish' + if: github.ref == 'refs/heads/main' && needs.build.outputs.testpypi-state == 'publish' runs-on: ubuntu-latest timeout-minutes: 10 environment: testpypi-public-disclosure @@ -479,7 +469,7 @@ jobs: publish-pypi: name: publish-pypi needs: [build, verify-testpypi] - if: needs.build.outputs.pypi-state == 'publish' + if: github.ref == 'refs/heads/main' && needs.build.outputs.pypi-state == 'publish' runs-on: ubuntu-latest timeout-minutes: 10 environment: pypi-production @@ -557,7 +547,7 @@ jobs: needs: [authorize, build, verify-pypi] if: >- always() && needs.authorize.result == 'success' && needs.build.result == 'success' && - needs.verify-pypi.result == 'success' + needs.verify-pypi.result == 'success' && github.ref == 'refs/heads/main' runs-on: ubuntu-latest timeout-minutes: 10 permissions: @@ -704,11 +694,6 @@ jobs: --hashes artifact-hashes.json \ --runtime-requirements runtime-requirements.txt \ --validate-existing release-receipt.json - if [[ "${GITHUB_EVENT_NAME}" == pull_request ]] && - ! jq -e --argjson run "${GITHUB_RUN_ID}" '.workflow.run_id == $run' release-receipt.json >/dev/null; then - echo "This receipt was created by another run. Use the main-branch release recovery dispatch." >&2 - exit 1 - fi ;; *) echo "duplicate GitHub Release receipt asset" >&2; exit 1 ;; esac diff --git a/.github/workflows/site-release-notify.yml b/.github/workflows/site-release-notify.yml index 4c23003c..cf591f51 100644 --- a/.github/workflows/site-release-notify.yml +++ b/.github/workflows/site-release-notify.yml @@ -3,6 +3,7 @@ name: Notify toolkit site of stable release on: workflow_run: workflows: [Release] + branches: [main] types: [completed] permissions: {} @@ -20,8 +21,7 @@ jobs: github.event.workflow_run.repository.full_name == github.repository && github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.conclusion == 'success' && - ((github.event.workflow_run.event == 'pull_request' && startsWith(github.event.workflow_run.head_branch, 'release/v')) || - (github.event.workflow_run.event == 'workflow_dispatch' && github.event.workflow_run.head_branch == 'main')) + github.event.workflow_run.event == 'workflow_dispatch' && github.event.workflow_run.head_branch == 'main' runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -104,11 +104,8 @@ jobs: exit 1 } read -r _ _ _ expected_tag expected_digest receipt_mode <<< "${marker}" - case "${SOURCE_EVENT}" in - pull_request) test "${SOURCE_HEAD_BRANCH}" = "release/${expected_tag}" ;; - workflow_dispatch) test "${SOURCE_HEAD_BRANCH}" = main ;; - *) exit 1 ;; - esac + test "${SOURCE_EVENT}" = workflow_dispatch + test "${SOURCE_HEAD_BRANCH}" = main gh api -H 'X-GitHub-Api-Version: 2026-03-10' "repos/${GITHUB_REPOSITORY}/releases/latest" \ > "${RUNNER_TEMP}/latest-release.json" @@ -137,21 +134,17 @@ jobs: exit 1 fi jq -e --arg tag "${expected_tag}" --arg mode "${receipt_mode}" \ - --arg event "${SOURCE_EVENT}" --arg head "${SOURCE_HEAD_SHA}" \ --argjson id "${SOURCE_RUN_ID}" --argjson attempt "${SOURCE_RUN_ATTEMPT}" ' def positive_integer: type == "number" and . == floor and . > 0; .schema_version == "ocr-toolkit.release-receipt/v2" and .tag == $tag and .version == ($tag | ltrimstr("v")) and (.reviewed.merge | type == "string" and test("^[0-9a-f]{40}$")) and .github.annotated_tag_target == .reviewed.merge and - ($event != "pull_request" or .reviewed.head == $head) and (.workflow.run_id | positive_integer) and (.workflow.run_attempt | positive_integer) and (if $mode == "created" then .workflow.run_id == $id and .workflow.run_attempt == $attempt - elif .workflow.run_id == $id then - .workflow.run_attempt <= $attempt else - $event == "workflow_dispatch" + .workflow.run_id != $id or .workflow.run_attempt <= $attempt end) ' "${RUNNER_TEMP}/release-receipt.json" >/dev/null diff --git a/changelog.d/364.maintenance.md b/changelog.d/364.maintenance.md new file mode 100644 index 00000000..2e220ac5 --- /dev/null +++ b/changelog.d/364.maintenance.md @@ -0,0 +1 @@ +Start stable publication on protected main and verify historical rebuilds against the original source attestations before registry upload. Group scheduled minor and patch runtime dependency updates on dev. Skip advisory macOS jobs on internal documentation-only PRs and direct dev-to-main promotions. diff --git a/docs/codex/TASKS_BACKLOG.md b/docs/codex/TASKS_BACKLOG.md index 725b0cd5..7f71e16c 100644 --- a/docs/codex/TASKS_BACKLOG.md +++ b/docs/codex/TASKS_BACKLOG.md @@ -136,3 +136,13 @@ The [signal-ownership audit](../engineering/review_signal_ownership.md) remains - **Exclusions:** Learned online routing, per-tool models, multiple agents, or silent policy changes. - **Validation:** Offline replay, adversarial boundaries, fallback tests, and quality thresholds. - **Release classification expectation:** `release-required`. + +## Maintainer CI + +### BL-026: Avoid redundant PR validations without replacing required checks + +- **Status:** planned +- **Activation trigger:** A hosted test repository can reproduce this project's required Actions and CodeQL app checks on protected branches. +- **Evidence:** A description edit on #361 cancelled checks and started a second validation of the same synthetic merge commit. During promotion, eight CI runs on Dependabot #346–349 used a combined 13,122 job-seconds on allocated runners. Four runs were created shortly after automatic closure and ran 22 test jobs to success. In #363 the macOS Python 3.12 runner waited 14m40s before starting. [Original validation](https://github.com/xeonvs/open-code-review-toolkit/actions/runs/46740538729) · [Replacement validation](https://github.com/xeonvs/open-code-review-toolkit/actions/runs/46740601948) · [Release CI](https://github.com/xeonvs/open-code-review-toolkit/actions/runs/46746189464) +- **Next safe action:** Measure runner queue and execution time separately across releases. Finalize PR descriptions before marking a PR ready. For later status updates, use PR comments. Evaluate metadata-only edits and already-closed Dependabot work in an isolated hosted repository. +- **Acceptance:** An edit to the title or body alone neither cancels work on the same revision nor emits a passing or skipped required check in place of a pending or failed one. Recheck the exact head, base and test-merge revisions on retarget, synchronization, draft/ready transitions, or ambiguous events. Verify merge eligibility for forks and repository-owned PRs with the actual required app identities. Preserve independent platform, secret, provenance and registry-install checks. diff --git a/docs/contributor-intake.md b/docs/contributor-intake.md index 7bc0490a..4930014c 100644 --- a/docs/contributor-intake.md +++ b/docs/contributor-intake.md @@ -12,4 +12,16 @@ 2. Review the full diff at those revisions before approving fork CI. Check workflow and executable changes, dependency and lockfile sources, installation and container inputs, Action pins and OCR qualification integrity values. Review additions and removals and both paths of renames and copies. Confirm a human updater's maintainer role in GitHub's repository access settings. For Dependabot updates to `dev`, verify the configured bot account, repository-owned branch and GitHub-verified commits through the reviewed head. Treat labels and branch names as context. Have a maintainer prepare dependency changes requested by an outside contributor. [Dependency audit and upstream review](development.md#dependency-audit-before-push) 3. Mark the PR ready and verify the full applicable protected CI ran and passed for the live base and head. Repeat review and checks when either revision changes. The maintainer verifies the author, source, target and revisions immediately before manual merge. Require an independent approval and dismiss stale approvals when there are two eligible maintainers. With a sole maintainer, record the exact revision reviewed and retain protected PR checks for maintainer-authored work. Squash eligible fork changes into `dev` with contributor attribution. For a CLI squash merge, supply the reviewed head with `gh pr merge "$PR_NUMBER" --squash --match-head-commit "$REVIEWED_HEAD"`. Whenever current main is no longer an ancestor of dev, including after a squash promotion or stable release, create a maintainer sync branch at the current `dev` tip, merge current `main` into it with a signed merge, and open a PR back to `dev`. Use a merge commit to preserve ancestry. Check that the current `main` tip is an ancestor of `dev` before the next promotion. [GitHub CLI merge options](https://cli.github.com/manual/gh_pr_merge) -Dependabot's `target-branch: dev` applies to scheduled version updates. GitHub opens security update PRs against the default branch. Retarget those to `dev` for review or prepare the fix there on a maintainer branch. [Dependabot target-branch behavior](https://docs.github.com/en/code-security/reference/supply-chain-security/dependabot-options-reference#target-branch) +Dependabot groups scheduled runtime minor and patch updates into one PR to `dev`. Review the lockfile changes for each package. GitHub opens security update PRs against the default branch. Retarget those to `dev` for review or prepare the fix there on a maintainer branch. [Dependabot target-branch behavior](https://docs.github.com/en/code-security/reference/supply-chain-security/dependabot-options-reference#target-branch) + +### Reconcile superseded Dependabot PRs before promotion + +Before merging a protected development promotion, list open Dependabot PRs targeting its base. This covers older version-update PRs that still target `main`. + +```sh +gh pr list --state open --base main --author app/dependabot --json number,title,headRefName,headRefOid +``` + +For a scheduled version update already incorporated in the reviewed promotion, compare the complete proposed dependency and lockfile or Action-pin diff, including transitive changes. If every change is accounted for, record the promotion PR and close the superseded bot PR before moving the base. Keep outstanding changes and security updates open until the target contains their fix. + +Check for queued or in-progress PR runs on the bot branch after closure. A queued event can create a run after the PR closes. Before cancelling an individual run, re-read the PR state and verify its closed, unmerged head, source repository and branch against the run. Limit cancellation to superseded pull-request validation runs in the same repository and confirm no open PR still uses that branch and revision. Use the run ID for cancellation and read back its terminal state. Ordinary dependency PRs continue through the usual required checks. diff --git a/docs/development.md b/docs/development.md index 96e33f7a..db082db4 100644 --- a/docs/development.md +++ b/docs/development.md @@ -30,16 +30,22 @@ A high combined result cannot hide a weak group. Individual DLP/audit, source syntax, shared credential material/completion, diagram-source metadata and orientation owners have 90% floors in the local and hosted coverage gates. Structural evidence sizing, bounded store serialization and optional target admission each have an independent 90% floor. -Ready hosted pull requests run source and contract -tests on all six supported OS/Python combinations. The expensive +Ready product pull requests and manual CI runs cover all six supported +OS/Python combinations. The expensive clean-install wheel/sdist behavioral test runs once in the required Ubuntu/Python 3.12 job; the separate required build job smoke-tests both distribution paths. -The five matrix jobs start alongside Python 3.12 rather than waiting for it. -Each of the four Linux jobs can fail the CI workflow, with Ubuntu on Python -3.14 as the sole coverage owner. Effective branch rules determine which -individual checks GitHub requires before merge. The two macOS endpoint jobs are best-effort compatibility -diagnostics: they remain visible for follow-up, but a platform-only failure does -not block a Linux-priority release. Bandit scans only the supported runtime package +The matrix starts alongside Ubuntu/Python 3.12. All four Linux check identities +remain available to the branch rules, with Ubuntu/Python 3.14 as the sole +coverage owner. CI omits the two advisory macOS jobs for positively classified +same-repository documentation-only pull requests and direct promotions from +`dev` to `main`. Direct promotions still run the Linux tests and coverage. +Manual runs, release-preparation pull requests, fork pull requests and uncertain +classifications retain the full matrix. Once required checks pass for the verified head and base, +an advisory job waiting for a runner can finish independently. Use a manual CI +run to check macOS on a deferred change. +Inspect any reported product regression before promotion. Report runner capacity +separately from test failures and retry only the affected job when appropriate. +Bandit scans only the supported runtime package at medium-or-higher severity and confidence; tests and synthetic fixtures are outside that bounded gate. diff --git a/docs/release.md b/docs/release.md index a24d4ce7..cbac5fc5 100644 --- a/docs/release.md +++ b/docs/release.md @@ -27,12 +27,12 @@ The delivery sequence is: 2. merge the protected feature pull request to `main`; 3. verify the deterministic `.devN` wheel and sdist on TestPyPI; 4. prepare and merge a protected signed `release/vX.Y.Z` pull request; -5. monitor stable TestPyPI and PyPI publication, annotated tag, provenance, attestations, and immutable GitHub Release; +5. start the Release workflow on protected `main` for the reviewed squash and monitor stable TestPyPI and PyPI publication, annotated tag, provenance, attestations, and immutable GitHub Release; 6. require the release CI jobs to independently compare artifact hashes and smoke-install every supported Python boundary; 7. require CI readback of the immutable `release-receipt.json`, then close the tracked issues and milestone; 8. independently read back the exact external state against the immutable receipt and issue comments, then close the delivery objective without another repository pull request. -The release pull request is the final repository mutation before stable publication. It owns stable and next version markers, deterministic source epoch, tracked authorization metadata, generated Towncrier changelog, release notes, and reconciliation of the plan and status documents. Follow the checked [plan archive and external reconciliation](#external-reconciliation-and-plan-archiving) below. `.release-reconciled-version` is historical evidence for releases that used a post-publication repository closure PR; it does not advance for plans closed in the release PR. Current validation uses the archived plan, stable index and immutable external receipts instead. The release PR must not claim that registry files, provenance, tag, immutable Release, receipt, or installs already exist. The protected-main merge may run the normal TestPyPI development workflow described below; verify its workflow outcome, but do not treat that development build as another stable release or repeat stable artifact readback. +The release pull request fixes the final source tree for stable publication. An explicitly authorized protected workflow repair can advance `main` before a historical recovery. The release PR owns stable and next version markers, deterministic source epoch, tracked authorization metadata, generated Towncrier changelog, release notes, and reconciliation of the plan and status documents. Follow the checked [plan archive and external reconciliation](#external-reconciliation-and-plan-archiving) below. `.release-reconciled-version` is historical evidence for releases that used a post-publication repository closure PR; it does not advance for plans closed in the release PR. Current validation uses the archived plan, stable index and immutable external receipts instead. The release PR must not claim that registry files, provenance, tag, immutable Release, receipt, or installs already exist. The protected-main merge may run the normal TestPyPI development workflow described below; verify its workflow outcome, but do not treat that development build as another stable release or repeat stable artifact readback. List tracked release issues in a release PR as bare references or ordinary non-closing prose. Do not use GitHub closing-keyword forms such as `close`, `closes`, `closed`, `fix`, `fixes`, `fixed`, `resolve`, or `resolves` together with those issue references: merging such a PR can close the issues before the immutable receipt exists. The Release workflow is the sole closure owner, and acts only after its post-publication receipt readback. @@ -87,9 +87,17 @@ are inputs to the release contracts, not bookkeeping covered by an earlier run. Other changed release boundaries add their own tests; this set does not replace the final quality gate or protected CI. -Squash-merging that exact repository-owned release PR is the only human publication gate. The **Release** workflow then: +Squash-merging the exact repository-owned release PR authorizes publication. Start the Release workflow once on protected `main` using the reviewed identities, preferably before advancing the branch again. -1. validates the branch, title, tracked metadata, reviewed head/base, exact required checks, squash-tree equivalence, merge parent, canonical version, and tracked build epoch; +```sh +gh workflow run release.yml --ref main \ + -f pull-request-number="$PR_NUMBER" -f version="$VERSION" \ + -f merge-commit="$MERGE_SHA" -f reviewed-head="$HEAD_SHA" -f reviewed-base="$BASE_SHA" +``` + +The **Release** workflow performs these steps. + +1. It validates the branch, title, tracked metadata, reviewed head/base, exact required checks, squash-tree equivalence, merge parent, canonical version, and tracked build epoch; 2. relies on successful required PR quality/build checks bound to the exact reviewed tree, then runs release dependency, packaging, and artifact-set checks; 3. builds wheel and sdist once, records SHA-256 values, and creates GitHub provenance attestations; 4. publishes or exact-hash-verifies the same bytes on TestPyPI through OIDC; @@ -131,7 +139,10 @@ After publication, independently verify the immutable release, workflow, tag, re Recovery dispatch is bound to the original release PR, version, merge commit, reviewed head, and protected reviewed base. Before loading the historical authorizer, the workflow confirms that the squash merge is on the first-parent -history of the exact `main` commit that started the dispatch. Recovery +history of the exact `main` commit that started the dispatch. If main has advanced, +the rebuilt wheel, sdist and runtime lock must each match an existing GitHub-hosted +release workflow attestation for the original squash on main before either +registry can receive files. Recovery evaluates the current effective `main` rules against the original reviewed head. Reconcile outstanding releases before adding new required check contexts, since the original reviewed head must still satisfy those checks. @@ -139,8 +150,7 @@ contexts, since the original reviewed head must still satisfy those checks. Recovery accepts only exact registry bytes and the existing immutable receipt's closed release identity, and rejects unknown receipt fields. When a prior dispatch created the receipt, resume through a new recovery dispatch -from `main`. A PR-triggered rerun can resume a receipt created by its own -workflow run. Draft +from `main`. Draft GitHub Releases are retained and addressed by their numeric release ID until publication because tag lookup does not expose private drafts reliably. Every numeric-ID read, asset upload, and publication step revalidates the expected diff --git a/tests/test_docs_only_ci.py b/tests/test_docs_only_ci.py index 4ed733c0..01adc792 100644 --- a/tests/test_docs_only_ci.py +++ b/tests/test_docs_only_ci.py @@ -588,8 +588,85 @@ def test_pr_cannot_replace_trusted_classifier(tmp_path: Path) -> None: **os.environ, "BASE": base, "HEAD": _git(tmp_path, "rev-parse", "HEAD"), + "BASE_REF": "dev", + "HEAD_REF": "topic", + "HEAD_REPO": "owner/toolkit", + "GITHUB_REPOSITORY": "owner/toolkit", "RUNNER_TEMP": str(tmp_path), "GITHUB_OUTPUT": str(output), } subprocess.run(["bash", "-e", "-c", classifier], cwd=tmp_path, env=environment, check=True) - assert output.read_text() == "docs_only=false\n" + assert output.read_text() == "docs_only=false\nskip_macos=false\n" + + +@pytest.mark.parametrize( + ("path", "target", "source", "same_repo", "uncertainty", "docs", "skipped"), + [ + ("README.md", "dev", "topic", True, "", True, True), + ("README.md", "dev", "topic", False, "", True, False), + ("runtime.py", "dev", "topic", True, "", False, False), + ("runtime.py", "main", "dev", True, "", False, True), + ("runtime.py", "main", "dev", False, "", False, False), + ("runtime.py", "dev", "dev", True, "", False, False), + (".release-version", "main", "release/v1.2.3", True, "", False, False), + ("runtime.py", "main", "dev", True, "missing-script", False, False), + ("runtime.py", "main", "dev", True, "script-exit", False, False), + ("runtime.py", "main", "dev", True, "unknown-output", False, False), + ("runtime.py", "main", "dev", True, "missing-head", False, False), + ("runtime.py", "main", "dev", True, "empty-delta", False, False), + ], +) +def test_advisory_runner_skip_requires_positive_same_repository_evidence( + tmp_path: Path, + path: str, + target: str, + source: str, + same_repo: bool, + uncertainty: str, + docs: bool, + skipped: bool, +) -> None: + _git(tmp_path, "init", "-q") + _git(tmp_path, "config", "user.email", "test@example.invalid") + _git(tmp_path, "config", "user.name", "Test") + script = tmp_path / "scripts" / "docs_only.py" + script.parent.mkdir() + if uncertainty != "missing-script": + code = { + "script-exit": "raise SystemExit(2)\n", + "unknown-output": 'print("docs_only=false\\nskip_macos=true")\n', + }.get(uncertainty, SCRIPT.read_text()) + script.write_text(code) + _git(tmp_path, "add", ".") + _git(tmp_path, "commit", "--allow-empty", "-qm", "base") + base = _git(tmp_path, "rev-parse", "HEAD") + if uncertainty != "empty-delta": + (tmp_path / path).write_text("changed\n") + _git(tmp_path, "add", path) + _git(tmp_path, "commit", "--allow-empty", "-qm", "head") + head = "0" * 40 if uncertainty == "missing-head" else _git(tmp_path, "rev-parse", "HEAD") + workflow = yaml.safe_load((ROOT / ".github/workflows/ci.yml").read_text()) + classifier = workflow["jobs"]["classify"]["steps"][-1] + output = tmp_path / "github-output" + subprocess.run( + ["bash", "-e", "-c", classifier["run"]], + cwd=tmp_path, + env={ + **os.environ, + "BASE": base, + "HEAD": head, + "BASE_REF": target, + "HEAD_REF": source, + "HEAD_REPO": "owner/toolkit" if same_repo else "contributor/toolkit", + "GITHUB_REPOSITORY": "owner/toolkit", + "RUNNER_TEMP": str(tmp_path), + "GITHUB_OUTPUT": str(output), + }, + capture_output=True, + check=True, + timeout=15, + ) + assert output.read_text().splitlines() == [ + f"docs_only={str(docs).lower()}", + f"skip_macos={str(skipped).lower()}", + ] diff --git a/tests/test_quality_script.py b/tests/test_quality_script.py index 5ab11996..affb4ac4 100644 --- a/tests/test_quality_script.py +++ b/tests/test_quality_script.py @@ -47,9 +47,6 @@ def test_quality_script_enforces_combined_and_boundary_coverage(tmp_path: Path) "uv run --no-sync pytest --ignore=tests/test_installed_policy_e2e.py --cov=ocr_toolkit --cov-report=term-missing --cov-fail-under=88" in workflow ) - assert workflow.count("coverage: true") == 1 - assert "if: ${{ needs.classify.outputs.docs_only != 'true' && matrix.coverage }}" in workflow - assert "if: ${{ needs.classify.outputs.docs_only != 'true' && !matrix.coverage }}" in workflow assert ( "for audit_module in cli corpus scanner state limits worker_process report proof; do" in script @@ -101,6 +98,16 @@ def declared_modules(text: str) -> list[str]: steps = yaml.safe_load(workflow)["jobs"]["test-matrix"]["steps"] coverage_steps = [s for s in steps if s.get("name") == "Test with boundary coverage gates"] assert len(coverage_steps) == 1 + coverage_if = ( + "${{ needs.classify.outputs.docs_only != 'true' && " + "matrix.os == 'ubuntu-latest' && matrix.python == '3.14' }}" + ) + assert coverage_steps[0]["if"] == coverage_if + assert next(step["if"] for step in steps if step.get("id") == "native-ocr") == coverage_if + assert next(step["if"] for step in steps if step.get("name") == "Test") == ( + "${{ needs.classify.outputs.docs_only != 'true' && " + "(matrix.os != 'ubuntu-latest' || matrix.python != '3.14') }}" + ) hosted = subprocess.run( ["sh", "-eu", "-c", coverage_steps[0]["run"]], cwd=PROJECT_ROOT, diff --git a/tests/test_release_authorization.py b/tests/test_release_authorization.py index 17f8d5d1..ae66274c 100644 --- a/tests/test_release_authorization.py +++ b/tests/test_release_authorization.py @@ -333,33 +333,67 @@ def test_required_check_and_ruleset_synchronization_are_exact() -> None: authorize(protection=protection) -def test_release_workflow_classifies_ordinary_merges_before_authorization() -> None: - workflow = WORKFLOW.read_text(encoding="utf-8") +def test_release_workflow_accepts_only_main_dispatches_with_explicit_identities() -> None: + workflow = yaml.load(WORKFLOW.read_text(encoding="utf-8"), Loader=yaml.BaseLoader) + assert set(workflow["on"]) == {"workflow_dispatch"} + inputs = workflow["on"]["workflow_dispatch"]["inputs"] + assert {name: (field["required"], field["type"]) for name, field in inputs.items()} == { + "pull-request-number": ("true", "number"), + "version": ("true", "string"), + "merge-commit": ("true", "string"), + "reviewed-head": ("true", "string"), + "reviewed-base": ("true", "string"), + } - assert "name: classify-release-trigger" in workflow - assert '[[ "${PR_HEAD_REF}" == release/v* ]]' in workflow - assert "needs: classify" in workflow - assert "needs.classify.outputs.release == 'true'" in workflow + jobs = workflow["jobs"] + assert {name for name, job in jobs.items() if "needs" not in job} == {"authorize"} + gate = jobs["authorize"]["if"] + assert gate == ( + "github.event_name == 'workflow_dispatch' && github.event.repository.private == false && " + "github.ref == 'refs/heads/main'" + ) + concurrency = workflow["concurrency"] + assert " ".join(concurrency["group"].split()) == ( + f"${{{{ {gate} && 'production-release' || format('release-ignored-{{0}}', github.run_id) }}}}" + ) + assert concurrency["cancel-in-progress"] == "false" + assert jobs["build"]["needs"] == "authorize" + assert jobs["build"]["if"] == "needs.authorize.outputs.approved == 'true'" + for publisher in ("publish-testpypi", "publish-pypi", "github-release"): + assert "github.ref == 'refs/heads/main'" in jobs[publisher]["if"] @pytest.mark.parametrize( - "scenario", ["matched", "wrong_base", "wrong_parent", "fork", "retired", "side_parent"] + "scenario", + [ + "matched", + "current", + "wrong_ref", + "wrong_base", + "wrong_parent", + "missing_merge", + "fork", + "retired", + "side_parent", + ], ) -def test_manual_recovery_verifies_protected_policy_before_checkout( - tmp_path: Path, scenario: str -) -> None: +def test_dispatch_verifies_protected_policy_before_checkout(tmp_path: Path, scenario: str) -> None: job = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))["jobs"]["authorize"] assert "github.ref == 'refs/heads/main'" in job["if"] trusted_checkout, gate, checkout = job["steps"][:3] - assert trusted_checkout["if"] == "github.event_name == 'workflow_dispatch'" + assert "if" not in trusted_checkout assert trusted_checkout["with"] == { "ref": "${{ github.sha }}", "path": "dispatch-main", "fetch-depth": 0, "persist-credentials": False, } - assert gate["if"] == "github.event_name == 'workflow_dispatch'" + assert "if" not in gate assert checkout["uses"].startswith("actions/checkout@") + assert checkout["with"] == { + "ref": "${{ inputs['reviewed-base'] }}", + "persist-credentials": False, + } history = tmp_path / "dispatch-main" history.mkdir() @@ -376,7 +410,8 @@ def git(*args: str) -> str: merge = git("rev-parse", "HEAD") if scenario in {"retired", "side_parent"}: git("switch", "-qc", "restored-main", base) - git("commit", "--allow-empty", "-qm", "current policy") + if scenario != "current": + git("commit", "--allow-empty", "-qm", "current policy") if scenario == "side_parent": git("merge", "--no-ff", "-qm", "merge old history as a side parent", merge) git("merge-base", "--is-ancestor", merge, "HEAD") @@ -387,6 +422,8 @@ def git(*args: str) -> str: pr["base"]["repo"] = {"full_name": repository} pr["base"]["sha"] = base pr["merge_commit_sha"] = merge + if scenario == "missing_merge": + del pr["merge_commit_sha"] if scenario == "fork": pr["head"]["repo"]["full_name"] = "fork/open-code-review-toolkit" parent = dispatch_sha if scenario == "wrong_parent" else base @@ -401,8 +438,16 @@ def git(*args: str) -> str: "esac\n" "for url do :; done\n" 'case "$url" in\n' - ' "https://api.github.com/repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER") cat pr.json ;;\n' - ' "https://api.github.com/repos/$GITHUB_REPOSITORY/git/commits/$MERGE") cat merge.json ;;\n' + ' "https://api.github.com/repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")\n' + ' case " $* " in\n' + ' *" X-GitHub-Api-Version: 2022-11-28 "*) cat pr.json ;;\n' + " *) jq 'del(.merge_commit_sha)' pr.json ;;\n" + " esac ;;\n" + ' "https://api.github.com/repos/$GITHUB_REPOSITORY/git/commits/$MERGE")\n' + ' case " $* " in\n' + ' *" X-GitHub-Api-Version: 2026-03-10 "*) cat merge.json ;;\n' + " *) exit 1 ;;\n" + " esac ;;\n" " *) exit 1 ;;\n" "esac\n" ) @@ -411,6 +456,7 @@ def git(*args: str) -> str: **os.environ, "PATH": f"{tmp_path}{os.pathsep}{os.environ['PATH']}", "GITHUB_REPOSITORY": repository, + "GITHUB_REF": "refs/heads/Main" if scenario == "wrong_ref" else "refs/heads/main", "GITHUB_SHA": dispatch_sha, "GH_TOKEN": "synthetic-token", "PR_NUMBER": "5", @@ -428,17 +474,26 @@ def git(*args: str) -> str: timeout=10, check=False, ) - assert (completed.returncode == 0) is (scenario == "matched"), completed.stderr + assert (completed.returncode == 0) is (scenario in {"matched", "current"}), completed.stderr if scenario in {"retired", "side_parent"}: assert "outside the dispatch main first-parent history" in completed.stderr + elif scenario == "wrong_ref": + assert "release dispatch must run from refs/heads/main" in completed.stderr + elif scenario in {"wrong_base", "fork", "missing_merge"}: + assert "release pull request does not match the requested identities" in completed.stderr + elif scenario == "wrong_parent": + assert "release merge is not a squash of the requested protected base" in completed.stderr def test_release_workflow_keeps_strict_release_authorization() -> None: workflow = WORKFLOW.read_text(encoding="utf-8") assert "python scripts/release_authorization.py" in workflow - assert "github.event.pull_request.base.sha || inputs['reviewed-base']" in workflow assert "Candidate head and merge commits are inspected only as data" in workflow + assert ( + "GITHUB_API_VERSION=2022-11-28 scripts/bounded_github_api.sh \\\n" + ' "repos/${REPOSITORY}/pulls/${PR_NUMBER}" /tmp/release-pr.json' + ) in workflow assert 'test "${RELEASE_BRANCH}" = "release/v${VERSION}"' in workflow assert "repos/${REPOSITORY}/rules/branches/main" in workflow assert "commits/${HEAD_SHA}/check-runs?filter=latest&per_page=100" in workflow @@ -460,7 +515,6 @@ def test_release_workflow_keeps_strict_release_authorization() -> None: assert "--validate-issue-only" in workflow assert 'test "$(git rev-parse HEAD^{tree})" = "${EXPECTED_TREE}"' in workflow assert 'test "$(git rev-parse FETCH_HEAD^{tree})" = "${EXPECTED_TREE}"' in workflow - assert "github.event.pull_request.merged == true" not in workflow def test_bounded_github_helper_rejects_unknown_endpoints_and_writes_atomically( diff --git a/tests/test_release_receipt.py b/tests/test_release_receipt.py index 6352bf9f..95ebe52c 100644 --- a/tests/test_release_receipt.py +++ b/tests/test_release_receipt.py @@ -158,6 +158,68 @@ def test_release_matrix_payload_reads_authorized_checkout_including_historical_b assert json.loads(completed.stdout.removeprefix("python-minors=")) == expected +@pytest.mark.parametrize("reject_sdist", [False, True]) +def test_historical_dispatch_verifies_original_artifacts_before_registry_work( + tmp_path: Path, reject_sdist: bool +) -> None: + import subprocess + + import yaml + + steps = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))["jobs"]["build"]["steps"] + verify = next( + step + for step in steps + if step.get("name") == "Verify original source attestations before publication" + ) + classify = next(step for step in steps if step.get("id") == "registry") + attest = next( + step + for step in steps + if step.get("uses", "").startswith("actions/attest-build-provenance@") + ) + assert steps.index(verify) < steps.index(classify) + assert verify["if"] == "github.sha != needs.authorize.outputs.commit" + assert verify["env"]["EXPECTED_COMMIT"] == "${{ needs.authorize.outputs.commit }}" + assert attest["if"] == "github.sha == needs.authorize.outputs.commit" + + (tmp_path / "dist").mkdir() + files = ("dist/a.whl", "dist/b.tar.gz", "runtime-requirements.txt") + for path in files: + (tmp_path / path).touch() + gh = tmp_path / "gh" + gh.write_text( + '#!/bin/sh\nprintf "%s\\n" "$*" >> calls\n' + 'test "$REJECT_SDIST" != 1 || test "$3" != dist/b.tar.gz\n', + encoding="utf-8", + ) + gh.chmod(0o700) + repository = "example/open-code-review-toolkit" + merge = "c" * 40 + environment = { + **os.environ, + "PATH": f"{tmp_path}{os.pathsep}{os.environ['PATH']}", + "LC_ALL": "C", + "GITHUB_REPOSITORY": repository, + "EXPECTED_COMMIT": merge, + "REJECT_SDIST": str(int(reject_sdist)), + } + completed = subprocess.run( + ["bash", "-e", "-o", "pipefail", "-c", verify["run"]], + cwd=tmp_path, + env=environment, + timeout=10, + check=False, + ) + assert (completed.returncode != 0) is reject_sdist + assert (tmp_path / "calls").read_text(encoding="utf-8").splitlines() == [ + f"attestation verify {path} --repo {repository} " + f"--signer-workflow {repository}/.github/workflows/release.yml " + f"--source-digest {merge} --source-ref refs/heads/main --deny-self-hosted-runners" + for path in (files[:2] if reject_sdist else files) + ] + + def test_existing_receipt_recovery_ignores_new_run_but_rejects_delivery_drift() -> None: payload = build_receipt(run_id=555, run_attempt=3) receipt.validate_receipt( diff --git a/tests/test_site_release_notify.py b/tests/test_site_release_notify.py index f73bbfa4..5502ce40 100644 --- a/tests/test_site_release_notify.py +++ b/tests/test_site_release_notify.py @@ -22,7 +22,10 @@ def _verification_step() -> str: def test_site_dispatch_occurs_once_after_read_only_verification() -> None: - jobs = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))["jobs"] + workflow = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8")) + assert workflow[True]["workflow_run"]["branches"] == ["main"] + jobs = workflow["jobs"] + assert "workflow_dispatch" in jobs["verify"]["if"] steps = jobs["notify"]["steps"] assert "--method POST" not in _verification_step() assert "OCR_SITE_DISPATCH_TOKEN" not in str(jobs["verify"]) @@ -59,7 +62,7 @@ def test_site_dispatch_occurs_once_after_read_only_verification() -> None: (["success"], {"receipt_attempt": 3, "receipt_mode": "reused"}, 1, "", 1, False), ( ["success"], - {"receipt_run": 39784500000, "receipt_attempt": 1, "receipt_mode": "reused"}, + {"receipt_run": 39784500000, "receipt_attempt": 1}, 1, "", 1, @@ -87,7 +90,7 @@ def test_site_dispatch_occurs_once_after_read_only_verification() -> None: 1, False, ), - (["success"], {"reviewed_head": "3" * 40}, 1, "", 1, False), + (["success"], {"event": "pull_request", "branch": "release/v0.12.1"}, 1, "", 1, False), ], ) def test_release_job_readback_is_bounded_and_fail_closed( @@ -199,8 +202,8 @@ def test_release_job_readback_is_bounded_and_fail_closed( "SOURCE_RUN_ATTEMPT": str(run_attempt), "SOURCE_WORKFLOW_ID": "315030204", "SOURCE_HEAD_SHA": source_sha, - "SOURCE_EVENT": str(overrides.get("event", "pull_request")), - "SOURCE_HEAD_BRANCH": str(overrides.get("branch", "release/v0.12.1")), + "SOURCE_EVENT": str(overrides.get("event", "workflow_dispatch")), + "SOURCE_HEAD_BRANCH": str(overrides.get("branch", "main")), "RUNNER_TEMP": str(tmp_path), "GITHUB_OUTPUT": str(output), } diff --git a/tests/test_testpypi_preview.py b/tests/test_testpypi_preview.py index 44e39623..5980e852 100644 --- a/tests/test_testpypi_preview.py +++ b/tests/test_testpypi_preview.py @@ -3,11 +3,15 @@ from __future__ import annotations import importlib.util +import json +import re +from itertools import product from pathlib import Path from types import ModuleType from typing import Any import pytest +import yaml SCRIPT = Path(__file__).parents[1] / "scripts" / "testpypi_preview.py" PROJECT_ROOT = SCRIPT.parents[1] @@ -297,7 +301,8 @@ def test_production_release_verifies_reviewed_registry_artifacts() -> None: assert "release_id=$(jq -r .id" in workflow assert "release_is_draft=$(jq -r .draft" in workflow assert "invalid GitHub Release numeric identity" in workflow - assert workflow.count("timeout-minutes:") == 8 + jobs = yaml.safe_load(workflow)["jobs"] + assert all(0 < job["timeout-minutes"] <= 30 for job in jobs.values()) assert workflow.count("--max-filesize 10485760") >= 1 assert "--retry 3 --retry-delay 2 --retry-connrefused" in verifier assert "--connect-timeout 10 --max-time 120" in verifier @@ -345,31 +350,34 @@ def test_distribution_build_is_a_bounded_pull_request_gate() -> None: def test_ci_matrix_covers_supported_python_minors_and_os_boundaries() -> None: - """Keep Linux blocking and macOS visible but advisory at both endpoints.""" + """Keep all Linux identities and both advisory macOS endpoints in full runs.""" workflow = (PROJECT_ROOT / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8") + jobs = yaml.safe_load(workflow)["jobs"] + job = jobs["test-matrix"] + matrix = job["strategy"]["matrix"] assert " push:" not in workflow - assert "continue-on-error: ${{ matrix.advisory }}" in workflow - assert "test-python312:" in workflow - assert "|| 'test-ubuntu-latest-py3.12' }}" in workflow - assert " test-matrix:\n needs: classify" in workflow + assert job["continue-on-error"] == "${{ matrix.os == 'macos-latest' }}" + assert jobs["test-python312"]["name"].endswith("|| 'test-ubuntu-latest-py3.12' }}") + assert job["name"].endswith("|| format('test-{0}-py{1}', matrix.os, matrix.python) }}") + assert job["needs"] == "classify" assert workflow.count("--ignore=tests/test_installed_policy_e2e.py") == 2 assert "run: uv run --no-sync pytest -q\n" in workflow assert 'UV_PYTHON: "3.12"' in workflow assert "UV_PYTHON: ${{ matrix.python }}" in workflow assert "uv sync --locked --python 3.12" in workflow assert 'uv sync --locked --python "${{ matrix.python }}"' in workflow - assert workflow.count("advisory: false") == 3 - assert workflow.count("advisory: true") == 2 - assert workflow.count("os: ubuntu-latest") == 3 - assert workflow.count("os: macos-latest") == 2 - assert workflow.count('python: "3.12"') == 1 - assert workflow.count('python: "3.13"') == 1 - assert workflow.count('python: "3.14"') == 2 - assert workflow.count('python: "3.15"') == 1 - for unsupported in ("3.10", "3.11"): - assert f'python: "{unsupported}"' not in workflow + assert ( + "github.event_name == 'pull_request' && needs.classify.result == 'success' && " + "needs.classify.outputs.skip_macos == 'true' &&" + ) in matrix["os"] + selected, fallback = (json.loads(value) for value in re.findall(r"'(\[[^']*\])'", matrix["os"])) + excluded = {(row["os"], row["python"]) for row in matrix["exclude"]} + required = {("ubuntu-latest", version) for version in ("3.13", "3.14", "3.15")} + advisory = {("macos-latest", version) for version in ("3.12", "3.14")} + assert set(product(selected, matrix["python"])) - excluded == required + assert set(product(fallback, matrix["python"])) - excluded == required | advisory def test_required_dependency_review_runs_for_every_pull_request() -> None: From f765aee1b668f338fe47f45e7784f29f3f8a9772 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:16:27 +0100 Subject: [PATCH 4/4] Track remaining PR metadata validation work in issue 364 --- docs/codex/TASKS_BACKLOG.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/docs/codex/TASKS_BACKLOG.md b/docs/codex/TASKS_BACKLOG.md index 7f71e16c..725b0cd5 100644 --- a/docs/codex/TASKS_BACKLOG.md +++ b/docs/codex/TASKS_BACKLOG.md @@ -136,13 +136,3 @@ The [signal-ownership audit](../engineering/review_signal_ownership.md) remains - **Exclusions:** Learned online routing, per-tool models, multiple agents, or silent policy changes. - **Validation:** Offline replay, adversarial boundaries, fallback tests, and quality thresholds. - **Release classification expectation:** `release-required`. - -## Maintainer CI - -### BL-026: Avoid redundant PR validations without replacing required checks - -- **Status:** planned -- **Activation trigger:** A hosted test repository can reproduce this project's required Actions and CodeQL app checks on protected branches. -- **Evidence:** A description edit on #361 cancelled checks and started a second validation of the same synthetic merge commit. During promotion, eight CI runs on Dependabot #346–349 used a combined 13,122 job-seconds on allocated runners. Four runs were created shortly after automatic closure and ran 22 test jobs to success. In #363 the macOS Python 3.12 runner waited 14m40s before starting. [Original validation](https://github.com/xeonvs/open-code-review-toolkit/actions/runs/46740538729) · [Replacement validation](https://github.com/xeonvs/open-code-review-toolkit/actions/runs/46740601948) · [Release CI](https://github.com/xeonvs/open-code-review-toolkit/actions/runs/46746189464) -- **Next safe action:** Measure runner queue and execution time separately across releases. Finalize PR descriptions before marking a PR ready. For later status updates, use PR comments. Evaluate metadata-only edits and already-closed Dependabot work in an isolated hosted repository. -- **Acceptance:** An edit to the title or body alone neither cancels work on the same revision nor emits a passing or skipped required check in place of a pending or failed one. Recheck the exact head, base and test-merge revisions on retarget, synchronization, draft/ready transitions, or ambiguous events. Verify merge eligibility for forks and repository-owned PRs with the actual required app identities. Preserve independent platform, secret, provenance and registry-install checks.