From d598fd65c28fd58f0379ae6e0ad57e7d0083c960 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:09:39 +0100 Subject: [PATCH 01/25] Document issue-first contributions and conditional release credit --- .github/ISSUE_TEMPLATE/bug_report.yml | 2 +- .github/ISSUE_TEMPLATE/feature_request.yml | 3 + .github/PULL_REQUEST_TEMPLATE.md | 4 + CONTRIBUTING.md | 28 +++-- PLANS.md | 133 +++++++++++++++++++++ changelog.d/README.md | 4 +- docs/codex/ENGINEERING_WORKFLOW_STATE.yaml | 2 +- docs/development.md | 4 + docs/release.md | 2 + pyproject.toml | 5 + tests/test_release_notes.py | 1 + 11 files changed, 177 insertions(+), 11 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 9d943d8c..1b3e6d96 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. 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/CONTRIBUTING.md b/CONTRIBUTING.md index bdedd764..fd63ffca 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. +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..8256053f 100644 --- a/PLANS.md +++ b/PLANS.md @@ -1,5 +1,138 @@ # 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 | pending | +| REQ-003 | Qualify #351/#354 and implement #352–353 | WQ-03 | pending | +| REQ-004 | Review #346–350 and qualify #355 | WQ-04 | pending | +| REQ-005 | Document contribution rules and conditional release credit | WQ-02, WQ-05 | in_progress | +| REQ-006 | Deliver and reconcile 0.16.1 | WQ-06 | pending | + +### Explicit Non-Goals + +This implementation handoff ends at a maintainer-owned draft PR against the current protected main, before merge or publication. Keep the external #354 branch and its implementation separate while the contributor prepares the requested changes. + +### 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. WQ-02 must enforce updater identity from trusted server metadata (maintainer permission or genuine Dependabot app origin, repository and revision), 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 | Land maintainer-owned bootstrap on protected 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 dev protections, runnable Build/CodeQL on dev, and a required base-controlled source/target admission gate. Permit external forks only into dev, maintainer-owned dev promotion and authorized release branches into main. Account explicitly for maintenance bots and bootstrap. Test denial and intended paths before retargeting #354. Synchronize contribution guide and template with rollout. | REQ-002, REQ-005 | pending | +| 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 | pending | +| 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 | pending | +| 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 | pending | +| WQ-06 | Review assembled range, merge protected promotion, verify TestPyPI dev, prepare signed release/v0.16.1 PR, archive and reconcile per release guide. | REQ-006 | pending | + +### 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 the intake checks. 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. Main requires linear history and a current base; the repository currently disables merge commits. For repeated direct promotions, propose allowing merge commits at repository level while retaining main's squash/rebase restrictions and signed linear history. Permit a reviewed signed main-to-dev synchronization merge on dev 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. Gitleaks policy, version selector and required admission checks must come from trusted policy. 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 + +Use a fork PR to verify dev CI and actual runner permission banners, external-to-main denial, eligible dev promotion, changed-head reapproval, and dev exclusion from both registry environments. Check release authorization on its existing protected path. Bind the admission gate to policy an external workflow cannot override; a same-named check from any Actions workflow alone is insufficient. 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 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. Documentation contracts passed (43 tests). + +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 admission checks 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 + +WQ-02. Prepare the trusted bootstrap and explicit main-only environments, verify the site credential boundary and exercise both branch routes before enabling dev intake or retargeting #354. + +### Plan Fidelity Check + +REQ-001–006 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. Contributor instructions switch their target when dev admission is operational. 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/changelog.d/README.md b/changelog.d/README.md index 4a349e4f..9dff8f90 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 links the PR by number. Group multiple contributions from the same person in one acknowledgment. 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/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/development.md b/docs/development.md index 123977f7..4379dc47 100644 --- a/docs/development.md +++ b/docs/development.md @@ -653,4 +653,8 @@ Performance evidence must separate cold-start validation from steady-state reque ## Dependency Audit Before Push +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. + +Only a repository maintainer or the configured Dependabot integration submits changes to dependencies, sources, hashes, lockfiles and Action references. Review changes in executable installation and workflow paths as well as manifest filenames. Verify the upstream source, pinned object, permissions and combined lock resolution before merge. An external contributor can identify a needed change and link its evidence. Maintainers own the follow-up patch. A trusted author still goes through protected review and CI. + 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`. diff --git a/docs/release.md b/docs/release.md index 7d12ae97..49f91838 100644 --- a/docs/release.md +++ b/docs/release.md @@ -55,6 +55,8 @@ and exact resume action. ## Development builds +For external changes, the maintainer records release credit only after the contribution has been accepted into the release tree. Use the conditional Towncrier `Contributors` category and the public PR number. Verify the generated section once in the changelog and in the extracted GitHub Release body, before the final comparison link. + Every non-release push to protected `main` with a product or release-relevant change runs the **TestPyPI development build** workflow. A proved documentation-only or internal CI/test-only push skips that build; the closed development classifier accepts only explicitly allowed Markdown, workflow, classifier, and Python test paths in the exact GitHub push range from event.before to github.sha and fails into the artifact route on unknown evidence, renames, or product/package changes. The pull-request classifier remains narrower: only Markdown can skip full PR checks. The immutable workflow run number produces `.devN` (for example `0.3.0.devN` after the 0.2.0 release); rerunning the same run reuses the version and succeeds only when the already-published filenames and SHA-256 values match the reviewed artifacts. Source tests, coverage, security, CodeQL, dependency review, and the package smoke gate already bind the protected pull-request tree, so this main-push workflow does not repeat them. It owns the new boundary instead: TestPyPI Trusted Publishing, attestations, exact `testpypi.yml` PEP 740 publisher and subject verification, bounded HTTPS readback, and smoke-installation of the exact development wheel and sdist with `--no-deps` after installing the reviewed hash-locked binary runtime dependencies. Each environment runs `pip check` and real installed MCP/schema probes. Development builds never create tags or GitHub Releases and never publish to production PyPI. TestPyPI is public disclosure, so only reviewed pull requests may reach `main`. 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/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", } From d37c88dfd69c07343abcf65fe650001c4262de10 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:16:35 +0100 Subject: [PATCH 02/25] Qualify OCR 1.14.6 and verify the pinned GitLab runner image --- changelog.d/355.bugfix.md | 1 + changelog.d/355.maintenance.md | 1 + changelog.d/356.security.md | 1 + .../evidence/ocr-1.14.6-local-review.json | 31 ++ compatibility/evidence/ocr-1.14.6.json | 421 ++++++++++++++++++ compatibility/ocr-support.json | 61 ++- docs/compatibility.md | 13 +- docs/gitlab.md | 4 + docs/security.md | 8 + examples/gitlab/ocr-review.gitlab-ci.yml | 2 +- src/ocr_toolkit/_qualified_handoffs.json | 30 ++ .../evidence/gitlink_projection.py | 3 +- src/ocr_toolkit/preflight.py | 3 +- tests/test_environment_contract.py | 4 + tests/test_gitlinks.py | 44 +- tests/test_ocr_qualification_recovery.py | 3 +- 16 files changed, 612 insertions(+), 18 deletions(-) create mode 100644 changelog.d/355.bugfix.md create mode 100644 changelog.d/355.maintenance.md create mode 100644 changelog.d/356.security.md create mode 100644 compatibility/evidence/ocr-1.14.6-local-review.json create mode 100644 compatibility/evidence/ocr-1.14.6.json 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.security.md b/changelog.d/356.security.md new file mode 100644 index 00000000..8feab4ac --- /dev/null +++ b/changelog.d/356.security.md @@ -0,0 +1 @@ +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. 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/compatibility.md b/docs/compatibility.md index 15894ae3..a2acf0a0 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -24,8 +24,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 +36,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 +51,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 toolkit accepts that exclusion in mixed gitlink reviews, keeping ignored paths out of completed coverage. | 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,8 +65,8 @@ 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. diff --git a/docs/gitlab.md b/docs/gitlab.md index c46381e7..9a9d7e87 100644 --- a/docs/gitlab.md +++ b/docs/gitlab.md @@ -8,6 +8,10 @@ Install `open-code-review-toolkit` from PyPI and install Open Code Review separa 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. +Use a `linux/amd64` runner with the example. The job starts the official Python +image at a pinned Docker Hub manifest digest and installs the Linux amd64 OCR +binary. + ## Required configuration Behavior/Impact Analysis requires the wheel and qualified binary described in diff --git a/docs/security.md b/docs/security.md index e2f422ae..ec8a1128 100644 --- a/docs/security.md +++ b/docs/security.md @@ -77,6 +77,14 @@ The main trust transitions are: authority. Generated promotion outputs reject conflicting existing content before any pin is changed; exclusive creation protects new destinations. +### 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. 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/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/evidence/gitlink_projection.py b/src/ocr_toolkit/evidence/gitlink_projection.py index 4289124c..a15bbf58 100644 --- a/src/ocr_toolkit/evidence/gitlink_projection.py +++ b/src/ocr_toolkit/evidence/gitlink_projection.py @@ -42,6 +42,7 @@ "default_path", "secret_exclude", "provider_directory", + "gitignore", "deleted", "binary", "too_large", @@ -583,7 +584,7 @@ def verify_gitlink_projection(reader: GitRepositoryReader, projection: GitlinkPr def qualify_gitlink_preview(projection: GitlinkProjection, raw: bytes) -> tuple[RawDiffEntry, ...]: - """Accept only the complete 1.13.3 preview for the independently proven diff.""" + """Verify native preview records against the independently proven Git diff.""" try: payload = json.loads(raw) 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/tests/test_environment_contract.py b/tests/test_environment_contract.py index 553a7c0d..c14618d4 100644 --- a/tests/test_environment_contract.py +++ b/tests/test_environment_contract.py @@ -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_gitlinks.py b/tests/test_gitlinks.py index 345730a8..b7be1c5e 100644 --- a/tests/test_gitlinks.py +++ b/tests/test_gitlinks.py @@ -65,6 +65,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") @@ -158,7 +173,8 @@ 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 _preview(path: str = "main.php", *, reason: str = "") -> bytes: + selected = not reason item: dict[str, object] = { "path": path, "status": "modified", @@ -167,7 +183,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 +203,8 @@ 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")) == () @pytest.mark.parametrize( @@ -1068,7 +1085,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 +1161,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 +1234,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_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"] From 74acebab6ae79d36eb506cbb8785ebc019a012a7 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:29:11 +0100 Subject: [PATCH 03/25] Harden contributor intake and separate draft checks --- .github/ISSUE_TEMPLATE/bug_report.yml | 2 +- .github/dependabot.yml | 2 + .github/workflows/actions-maintenance.yml | 1 + .github/workflows/build.yml | 21 +- .github/workflows/ci.yml | 48 +- .github/workflows/codeql.yml | 19 +- .github/workflows/contributor-intake.yml | 63 +++ .github/workflows/dependency-review.yml | 6 +- .github/workflows/ocr-compatibility.yml | 46 +- .github/workflows/release.yml | 50 +- .github/workflows/scorecard.yml | 6 +- .github/workflows/security.yml | 77 ++- .github/workflows/site-release-notify.yml | 122 +++-- .github/workflows/testpypi.yml | 6 +- CONTRIBUTING.md | 2 +- PLANS.md | 26 +- changelog.d/346.maintenance.md | 1 + changelog.d/350.security.md | 1 + changelog.d/356.maintenance.md | 1 + changelog.d/README.md | 2 +- docs/README.md | 2 + docs/compatibility.md | 4 +- docs/contributor-intake.md | 33 ++ docs/development.md | 48 +- docs/gitlab.md | 2 +- docs/release.md | 21 +- scripts/contributor_intake.py | 602 ++++++++++++++++++++++ scripts/dependency-audit.sh | 2 +- tests/test_contributor_intake.py | 432 ++++++++++++++++ tests/test_dependency_workflow.py | 49 +- tests/test_docs_only_ci.py | 120 ++++- tests/test_integration_contracts.py | 8 +- tests/test_operations_docs.py | 9 +- tests/test_release_authorization.py | 64 +++ tests/test_site_release_notify.py | 144 +++++- tests/test_testpypi_preview.py | 4 +- uv.lock | 412 +++++++-------- 37 files changed, 2064 insertions(+), 394 deletions(-) create mode 100644 .github/workflows/contributor-intake.yml create mode 100644 changelog.d/346.maintenance.md create mode 100644 changelog.d/350.security.md create mode 100644 changelog.d/356.maintenance.md create mode 100644 docs/contributor-intake.md create mode 100644 scripts/contributor_intake.py create mode 100644 tests/test_contributor_intake.py diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 1b3e6d96..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: Search existing issues and PRs first. Use a minimal synthetic example. For a suspected vulnerability, use the private reporting link on the issue chooser. + 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/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..b927f71f 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,20 @@ 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: >- + ${{ 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' @@ -130,8 +149,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 +161,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..5ccf6ca1 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,8 +17,13 @@ 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 env: # CodeQL v4 controls overlay database caching separately from TRAP caching. @@ -30,8 +36,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/contributor-intake.yml b/.github/workflows/contributor-intake.yml new file mode 100644 index 00000000..08a30ca3 --- /dev/null +++ b/.github/workflows/contributor-intake.yml @@ -0,0 +1,63 @@ +name: Contributor intake policy + +on: + workflow_run: + workflows: [CI] + types: [completed] + workflow_dispatch: + inputs: + pull-request-number: + description: Open pull request number + required: true + type: string + target: + description: Exact protected base branch + required: true + type: choice + options: [dev, main] + base: + description: Full current base commit SHA + required: true + type: string + head: + description: Full reviewed head commit SHA + required: true + type: string + +permissions: + actions: read + contents: read + pull-requests: read + +concurrency: + group: intake-${{ github.event.workflow_run.head_sha || inputs.head }} + cancel-in-progress: false + +jobs: + evaluate: + name: Evaluate protected intake policy + if: >- + github.repository == 'xeonvs/open-code-review-toolkit' && github.ref == 'refs/heads/main' && + (github.event_name == 'workflow_dispatch' || + (github.event.workflow_run.workflow_id == 315030197 && github.event.workflow_run.event == 'pull_request')) + runs-on: ubuntu-latest + timeout-minutes: 5 + environment: contributor-intake + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 + id: publisher + if: vars.INTAKE_APP_CLIENT_ID != '' || vars.INTAKE_APP_ID != '' + with: + client-id: ${{ vars.INTAKE_APP_CLIENT_ID }} + private-key: ${{ secrets.INTAKE_APP_PRIVATE_KEY }} + permission-checks: write + - name: Evaluate GitHub metadata + env: + GH_TOKEN: ${{ github.token }} + INTAKE_APP_ID: ${{ vars.INTAKE_APP_ID }} + INTAKE_CHECK_TOKEN: ${{ steps.publisher.outputs.token }} + run: python3 scripts/contributor_intake.py diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml index 40a88fe6..a95838c5 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,13 @@ 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 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..c418ffaf 100644 --- a/.github/workflows/ocr-compatibility.yml +++ b/.github/workflows/ocr-compatibility.yml @@ -32,6 +32,7 @@ concurrency: jobs: discover: name: discover-stable-releases + if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest timeout-minutes: 5 outputs: @@ -121,10 +122,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 +184,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: @@ -246,40 +249,3 @@ 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' - env: - GH_TOKEN: ${{ secrets.OCR_UPDATE_BOT_TOKEN }} - REPOSITORY: ${{ github.repository }} - TARGET_VERSION: ${{ steps.chain.outputs.target }} - 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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 12aa0d57..f2a45a08 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,31 @@ jobs: tree: ${{ steps.authorize.outputs.tree }} version: ${{ steps.authorize.outputs.version }} steps: + - 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}$ ]] + gh api "repos/${GITHUB_REPOSITORY}/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 + gh api "repos/${GITHUB_REPOSITORY}/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 +228,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 +551,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 +643,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 +665,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}" \ @@ -785,3 +817,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..2cc8f085 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -18,7 +18,7 @@ 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 permissions: security-events: write # Upload Scorecard SARIF to code scanning. @@ -28,11 +28,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..121b624f 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,84 @@ 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 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) + 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" + test "$(git rev-parse FETCH_HEAD)" = "${PR_HEAD}" + 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 fd63ffca..568f6565 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,7 +5,7 @@ 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. 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. +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). diff --git a/PLANS.md b/PLANS.md index 8256053f..30b88fcc 100644 --- a/PLANS.md +++ b/PLANS.md @@ -26,10 +26,10 @@ Review the new contributor's entire repository history, fix incremental qualific | 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 | pending | -| REQ-003 | Qualify #351/#354 and implement #352–353 | WQ-03 | pending | -| REQ-004 | Review #346–350 and qualify #355 | WQ-04 | pending | -| REQ-005 | Document contribution rules and conditional release credit | WQ-02, WQ-05 | in_progress | +| REQ-002 | Protect dev intake and isolate privileged publication | WQ-02 | in_progress | +| REQ-003 | Qualify #351/#354 and implement #352–353 | WQ-03 | in_progress | +| 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 | pending | ### Explicit Non-Goals @@ -67,11 +67,11 @@ At b93ec7d the three changed files cover local opt-in qualification, its tests a | 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 | Land maintainer-owned bootstrap on protected 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 dev protections, runnable Build/CodeQL on dev, and a required base-controlled source/target admission gate. Permit external forks only into dev, maintainer-owned dev promotion and authorized release branches into main. Account explicitly for maintenance bots and bootstrap. Test denial and intended paths before retargeting #354. Synchronize contribution guide and template with rollout. | REQ-002, REQ-005 | pending | -| 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 | pending | -| 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 | pending | -| 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 | pending | -| WQ-06 | Review assembled range, merge protected promotion, verify TestPyPI dev, prepare signed release/v0.16.1 PR, archive and reconcile per release guide. | REQ-006 | pending | +| WQ-02 | Land maintainer-owned bootstrap on protected 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 dev protections, runnable Build/CodeQL on dev, and a required base-controlled source/target admission gate. Permit external forks only into dev, maintainer-owned dev promotion and authorized release branches into main. Account explicitly for maintenance bots and bootstrap. Test denial and intended 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 | in_progress | +| 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 the bootstrap draft and maintainer approval, 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 | ### Locked Decisions @@ -85,7 +85,7 @@ Fork validation uses GitHub-hosted pull_request jobs with SHA-pinned actions, re ### Verification -Use a fork PR to verify dev CI and actual runner permission banners, external-to-main denial, eligible dev promotion, changed-head reapproval, and dev exclusion from both registry environments. Check release authorization on its existing protected path. Bind the admission gate to policy an external workflow cannot override; a same-named check from any Actions workflow alone is insufficient. 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. +On a same-repository dev push and a dev-to-main promotion, verify effective job permissions and exclusion of publishing OIDC and site credentials from PR-controlled jobs. Use a fork PR to verify dev CI and actual runner permission banners, external-to-main denial, eligible dev promotion, changed-head reapproval, and dev exclusion from both registry environments. Check release authorization on its existing protected path. Bind the admission gate to policy an external workflow cannot override; a same-named check from any Actions workflow alone is insufficient. 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. @@ -93,7 +93,9 @@ For #351–353 exercise installed incremental review across successive heads, an 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 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. Documentation contracts passed (43 tests). +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 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. @@ -109,7 +111,7 @@ Protect dev before admitting any external code. A PR from dev in the same reposi ### Resume Point -WQ-02. Prepare the trusted bootstrap and explicit main-only environments, verify the site credential boundary and exercise both branch routes before enabling dev intake or retargeting #354. +Review the maintainer bootstrap draft. Before enabling dev intake or retargeting #354, restrict both registry environments to named main, migrate the site credential, configure protected intake and verify both branch routes using docs/contributor-intake.md. Recheck the contributor head and outstanding requests. ### Plan Fidelity Check 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/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/README.md b/changelog.d/README.md index 9dff8f90..983e9153 100644 --- a/changelog.d/README.md +++ b/changelog.d/README.md @@ -4,7 +4,7 @@ Every user-visible 0.x change needs one fragment named `..md`, wher 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 links the PR by number. Group multiple contributions from the same person in one acknowledgment. An empty category produces no heading. +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 links the PR by number. Group multiple contributions from the same person in one acknowledgment and link each additional accepted PR explicitly in its body. 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. 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/compatibility.md b/docs/compatibility.md index a2acf0a0..abea4bf5 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: @@ -209,7 +211,7 @@ 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 an automatic-safe result, 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 diff --git a/docs/contributor-intake.md b/docs/contributor-intake.md new file mode 100644 index 00000000..e1f35d24 --- /dev/null +++ b/docs/contributor-intake.md @@ -0,0 +1,33 @@ +# Protected contributor intake + +External pull requests target `dev` once the maintainer opens it for intake. The protected admission routes into `main` are maintainer promotion from repository-owned `dev` and a maintainer release PR from a repository-owned `release/vX.Y.Z` branch with the matching title. [Contributor guide](../CONTRIBUTING.md) · [Stable release authorization](release.md#stable-release) + +The **Contributor intake policy** workflow runs from protected `main` after the repository's PR CI completes, or through an exact-revision manual dispatch. The automatic path checks GitHub's numeric CI workflow identity, workflow path, run attempt and unique PR association. It compares the source repository and branch and both revision SHAs with current GitHub metadata. Candidate files enter the workflow only as REST data. Checkout and execution are limited to the trusted policy, and the optional publisher can write admission checks. This trigger works under GitHub's default public-repository event policy. [GitHub `workflow_run` behavior](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows#workflow_run) · [GitHub public-repository policy](https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target#default-policy-for-pull_request_target) + +GitHub's authenticated base-repository metadata establishes the owner of this user-owned repository. For other submitters on repository-owned branches, the read-only installation token queries GitHub's current `admin` or `maintain` role. If GitHub cannot supply those permissions, the collaborator route stays blocked until the lookup recovers or the verified owner prepares and submits the change. [GitHub App metadata permission](https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps#repository-permissions-for-metadata) + +## Dependency ownership + +Maintainers own dependency manifests and lockfiles, origins and integrity values, Actions and CI configuration, installer scripts, container sources and OCR qualification pins. A contributor can document a needed change and ask a maintainer to prepare the update. The gate checks both paths of a rename or copy, checks additions and removals, and checks changed lines for common installation, source and pin syntax outside the governed paths. Missing or incomplete comparison evidence requires a maintainer-owned revision. This file and text inspection supports a maintainer's review of the full diff and executable paths, including unfamiliar formats or dependencies assembled dynamically. [Dependency audit and upstream review](development.md#dependency-audit-before-push) + +The configured Dependabot app can submit its `uv` dependency updates and fixed-SHA updates to the existing GitHub Actions references on `dev`. The gate requires GitHub's authenticated Dependabot user ID, a repository-owned updater branch, and a complete linear chain of GitHub-verified Dependabot commits through the PR head. Where GitHub supplies an app ID on the PR, it must be Dependabot's. Labels, branch names and display text carry no independent authority. A bot update still receives the same maintainer review and applicable tests. + +Dependabot's `target-branch: dev` applies to scheduled version updates. GitHub opens Dependabot security updates against the default branch. The maintainer retargets a genuine security update to `dev` for review or prepares 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) + +## Configuration and activation + +1. Land the reviewed maintainer bootstrap through the existing protected `main` procedure before activating the admission rules. In repository Actions settings, require workflow approval for all outside collaborators, retain GitHub-hosted pull-request validation with read-only effective permissions, and turn off automatic merge for intake. Keep publisher credentials and deployment environments restricted to their trusted `main` triggers. [Actions approval 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) +2. Pre-create the `contributor-intake` environment with **Selected branches and tags**, a single branch rule for `main` and no tag rule. Confirm the effective deployment policy before adding any secret. Protect `dev` from force pushes and deletion and require the protected PR and CI rules on it before retargeting any contributor PR. Retain the protected-main signature and release rules. Require current CI for both branches and keep any emergency administrator bypass limited to audited PR recovery. +3. If enabling server-enforced check provenance, register a private dedicated GitHub App with **Checks: read and write** and its implicit **Metadata: read** only. Disable webhooks and install it on this repository alone. Add its numeric app ID as environment variable `INTAKE_APP_ID`, its client ID as environment variable `INTAKE_APP_CLIENT_ID`, and its private key as environment secret `INTAKE_APP_PRIVATE_KEY`. The workflow requests a short-lived repository-scoped token with `checks: write`. Give this app no ruleset bypass or merge capability. [GitHub App permissions](https://docs.github.com/en/apps/creating-github-apps/registering-a-github-app/choosing-permissions-for-a-github-app) +4. Observe the app publish `Trusted admission / dev` and `Trusted admission / main`. Configure the matching required check on each branch's ruleset with the dedicated app's numeric `integration_id`. Confirm GitHub's effective rules list the correct check and app on both refs. Keep the existing required checks on `main` as check runs so the stable release authorizer can read them on the exact head. If the applicable GitHub plan or repository settings cannot require a check from the app, the protected-main workflow remains advisory and a maintainer must enforce its result at merge time. A same-name GitHub Actions job provides no independent app identity. [Selecting the source of a required status check](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets#require-status-checks-to-pass-before-merging) +5. Before opening `dev` to contributors, verify an ordinary fork PR targeting `dev`, a fork PR changing a manifest or pin, a mislabeled bot attempt, an external PR targeting `main`, genuine Dependabot retargeted to `dev`, a maintainer update, and a repository `dev` promotion to `main`. Confirm a changed head or base needs fresh evidence, a draft remains ineligible, and Ready for review runs new full validation. For the app mode, check the app identity and attempt to satisfy the requirement with a same-named ordinary workflow in a controlled test. Confirm read-only tokens on fork validation and rejection of publication from `dev` before opening intake. Use the existing protected release contracts for the stable route. + +## Merging a reviewed PR + +Before merging, fetch the live PR and confirm the intended PR number, source repository and branch, target branch, base SHA and head SHA. On the newest **Contributor intake policy** run from `main`, or in the dedicated app's check details if configured, verify the recorded PR number, target, revision pair and current policy SHA. GitHub required checks are commit-scoped. The app binding proves who produced a check, while the maintainer verifies the admission record describes this specific PR. Use manual merge after this verification and maintainer review. [GitHub required-check commit resolution](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks#required-check-needs-to-succeed-against-the-latest-commit-sha) + +Review the changed head before approving its validation workflows. Confirm the PR is ready for review and inspect the workflow jobs to verify the full applicable protected CI ran and passed for the live base and head. If the base changed, run fresh checks against the new base. Recheck the revision pair before the actual merge. Stable publication follows the existing signed merge and release authorization process. + +GitHub may omit the PR association for fork CI. Missing, ambiguous or stale CI metadata calls for manual dispatch. Run **Contributor intake policy** from `main` with the open PR number, exact `main` or `dev` target, current full base SHA and reviewed full head SHA. Use a fresh dispatch after a base move or policy update and read the resulting decision for that exact revision. Retargeting, reopening and marking a PR ready start normal PR CI. The automatic intake runs when that CI completes. + +Squash-merge eligible fork changes into `dev` with contributor attribution. Promote the reviewed tree using a separate repository-owned `dev` PR into `main`. For a protected squash merge with the CLI, supply the reviewed head as `gh pr merge "$PR_NUMBER" --squash --match-head-commit "$REVIEWED_HEAD"` after confirming the live base. Protect the long-lived `dev` ref and keep it available for subsequent promotions. Enable merge commits for the `dev` synchronization route and retain linear history on `main`. Synchronize `main` back to `dev` after promotion or release through a reviewed signed merge so the next promotion includes the current `main` ancestry. [GitHub CLI merge options](https://cli.github.com/manual/gh_pr_merge) diff --git a/docs/development.md b/docs/development.md index 4379dc47..1afb03b0 100644 --- a/docs/development.md +++ b/docs/development.md @@ -30,28 +30,60 @@ 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. +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, run `scripts/gitleaks.sh --tree` and `scripts/gitleaks.sh`, +plus 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. The history mode scans the complete first-parent +feature history. 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 PR head, checks the event SHA, 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. Review changes to the hosted workflow before approving each +new external head. `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. @@ -655,6 +687,6 @@ Performance evidence must separate cold-start validation from steady-state reque 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. -Only a repository maintainer or the configured Dependabot integration submits changes to dependencies, sources, hashes, lockfiles and Action references. Review changes in executable installation and workflow paths as well as manifest filenames. Verify the upstream source, pinned object, permissions and combined lock resolution before merge. An external contributor can identify a needed change and link its evidence. Maintainers own the follow-up patch. A trusted author still goes through protected review and CI. +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.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, 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/gitlab.md b/docs/gitlab.md index 9a9d7e87..ebf8922f 100644 --- a/docs/gitlab.md +++ b/docs/gitlab.md @@ -8,7 +8,7 @@ Install `open-code-review-toolkit` from PyPI and install Open Code Review separa 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. -Use a `linux/amd64` runner with the example. The job starts the official Python +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. diff --git a/docs/release.md b/docs/release.md index 49f91838..f068b32f 100644 --- a/docs/release.md +++ b/docs/release.md @@ -55,8 +55,6 @@ and exact resume action. ## Development builds -For external changes, the maintainer records release credit only after the contribution has been accepted into the release tree. Use the conditional Towncrier `Contributors` category and the public PR number. Verify the generated section once in the changelog and in the extracted GitHub Release body, before the final comparison link. - Every non-release push to protected `main` with a product or release-relevant change runs the **TestPyPI development build** workflow. A proved documentation-only or internal CI/test-only push skips that build; the closed development classifier accepts only explicitly allowed Markdown, workflow, classifier, and Python test paths in the exact GitHub push range from event.before to github.sha and fails into the artifact route on unknown evidence, renames, or product/package changes. The pull-request classifier remains narrower: only Markdown can skip full PR checks. The immutable workflow run number produces `.devN` (for example `0.3.0.devN` after the 0.2.0 release); rerunning the same run reuses the version and succeeds only when the already-published filenames and SHA-256 values match the reviewed artifacts. Source tests, coverage, security, CodeQL, dependency review, and the package smoke gate already bind the protected pull-request tree, so this main-push workflow does not repeat them. It owns the new boundary instead: TestPyPI Trusted Publishing, attestations, exact `testpypi.yml` PEP 740 publisher and subject verification, bounded HTTPS readback, and smoke-installation of the exact development wheel and sdist with `--no-deps` after installing the reviewed hash-locked binary runtime dependencies. Each environment runs `pip check` and real installed MCP/schema probes. Development builds never create tags or GitHub Releases and never publish to production PyPI. TestPyPI is public disclosure, so only reviewed pull requests may reach `main`. @@ -66,6 +64,19 @@ 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. 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`. @@ -85,7 +96,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. @@ -98,7 +111,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. diff --git a/scripts/contributor_intake.py b/scripts/contributor_intake.py new file mode 100644 index 00000000..c71db396 --- /dev/null +++ b/scripts/contributor_intake.py @@ -0,0 +1,602 @@ +#!/usr/bin/env python3 +"""Evaluate contributor intake using bounded GitHub metadata and immutable diffs.""" + +from __future__ import annotations + +import json +import os +import re +import sys +import urllib.error +import urllib.parse +import urllib.request +from collections import Counter +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path, PurePosixPath +from typing import Any + +REPOSITORY = "xeonvs/open-code-review-toolkit" +REPOSITORY_ID = 1303814119 +API_URL = f"https://api.github.com/repos/{REPOSITORY}/" +CI_WORKFLOW_ID = 315030197 +CI_WORKFLOW_PATH = ".github/workflows/ci.yml" +MAX_RESPONSE_BYTES = 4_194_304 +MAX_COMPARE_FILES = 300 # GitHub truncates the compare result here. +MAX_BOT_COMMITS = 25 +DEPENDABOT = (49699333, "dependabot[bot]", "Bot") +DEPENDABOT_APP_ID = 29110 +GITHUB_WEB_FLOW = (19864447, "web-flow", "User") +SHA_RE = re.compile(r"[0-9a-f]{40}") +LOGIN_RE = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})") +RELEASE_REF_RE = re.compile(r"release/v([0-9]+\.[0-9]+\.[0-9]+)") +ACTION_PIN_RE = re.compile( + r"\s*(?:-\s+)?uses:\s+([\w.-]+/[\w.-]+(?:/[\w./-]+)?)@[0-9a-f]{40}(?:\s+#.*)?\s*" +) +SUPPLY_LINE_RE = re.compile( + r"(?:^\s*(?:-\s+)?(?:uses|image|include|index[-_]url|extra[-_]index[-_]url)\s*:" + r"|^\s*(?-i:FROM)\s+|(?:@|\b)sha256:[0-9a-f]{64}\b" + r"|\bgit\+https?://|\s@\s+https?://|/releases/download/" + r"|--(?:extra-)?index-url\b|--find-links\b|--(?:require-)?hash(?:es)?\b" + r"|\b(?:curl|wget|uvx|pipx)\s|\b(?:pip[0-9.]*|uv\s+pip|npm|pnpm|yarn|apt(?:-get)?|brew)" + r"\s+(?:install|add|ci|sync)\b|\buv\s+(?:sync|tool\s+install)\b" + r"|\b(?:docker|podman)\s+(?:pull|build)\b)", + re.IGNORECASE, +) +CONTROL_FILES = frozenset( + { + ".gitmodules", + ".python-version", + ".tool-versions", + "codeowners", + "pyproject.toml", + "setup.py", + "setup.cfg", + "pip.conf", + "pip.ini", + "pipfile", + "uv.toml", + "tox.ini", + "makefile", + "mise.toml", + "justfile", + "package.json", + "npm-shrinkwrap.json", + ".npmrc", + "gemfile", + "go.mod", + "go.sum", + "cargo.toml", + "composer.json", + "pom.xml", + "nuget.config", + "global.json", + "packages.config", + } +) + + +class IntakeError(ValueError): + """GitHub state could not establish an admission result.""" + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args: Any, **kwargs: Any) -> None: + return None + + +class GitHub: + def __init__(self, token: str) -> None: + if not token: + raise IntakeError("GitHub API credentials are unavailable") + self.token = token + self.opener = urllib.request.build_opener(NoRedirect()) + + def request( + self, endpoint: str, *, method: str = "GET", body: dict[str, Any] | None = None + ) -> Any: + request = urllib.request.Request( + API_URL + endpoint, + method=method, + data=json.dumps(body).encode() if body is not None else None, + headers={ + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {self.token}", + "Content-Type": "application/json", + "X-GitHub-Api-Version": "2026-03-10", + }, + ) + try: + with self.opener.open(request, timeout=15) as response: + raw = response.read(MAX_RESPONSE_BYTES + 1) + if len(raw) > MAX_RESPONSE_BYTES: + raise IntakeError("GitHub API response exceeds the intake byte limit") + return json.loads(raw) + except urllib.error.HTTPError as error: + raise IntakeError(f"GitHub API returned HTTP {error.code}") from None + except (OSError, UnicodeDecodeError, json.JSONDecodeError, RecursionError): + raise IntakeError("GitHub API response is unavailable or malformed") from None + + +def as_object(value: Any) -> dict[str, Any]: + if not isinstance(value, dict): + raise IntakeError("GitHub metadata is missing or malformed") + return value + + +def as_count(value: Any, *, minimum: int = 0) -> int: + if type(value) is not int or value < minimum: + raise IntakeError("GitHub metadata contains an invalid count or ID") + return value + + +def as_sha(value: Any) -> str: + if not isinstance(value, str) or not SHA_RE.fullmatch(value): + raise IntakeError("GitHub metadata contains an invalid revision") + return value + + +def identity(value: Any) -> tuple[Any, Any, Any]: + user = as_object(value) + return (user.get("id"), user.get("login"), user.get("type")) + + +@dataclass(frozen=True) +class PullRequest: + number: int + target: str + base: str + source: str + source_repo: int + head: str + author: tuple[Any, Any, Any] + base_owner: tuple[Any, Any, Any] + source_app: int | None + release_title_matches: bool + draft: bool + changed_files: int + commits: int + + @classmethod + def from_api(cls, data: Any) -> PullRequest: + pull = as_object(data) + base = as_object(pull.get("base")) + base_repo = as_object(base.get("repo")) + head = as_object(pull.get("head")) + target = base.get("ref") + source = head.get("ref") + if ( + pull.get("state") != "open" + or base_repo.get("id") != REPOSITORY_ID + or target not in {"main", "dev"} + or not isinstance(source, str) + or not 1 <= len(source) <= 255 + or type(pull.get("draft")) is not bool + ): + raise IntakeError("pull request has no open protected intake route") + app = pull.get("performed_via_github_app") + release = RELEASE_REF_RE.fullmatch(source) + return cls( + number=as_count(pull.get("number"), minimum=1), + target=target, + base=as_sha(base.get("sha")), + source=source, + source_repo=as_count(as_object(head.get("repo")).get("id"), minimum=1), + head=as_sha(head.get("sha")), + author=identity(pull.get("user")), + base_owner=identity(base_repo.get("owner")), + source_app=as_count(as_object(app).get("id"), minimum=1) if app is not None else None, + release_title_matches=bool(release and pull.get("title") == f"Release v{release[1]}"), + draft=pull["draft"], + changed_files=as_count(pull.get("changed_files")), + commits=as_count(pull.get("commits")), + ) + + @property + def proof(self) -> str: + return ( + f"PR #{self.number} into {self.target}, base {self.base}, " + f"head {self.head}, source repository ID {self.source_repo}" + ) + + +def is_maintainer(api: GitHub, pull: PullRequest) -> bool: + account_id, login, account_type = pull.author + if ( + type(account_id) is not int + or account_id < 1 + or account_type != "User" + or not isinstance(login, str) + or not LOGIN_RE.fullmatch(login) + ): + return False + # GitHub's authenticated base-repository owner record establishes ownership + # independently of the collaborator endpoint for this user-owned repository. + if pull.author == pull.base_owner: + return True + permission = as_object(api.request(f"collaborators/{login}/permission")) + # GitHub calls both maintain and write the `write` permission value. + user = as_object(permission.get("user")) if permission.get("user") is not None else {} + return user.get("id") == account_id and permission.get("role_name") in {"admin", "maintain"} + + +def is_control_path(path: str) -> bool: + path = path.casefold() + name = PurePosixPath(path).name + return ( + path.startswith((".github/", "scripts/", "compatibility/", "examples/gitlab/", ".codex/")) + or path.startswith(".release-") + or path in {"src/ocr_toolkit/_version.py", "src/ocr_toolkit/preflight.py"} + or name in CONTROL_FILES + or name.startswith(("dockerfile", "containerfile", "requirements", "constraints")) + or name.endswith((".lock", "-lock.json", "-lock.yaml", "-lock.yml", ".lock.json")) + or name.endswith((".sh", ".bash", ".zsh", ".ps1", ".cmd", ".bat", ".csproj", ".props")) + or name.endswith((".gradle", ".gradle.kts", ".gitlab-ci.yml", ".gitlab-ci.yaml")) + or re.search(r"(?:^|[-_.])(?:install|bootstrap)(?:[-_.]|$)", name) is not None + ) + + +def patch_lines(file: dict[str, Any]) -> tuple[list[str], list[str]] | None: + added = as_count(file.get("additions")) + deleted = as_count(file.get("deletions")) + if added == deleted == 0 and file.get("status") == "renamed": + return ([], []) + patch = file.get("patch") + if not isinstance(patch, str) or not patch.startswith("@@ "): + return None + lines = patch.split("\n") + additions = [line[1:] for line in lines if line.startswith("+")] + deletions = [line[1:] for line in lines if line.startswith("-")] + if (len(additions), len(deletions)) != (added, deleted) or added + deleted == 0: + return None + return additions, deletions + + +def path_from(file: dict[str, Any], key: str) -> str: + path = file.get(key) + if not isinstance(path, str) or not path or len(path) > 4096: + raise IntakeError("GitHub comparison contains an invalid path") + return path + + +def compare(api: GitHub, pull: PullRequest, *, accept_bot_commits: bool = False) -> dict[str, Any]: + if not 0 < pull.changed_files < MAX_COMPARE_FILES: + raise IntakeError("GitHub cannot prove the complete nonempty comparison within its limit") + per_page = MAX_BOT_COMMITS if accept_bot_commits else 1 + data = as_object(api.request(f"compare/{pull.base}...{pull.head}?per_page={per_page}")) + files = data.get("files") + if ( + as_object(data.get("base_commit")).get("sha") != pull.base + or not isinstance(files, list) + or len(files) != pull.changed_files + or as_count(data.get("total_commits")) != pull.commits + ): + raise IntakeError("GitHub immutable comparison disagrees with the pull request") + as_sha(as_object(data.get("merge_base_commit")).get("sha")) + names = {path_from(as_object(file), "filename") for file in files} + if len(names) != len(files): + raise IntakeError("GitHub comparison has duplicated paths") + return data + + +def ordinary_fork_change(files: list[Any]) -> bool: + for raw in files: + file = as_object(raw) + status = file.get("status") + if status not in {"added", "modified", "removed", "renamed", "copied"}: + return False + paths = [path_from(file, "filename")] + if status in {"renamed", "copied"} or "previous_filename" in file: + paths.append(path_from(file, "previous_filename")) + if any(is_control_path(path) for path in paths): + return False + changes = patch_lines(file) + if changes is None or any(SUPPLY_LINE_RE.search(line) for part in changes for line in part): + return False + return True + + +def only_action_pin_updates(file: dict[str, Any]) -> bool: + changes = patch_lines(file) + if changes is None: + return False + actions: list[Counter[str]] = [] + for part in changes: + pins: Counter[str] = Counter() + for line in part: + match = ACTION_PIN_RE.fullmatch(line) + if not match: + return False + pins[match[1]] += 1 + actions.append(pins) + return actions[0] == actions[1] + + +def genuine_dependabot(api: GitHub, pull: PullRequest) -> bool: + ecology = pull.source.split("/", 2) + if ( + pull.source_app not in {None, DEPENDABOT_APP_ID} + or len(ecology) != 3 + or ecology[0] != "dependabot" + or ecology[1] not in {"uv", "github_actions"} + or not 0 < pull.commits <= MAX_BOT_COMMITS + ): + return False + data = compare(api, pull, accept_bot_commits=True) + commits = data.get("commits") + if not isinstance(commits, list) or len(commits) != pull.commits: + return False + parent = as_sha(as_object(data.get("merge_base_commit")).get("sha")) + for raw in commits: + commit = as_object(raw) + verification = as_object(as_object(commit.get("commit")).get("verification")) + parents = commit.get("parents") + if ( + identity(commit.get("author")) != DEPENDABOT + or identity(commit.get("committer")) != GITHUB_WEB_FLOW + or verification.get("verified") is not True + or verification.get("reason") != "valid" + or not verification.get("signature") + or not isinstance(parents, list) + or len(parents) != 1 + or as_object(parents[0]).get("sha") != parent + ): + return False + parent = as_sha(commit.get("sha")) + if parent != pull.head: + return False + for raw in data["files"]: + file = as_object(raw) + name = path_from(file, "filename") + if file.get("status") != "modified" or "previous_filename" in file: + return False + if ecology[1] == "uv": + if name not in {"pyproject.toml", "uv.lock"}: + return False + elif ( + not name.startswith((".github/workflows/", ".github/actions/")) + or not name.endswith((".yml", ".yaml")) + or not only_action_pin_updates(file) + ): + return False + return True + + +def admission(api: GitHub, pull: PullRequest) -> tuple[bool, str]: + if pull.draft: + return False, "Mark the pull request ready for review and run full checks." + if pull.source_repo != REPOSITORY_ID: + if pull.target == "main": + return False, "Fork pull requests target dev." + if not ordinary_fork_change(compare(api, pull)["files"]): + return ( + False, + "A maintainer must submit governed changes or resolve incomplete diff evidence.", + ) + return True, "Ordinary fork change eligible for maintainer review on dev." + + if pull.target == "dev" and pull.author == DEPENDABOT: + if genuine_dependabot(api, pull): + return True, "Verified Dependabot update eligible for maintainer review on dev." + return False, "Dependabot source or revision evidence did not match the repository policy." + if not is_maintainer(api, pull): + return ( + False, + "Repository-owned intake requires a current maintainer or verified Dependabot.", + ) + if pull.target == "dev": + return True, "Maintainer branch eligible for review on dev." + if pull.source == "dev": + return True, "Repository dev promotion eligible for review on main." + if pull.release_title_matches: + return True, "Repository release PR eligible for review on main." + return False, "Main accepts the repository dev branch and the version-matched release route." + + +def branch_sha(api: GitHub, target: str) -> str: + if target not in {"main", "dev"}: + raise IntakeError("intake base must be main or dev") + ref = f"refs/heads/{target}" + live = as_object(api.request(f"git/ref/heads/{target}")) + if live.get("ref") != ref: + raise IntakeError("GitHub returned an unexpected base branch") + return as_sha(as_object(live.get("object")).get("sha")) + + +def verify_policy(api: GitHub) -> str: + policy = as_sha(os.environ.get("GITHUB_SHA")) + if ( + os.environ.get("GITHUB_REPOSITORY") != REPOSITORY + or os.environ.get("GITHUB_REF") != "refs/heads/main" + or branch_sha(api, "main") != policy + ): + raise IntakeError("intake policy is stale or outside protected main; dispatch a fresh run") + return policy + + +@dataclass(frozen=True) +class ExpectedPull: + number: int + target: str + base: str + head: str + source: str | None = None + source_repo: int | None = None + + def matches(self, pull: PullRequest) -> bool: + return ( + (pull.number, pull.target, pull.base, pull.head) + == (self.number, self.target, self.base, self.head) + and (self.source is None or self.source == pull.source) + and (self.source_repo is None or self.source_repo == pull.source_repo) + ) + + def verify_base(self, api: GitHub, policy: str) -> None: + live = policy if self.target == "main" else branch_sha(api, self.target) + if self.base != live: + raise IntakeError("protected base moved; dispatch a fresh exact-revision run") + + +def ci_subject(data: Any) -> tuple[int, int, ExpectedPull]: + run = as_object(data) + if ( + run.get("workflow_id") != CI_WORKFLOW_ID + or run.get("path") != CI_WORKFLOW_PATH + or run.get("event") != "pull_request" + or run.get("status") != "completed" + or as_object(run.get("repository")).get("id") != REPOSITORY_ID + ): + raise IntakeError("completed run is outside the configured pull-request CI workflow") + associations = run.get("pull_requests") + if not isinstance(associations, list) or len(associations) != 1: + raise IntakeError("CI has no unique PR association; dispatch a fresh exact-revision run") + pull = as_object(associations[0]) + base = as_object(pull.get("base")) + head = as_object(pull.get("head")) + source = head.get("ref") + target = base.get("ref") + head_sha = as_sha(head.get("sha")) + source_repo = as_count(as_object(head.get("repo")).get("id"), minimum=1) + if ( + as_object(base.get("repo")).get("id") != REPOSITORY_ID + or target not in {"dev", "main"} + or not isinstance(source, str) + or not 1 <= len(source) <= 255 + or run.get("head_sha") != head_sha + or run.get("head_branch") != source + or as_object(run.get("head_repository")).get("id") != source_repo + ): + raise IntakeError("CI run and PR metadata disagree; dispatch a fresh exact-revision run") + expected = ExpectedPull( + as_count(pull.get("number"), minimum=1), + target, + as_sha(base.get("sha")), + head_sha, + source, + source_repo, + ) + return as_count(run.get("id"), minimum=1), as_count(run.get("run_attempt"), minimum=1), expected + + +def requested_pull(api: GitHub) -> ExpectedPull: + event_path = Path(os.environ["GITHUB_EVENT_PATH"]) + with event_path.open("rb") as payload: + raw = payload.read(MAX_RESPONSE_BYTES + 1) + if len(raw) > MAX_RESPONSE_BYTES: + raise IntakeError("GitHub event exceeds the intake byte limit") + event = as_object(json.loads(raw)) + if as_object(event.get("repository")).get("id") != REPOSITORY_ID: + raise IntakeError("GitHub event is from a different repository") + if os.environ.get("GITHUB_EVENT_NAME") == "workflow_run" and event.get("action") == "completed": + subject = ci_subject(event.get("workflow_run")) + run_id, _, expected = subject + if ci_subject(api.request(f"actions/runs/{run_id}")) != subject: + raise IntakeError( + "CI attempt or PR association changed; dispatch a fresh exact-revision run" + ) + return expected + if os.environ.get("GITHUB_EVENT_NAME") == "workflow_dispatch": + inputs = as_object(event.get("inputs")) + number = inputs.get("pull-request-number") + target = inputs.get("target") + if ( + not isinstance(number, str) + or not re.fullmatch(r"[1-9][0-9]{0,9}", number) + or target not in {"dev", "main"} + ): + raise IntakeError("manual refresh requires an exact PR and protected target") + return ExpectedPull( + int(number), target, as_sha(inputs.get("base")), as_sha(inputs.get("head")) + ) + raise IntakeError("unsupported contributor intake event") + + +def publish(api: GitHub, pull: PullRequest, policy: str, approved: bool, message: str) -> None: + name = f"Trusted admission / {pull.target}" + external_id = f"{pull.number}:{pull.target}:{pull.base}:{pull.head}:{policy}" + output = {"title": message, "summary": f"{pull.proof}\n\nProtected main policy {policy}"} + query = urllib.parse.urlencode({"check_name": name, "filter": "latest", "per_page": 100}) + app_id = os.environ.get("INTAKE_APP_ID", "") + if not re.fullmatch(r"[1-9][0-9]{0,11}", app_id): + raise IntakeError("check publisher numeric app ID is missing or malformed") + checks = as_object(api.request(f"commits/{pull.head}/check-runs?{query}&app_id={app_id}")) + runs = checks.get("check_runs") + if not isinstance(runs, list) or checks.get("total_count") != len(runs) or len(runs) > 1: + raise IntakeError("check publisher could not identify an unambiguous previous result") + data = { + "name": name, + "status": "completed", + "conclusion": "success" if approved else "failure", + "completed_at": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), + "external_id": external_id, + "output": output, + } + run_id = os.environ.get("GITHUB_RUN_ID", "") + if re.fullmatch(r"[1-9][0-9]{0,15}", run_id): + data["details_url"] = f"https://github.com/{REPOSITORY}/actions/runs/{run_id}" + if runs: + run = as_object(runs[0]) + if ( + run.get("head_sha") != pull.head + or run.get("name") != name + or as_object(run.get("app")).get("id") != int(app_id) + ): + raise IntakeError("previous check did not match the revision or publisher") + check_id = as_count(run.get("id"), minimum=1) + result = api.request(f"check-runs/{check_id}", method="PATCH", body=data) + else: + result = api.request("check-runs", method="POST", body={**data, "head_sha": pull.head}) + published = as_object(result) + if ( + published.get("name") != name + or published.get("head_sha") != pull.head + or published.get("external_id") != external_id + or published.get("status") != "completed" + or published.get("conclusion") != data["conclusion"] + or as_object(published.get("app")).get("id") != int(app_id) + ): + raise IntakeError("published check did not match the intake decision") + + +def main() -> int: + try: + api = GitHub(os.environ.get("GH_TOKEN", "")) + policy = verify_policy(api) + expected = requested_pull(api) + expected.verify_base(api, policy) + endpoint = f"pulls/{expected.number}" + pull = PullRequest.from_api(api.request(endpoint)) + if not expected.matches(pull): + raise IntakeError("pull request changed after the event; dispatch a fresh run") + try: + approved, message = admission(api, pull) + except IntakeError as error: + approved, message = False, str(error) + if PullRequest.from_api(api.request(endpoint)) != pull: + raise IntakeError("pull request changed while being checked; dispatch a fresh run") + policy = verify_policy(api) + expected.verify_base(api, policy) + check_token = os.environ.get("INTAKE_CHECK_TOKEN", "") + if check_token or os.environ.get("INTAKE_APP_ID"): + publish(GitHub(check_token), pull, policy, approved, message) + print(f"{pull.proof}\nProtected main policy {policy}\n{message}") + return 0 if approved else 1 + except ( + IntakeError, + KeyError, + OSError, + UnicodeDecodeError, + json.JSONDecodeError, + RecursionError, + ) as error: + message = ( + str(error) + if isinstance(error, IntakeError) + else "GitHub event is unavailable or malformed" + ) + print(f"Contributor intake could not establish admission. {message}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) 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/tests/test_contributor_intake.py b/tests/test_contributor_intake.py new file mode 100644 index 00000000..847ae0a0 --- /dev/null +++ b/tests/test_contributor_intake.py @@ -0,0 +1,432 @@ +from __future__ import annotations + +import importlib.util +import json +import sys +from dataclasses import replace +from pathlib import Path +from typing import Any + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location( + "contributor_intake", ROOT / "scripts/contributor_intake.py" +) +assert SPEC is not None and SPEC.loader is not None +gate = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = gate +SPEC.loader.exec_module(gate) + +BASE = "a" * 40 +HEAD = "b" * 40 +POLICY = "c" * 40 + + +class Api: + def __init__(self, responses: dict[str, Any]) -> None: + self.responses = responses + + def request(self, endpoint: str, **kwargs: Any) -> Any: + response = self.responses[endpoint] + return response(**kwargs) if callable(response) else response + + +def user(account: tuple[int, str, str]) -> dict[str, Any]: + account_id, login, account_type = account + return {"id": account_id, "login": login, "type": account_type} + + +def candidate() -> Any: + return gate.PullRequest( + number=1, + target="dev", + base=BASE, + source="contribution", + source_repo=456, + head=HEAD, + author=(123, "contributor", "User"), + base_owner=(987, "owner", "User"), + source_app=None, + release_title_matches=False, + draft=False, + changed_files=1, + commits=1, + ) + + +def change( + filename: str, + *, + status: str = "modified", + old: str = "existing_text", + new: str = "revised_text", + **metadata: Any, +) -> dict[str, Any]: + patch = "@@ -1 +1 @@" + if old: + patch += f"\n-{old}" + if new: + patch += f"\n+{new}" + return { + "filename": filename, + "status": status, + "additions": int(bool(new)), + "deletions": int(bool(old)), + "patch": patch, + **metadata, + } + + +def comparison(file: dict[str, Any], *, commits: list[Any] | None = None) -> Api: + data = { + "base_commit": {"sha": BASE}, + "merge_base_commit": {"sha": BASE}, + "total_commits": 1, + "files": [file], + "commits": commits, + } + return Api({f"compare/{BASE}...{HEAD}?per_page={gate.MAX_BOT_COMMITS if commits else 1}": data}) + + +def test_fork_routes_depend_on_repository_identity_and_exact_target() -> None: + fork = candidate() + ordinary = change("src/ocr_toolkit/feature.py", new="from pathlib import Path") + assert gate.admission(comparison(ordinary), fork)[0] + # A maintainer account and reserved ref on a fork confer no promotion authority. + wrong_repo = replace(fork, source="dev", target="main", author=(789, "maintainer", "User")) + assert not gate.admission(Api({}), wrong_repo)[0] + assert not gate.admission(Api({}), replace(fork, draft=True))[0] + + +@pytest.mark.parametrize( + "file", + [ + change("uv.lock", status="added", old=""), + change("pyproject.toml", status="removed", new=""), + change(".python-version", old="3.14", new="3.15"), + change(".tool-versions", old="uv 0.13.8", new="uv 0.13.10"), + change("new-file.txt", status="renamed", old="", new="", previous_filename="uv.lock"), + change("scripts/setup.sh", status="renamed", previous_filename="src/feature.py"), + change("examples/gitlab/ocr-review.gitlab-ci.yml"), + change(".github/WORKFLOWS/added.yml", status="added", old=""), + change("nested/action.yaml", old=" uses: org/action@reference"), + change("misc/unknown.txt", new="wget https://downloads.example.invalid/app"), + change("misc/unknown.txt", old="git+https://git.example.invalid/project", new=""), + change("misc/file.txt", new=" index-url: https://pypi.example.invalid"), + change("misc/file.txt", new=" --extra-index-url https://pypi.example.invalid"), + change("misc/file.txt", new=" FROM python:3.13"), + {"filename": "file.bin", "status": "modified", "additions": 0, "deletions": 0}, + {**change("file.txt"), "additions": 2}, + ], +) +def test_fork_governed_or_incomplete_change_is_rejected(file: dict[str, Any]) -> None: + assert not gate.admission(comparison(file), candidate())[0] + + +def test_incomplete_or_wrong_comparison_cannot_allow_intake() -> None: + api = comparison(change("file.txt")) + with pytest.raises(gate.IntakeError, match="disagrees"): + gate.admission(api, replace(candidate(), changed_files=2)) + with pytest.raises(gate.IntakeError, match="limit"): + gate.admission(api, replace(candidate(), changed_files=gate.MAX_COMPARE_FILES)) + + +@pytest.mark.parametrize("role, approved", [("admin", True), ("maintain", True), ("write", False)]) +def test_same_repo_dependency_updates_require_current_maintainer_role( + role: str, approved: bool +) -> None: + author = (789, "maintainer", "User") + pull = replace(candidate(), source_repo=gate.REPOSITORY_ID, author=author) + permission = {"role_name": role, "user": user(author)} + assert ( + gate.admission(Api({"collaborators/maintainer/permission": permission}), pull)[0] + is approved + ) + bad_id = {**permission, "user": user((790, "maintainer", "User"))} + assert not gate.admission(Api({"collaborators/maintainer/permission": bad_id}), pull)[0] + + +def test_maintainer_main_routes_require_promotion_or_exact_release() -> None: + author = (789, "maintainer", "User") + api = Api({"collaborators/maintainer/permission": {"role_name": "admin", "user": user(author)}}) + pull = replace(candidate(), target="main", source_repo=gate.REPOSITORY_ID, author=author) + assert gate.admission(api, replace(pull, source="dev"))[0] + assert gate.admission(api, replace(pull, source="release/v0.16.1", release_title_matches=True))[ + 0 + ] + assert not gate.admission(api, replace(pull, source="release/v0.16.1"))[0] + assert not gate.admission(api, replace(pull, source="maintainer/0.16.1-intake"))[0] + assert not gate.admission(api, replace(pull, source="maintainer/other"))[0] + + +def test_repo_owner_is_admitted_from_authenticated_base_metadata_without_collaborator_lookup() -> ( + None +): + pull = replace(candidate(), source_repo=gate.REPOSITORY_ID, target="main", source="dev") + assert gate.admission(Api({}), replace(pull, author=pull.base_owner))[0] + assert not gate.admission(Api({}), replace(pull, author=pull.base_owner, source_repo=9876))[0] + + +def signed_bot_commit() -> dict[str, Any]: + return { + "sha": HEAD, + "author": user(gate.DEPENDABOT), + "committer": user(gate.GITHUB_WEB_FLOW), + "parents": [{"sha": BASE}], + "commit": {"verification": {"verified": True, "reason": "valid", "signature": "signature"}}, + } + + +def bot_pr() -> Any: + return replace( + candidate(), + source_repo=gate.REPOSITORY_ID, + source="dependabot/uv/update", + author=gate.DEPENDABOT, + ) + + +def test_dependabot_requires_authenticated_author_and_verified_exact_head() -> None: + pull = bot_pr() + lock = change("uv.lock") + signed = signed_bot_commit() + api = comparison(lock, commits=[signed]) + assert gate.admission(api, pull)[0] + assert gate.admission(api, replace(pull, source_app=gate.DEPENDABOT_APP_ID))[0] + assert not gate.admission(Api({}), replace(pull, source_app=999))[0] + assert not gate.admission(Api({}), replace(pull, target="main"))[0] + assert not gate.admission(Api({}), replace(pull, author=(1234, "dependabot[bot]", "Bot")))[0] + assert not gate.admission(comparison(lock), replace(pull, source_repo=1234))[0] + assert not gate.admission(comparison(lock, commits=[{**signed, "sha": POLICY}]), pull)[0] + assert not gate.admission( + comparison(lock, commits=[{**signed, "commit": {"verification": {"verified": False}}}]), + pull, + )[0] + assert not gate.admission( + comparison(lock, commits=[{**signed, "parents": [{"sha": POLICY}]}]), pull + )[0] + + +def test_dependabot_action_changes_are_same_action_pin_updates() -> None: + pull = replace(bot_pr(), source="dependabot/github_actions/update") + workflow = ".github/workflows/ci.yml" + old = f" - uses: org/action@{BASE} # v1" + new = f" - uses: org/action@{HEAD} # v2" + files = [ + change(workflow, old=old, new=new), + change(workflow, old=old, new=new.replace("org/", "other/")), + ] + for file, approved in zip(files, (True, False), strict=True): + assert gate.admission(comparison(file, commits=[signed_bot_commit()]), pull)[0] is approved + assert not gate.admission( + comparison( + change(workflow, old=old, new=" - run: echo check"), commits=[signed_bot_commit()] + ), + pull, + )[0] + + +def pull_json(pull: Any, *, title: str = "Change") -> dict[str, Any]: + return { + "number": pull.number, + "state": "open", + "draft": pull.draft, + "title": title, + "user": user(pull.author), + "base": { + "ref": pull.target, + "sha": pull.base, + "repo": {"id": gate.REPOSITORY_ID, "owner": user(pull.base_owner)}, + }, + "head": {"ref": pull.source, "sha": pull.head, "repo": {"id": pull.source_repo}}, + "changed_files": pull.changed_files, + "commits": pull.commits, + "performed_via_github_app": {"id": pull.source_app} + if pull.source_app is not None + else None, + } + + +def test_release_title_must_match_branch_version_exactly() -> None: + pull = replace(candidate(), target="main", source="release/v0.16.1") + assert gate.PullRequest.from_api(pull_json(pull, title="Release v0.16.1")).release_title_matches + assert not gate.PullRequest.from_api( + pull_json(pull, title="Release v0.16.2") + ).release_title_matches + + +def test_app_published_result_names_target_and_identifies_pr_base_head_and_policy( + monkeypatch: pytest.MonkeyPatch, +) -> None: + pull = candidate() + monkeypatch.setenv("INTAKE_APP_ID", "888") + + def post(*, method: str, body: dict[str, Any]) -> dict[str, Any]: + assert method == "POST" + assert body["name"] == "Trusted admission / dev" + assert body["external_id"] == f"1:dev:{BASE}:{HEAD}:{POLICY}" + assert body["conclusion"] == "failure" + return {**body, "app": {"id": 888}} + + api = Api( + { + f"commits/{HEAD}/check-runs?check_name=Trusted+admission+%2F+dev&filter=latest&per_page=100&app_id=888": { + "total_count": 0, + "check_runs": [], + }, + "check-runs": post, + } + ) + gate.publish(api, pull, POLICY, False, "Denied.") + + +def test_app_refresh_updates_the_existing_same_revision_check( + monkeypatch: pytest.MonkeyPatch, +) -> None: + pull = replace(candidate(), target="main", source_repo=gate.REPOSITORY_ID, source="dev") + monkeypatch.setenv("INTAKE_APP_ID", "888") + existing = {"id": 17, "name": "Trusted admission / main", "head_sha": HEAD, "app": {"id": 888}} + + def update(*, method: str, body: dict[str, Any]) -> dict[str, Any]: + assert method == "PATCH" + assert body["external_id"] == f"1:main:{BASE}:{HEAD}:{POLICY}" + assert body["conclusion"] == "success" + return {**existing, **body} + + api = Api( + { + f"commits/{HEAD}/check-runs?check_name=Trusted+admission+%2F+main&filter=latest&per_page=100&app_id=888": { + "total_count": 1, + "check_runs": [existing], + }, + "check-runs/17": update, + } + ) + gate.publish(api, pull, POLICY, True, "Approved.") + existing["app"] = {"id": 999} + with pytest.raises(gate.IntakeError, match="previous check did not match"): + gate.publish(api, pull, POLICY, True, "Approved.") + + +def run_json(pull: Any) -> dict[str, Any]: + data = pull_json(pull) + return { + "id": 8, + "run_attempt": 3, + "workflow_id": gate.CI_WORKFLOW_ID, + "path": gate.CI_WORKFLOW_PATH, + "event": "pull_request", + "status": "completed", + "repository": {"id": gate.REPOSITORY_ID}, + "head_repository": {"id": pull.source_repo}, + "head_branch": pull.source, + "head_sha": pull.head, + "pull_requests": [{key: data[key] for key in ("number", "base", "head")}], + } + + +def set_event( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, name: str, payload: dict[str, Any] +) -> Path: + event_path = tmp_path / "event.json" + event_path.write_text(json.dumps({"repository": {"id": gate.REPOSITORY_ID}, **payload})) + monkeypatch.setenv("GITHUB_EVENT_PATH", str(event_path)) + monkeypatch.setenv("GITHUB_EVENT_NAME", name) + return event_path + + +def test_workflow_rechecks_exact_event_and_live_revision_before_publishing( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + pull = candidate() + run = run_json(pull) + set_event(monkeypatch, tmp_path, "workflow_run", {"action": "completed", "workflow_run": run}) + monkeypatch.setenv("GITHUB_REPOSITORY", gate.REPOSITORY) + monkeypatch.setenv("GITHUB_REF", "refs/heads/main") + monkeypatch.setenv("GITHUB_SHA", POLICY) + monkeypatch.setenv("INTAKE_CHECK_TOKEN", "install-token") + api = comparison(change("src/feature.py")) + api.responses.update( + { + "git/ref/heads/main": {"ref": "refs/heads/main", "object": {"sha": POLICY}}, + "git/ref/heads/dev": {"ref": "refs/heads/dev", "object": {"sha": BASE}}, + "actions/runs/8": run, + "pulls/1": lambda: next(snapshots), + } + ) + snapshots = iter([pull_json(pull), pull_json(replace(pull, head=POLICY))]) + monkeypatch.setattr(gate, "GitHub", lambda _token: api) + assert gate.main() == 1 + assert "changed while being checked" in capsys.readouterr().err + + api.responses["pulls/1"] = pull_json(replace(pull, target="main")) + assert gate.main() == 1 + assert "changed after the event" in capsys.readouterr().err + + api.responses["git/ref/heads/dev"]["object"]["sha"] = HEAD + assert gate.main() == 1 + assert "protected base moved" in capsys.readouterr().err + + api.responses["git/ref/heads/main"]["object"]["sha"] = BASE + assert gate.main() == 1 + assert "policy is stale" in capsys.readouterr().err + + +@pytest.mark.parametrize( + "field,value", + [ + ("workflow_id", 999), + ("path", ".github/workflows/other.yml"), + ("event", "pull_request_target"), + ("status", "queued"), + ("head_repository", {"id": 9999}), + ("head_branch", "different"), + ("head_sha", POLICY), + ("pull_requests", []), + ], +) +def test_ci_requires_exact_workflow_and_immutable_pr_association(field: str, value: Any) -> None: + run = run_json(candidate()) + with pytest.raises(gate.IntakeError): + gate.ci_subject({**run, field: value}) + with pytest.raises(gate.IntakeError, match="no unique PR association"): + gate.ci_subject({**run, "pull_requests": run["pull_requests"] * 2}) + + +def test_no_fork_association_can_be_refreshed_by_exact_manual_dispatch( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + pull = candidate() + run = {**run_json(pull), "pull_requests": []} + set_event(monkeypatch, tmp_path, "workflow_run", {"action": "completed", "workflow_run": run}) + with pytest.raises(gate.IntakeError, match="no unique PR association"): + gate.requested_pull(Api({})) + + run["pull_requests"] = run_json(pull)["pull_requests"] + set_event(monkeypatch, tmp_path, "workflow_run", {"action": "completed", "workflow_run": run}) + with pytest.raises(gate.IntakeError, match="attempt or PR association changed"): + gate.requested_pull(Api({"actions/runs/8": {**run, "run_attempt": 4}})) + + set_event( + monkeypatch, + tmp_path, + "workflow_dispatch", + {"inputs": {"pull-request-number": "1", "target": "dev", "base": BASE, "head": HEAD}}, + ) + monkeypatch.setenv("GITHUB_REPOSITORY", gate.REPOSITORY) + monkeypatch.setenv("GITHUB_REF", "refs/heads/main") + monkeypatch.setenv("GITHUB_SHA", POLICY) + monkeypatch.delenv("INTAKE_APP_ID", raising=False) + monkeypatch.delenv("INTAKE_CHECK_TOKEN", raising=False) + api = comparison(change("src/feature.py")) + api.responses.update( + { + "git/ref/heads/main": {"ref": "refs/heads/main", "object": {"sha": POLICY}}, + "git/ref/heads/dev": {"ref": "refs/heads/dev", "object": {"sha": BASE}}, + "pulls/1": pull_json(pull), + } + ) + monkeypatch.setattr(gate, "GitHub", lambda _token: api) + assert gate.main() == 0 + assert "eligible for maintainer review on dev" in capsys.readouterr().out 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_docs_only_ci.py b/tests/test_docs_only_ci.py index 224ee626..b8e502dc 100644 --- a/tests/test_docs_only_ci.py +++ b/tests/test_docs_only_ci.py @@ -197,14 +197,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 +228,111 @@ 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", "") + + +def test_hosted_secrets_scan_fetches_the_exact_pr_without_checking_it_out(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") + _git(tmp_path, "commit", "--allow-empty", "-qm", "base policy") + base = _git(tmp_path, "rev-parse", "HEAD") + (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" + 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"]] + 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, check=False) + assert rejected.returncode != 0 + assert not scanned.exists() + + 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_integration_contracts.py b/tests/test_integration_contracts.py index 10129d6d..7ab4ad28 100644 --- a/tests/test_integration_contracts.py +++ b/tests/test_integration_contracts.py @@ -439,10 +439,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_operations_docs.py b/tests/test_operations_docs.py index 632b6c72..08f784f0 100644 --- a/tests/test_operations_docs.py +++ b/tests/test_operations_docs.py @@ -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] @@ -920,7 +919,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_release_authorization.py b/tests/test_release_authorization.py index 16eb21dd..3e04b7dd 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,57 @@ 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"]) +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"] + gate, checkout = job["steps"][:2] + assert gate["if"] == "github.event_name == 'workflow_dispatch'" + assert checkout["uses"].startswith("actions/checkout@") + + repository = "example/open-code-review-toolkit" + pr = release_pr() + pr["base"]["repo"] = {"full_name": repository} + if scenario == "fork": + pr["head"]["repo"]["full_name"] = "fork/open-code-review-toolkit" + parent = "d" * 40 if scenario == "wrong_parent" else "b" * 40 + (tmp_path / "pr.json").write_text(json.dumps(pr)) + (tmp_path / "merge.json").write_text(json.dumps(commit_payload("a" * 40, "e" * 40, [parent]))) + fake_gh = tmp_path / "gh" + fake_gh.write_text( + "#!/bin/sh\n" + '[ "$1" = api ] || exit 1\n' + 'case "$2" in\n' + ' "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER") cat pr.json ;;\n' + ' "repos/$GITHUB_REPOSITORY/commits/$MERGE") cat merge.json ;;\n' + " *) exit 1 ;;\n" + "esac\n" + ) + fake_gh.chmod(0o700) + environment = { + **os.environ, + "PATH": f"{tmp_path}{os.pathsep}{os.environ['PATH']}", + "GITHUB_REPOSITORY": repository, + "PR_NUMBER": "5", + "VERSION": "0.1.0", + "HEAD": "c" * 40, + "MERGE": "a" * 40, + "BASE": "d" * 40 if scenario == "wrong_base" else "b" * 40, + } + 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 + + def test_release_workflow_keeps_strict_release_authorization() -> None: workflow = WORKFLOW.read_text(encoding="utf-8") 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_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 068175444a19f84ff9d43d56927c140589e5b0eb Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:36:35 +0100 Subject: [PATCH 04/25] Verify local incremental reuse and preserve federated review accounting --- PLANS.md | 6 +- changelog.d/352.feature.md | 1 + changelog.d/353.feature.md | 1 + changelog.d/README.md | 2 +- docs/local.md | 45 +- docs/review-decision-flow.md | 13 +- src/ocr_toolkit/evidence/repository.py | 127 +++++- src/ocr_toolkit/local_incremental.py | 280 ++++++++++-- .../local_incremental_dependencies.py | 370 +++++++++++----- src/ocr_toolkit/local_incremental_replay.py | 248 +++++++++++ src/ocr_toolkit/local_incremental_state.py | 253 ++++++++++- src/ocr_toolkit/providers/local.py | 4 +- src/ocr_toolkit/reporting/incremental.py | 52 +++ src/ocr_toolkit/review_runner.py | 12 +- tests/federation/test_ocr_qualification.py | 139 ++++++ tests/test_local_incremental.py | 402 ++++++++++++++++-- 16 files changed, 1720 insertions(+), 235 deletions(-) create mode 100644 changelog.d/352.feature.md create mode 100644 changelog.d/353.feature.md create mode 100644 src/ocr_toolkit/local_incremental_replay.py diff --git a/PLANS.md b/PLANS.md index 30b88fcc..f2377e25 100644 --- a/PLANS.md +++ b/PLANS.md @@ -85,7 +85,7 @@ Fork validation uses GitHub-hosted pull_request jobs with SHA-pinned actions, re ### Verification -On a same-repository dev push and a dev-to-main promotion, verify effective job permissions and exclusion of publishing OIDC and site credentials from PR-controlled jobs. Use a fork PR to verify dev CI and actual runner permission banners, external-to-main denial, eligible dev promotion, changed-head reapproval, and dev exclusion from both registry environments. Check release authorization on its existing protected path. Bind the admission gate to policy an external workflow cannot override; a same-named check from any Actions workflow alone is insufficient. 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. +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, external-to-main denial, eligible dev promotion, changed-head reapproval, and dev exclusion from both registry environments. Check release authorization on its existing protected path. Bind the admission gate to policy an external workflow cannot override; a same-named check from any Actions workflow alone is insufficient. 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. @@ -95,6 +95,10 @@ The maintainer intake work is tracked in [#356](https://github.com/xeonvs/open-c 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 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. + 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. 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/README.md b/changelog.d/README.md index 983e9153..cf1a40eb 100644 --- a/changelog.d/README.md +++ b/changelog.d/README.md @@ -4,7 +4,7 @@ Every user-visible 0.x change needs one fragment named `..md`, wher 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 links the PR by number. Group multiple contributions from the same person in one acknowledgment and link each additional accepted PR explicitly in its body. An empty category produces no heading. +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. diff --git a/docs/local.md b/docs/local.md index 6405d7aa..bea920f5 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,30 @@ 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 +checks Python dependencies around edited function bodies. It 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 edit with unsupported source +semantics, or a change to the 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 runs locally before OCR. 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 +204,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,14 +220,25 @@ 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 requires compact JSON, Markdown still contains all admitted findings and their provenance. +Incremental review and continuation run a verified private copy of OCR. On a +machine with outbound network rules tied to the executable path, an installed +`ocr llm test` can succeed while the private copy times out before a model +response. Check the effective outbound decision for the failed process. Use +`ocr-ci review --local` for a fresh review through the installed binary when +that path can reach the provider. A failed run provides no review coverage. + ## LLM authentication Local review uses the configured API provider by default, including custom diff --git a/docs/review-decision-flow.md b/docs/review-decision-flow.md index d14788f7..8acefad0 100644 --- a/docs/review-decision-flow.md +++ b/docs/review-decision-flow.md @@ -146,8 +146,11 @@ 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] + 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 --> 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] @@ -181,7 +184,7 @@ flowchart TD 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;
label carried findings or record the federated fallback] 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?} @@ -217,8 +220,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,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 diff --git a/src/ocr_toolkit/evidence/repository.py b/src/ocr_toolkit/evidence/repository.py index 87c47168..653d4986 100644 --- a/src/ocr_toolkit/evidence/repository.py +++ b/src/ocr_toolkit/evidence/repository.py @@ -42,6 +42,7 @@ ) 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 @@ -198,24 +199,35 @@ 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 ) -> 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) + if self.command_timeout is not None or local_only: + return self._run_streamed( + args, timeout=self._timeout(timeout), text=text, local_only=local_only + ) return self._run_at(self.root, args, timeout=self._timeout(timeout), text=text) 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 = MAX_GIT_TEXT_BYTES, ) -> subprocess.CompletedProcess[str] | subprocess.CompletedProcess[bytes]: """Bound audit metadata while consuming it, including enormous Git trees.""" command = [*_git_prefix(self.root), *args] + environment = _git_environment() + if local_only: + environment.update(GIT_ALLOW_PROTOCOL="", GIT_NO_LAZY_FETCH="1") 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,11 +241,11 @@ 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, max_bytes - 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) > max_bytes: raise RepositoryEvidenceError( "Git plumbing output exceeds the bounded byte limit" ) @@ -251,6 +263,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.""" @@ -344,12 +442,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,12 +469,17 @@ 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) + sha = self.resolve_commit(ref, local_only=local_only) + result = self._run( + ["ls-tree", "-z", "-r", "--full-tree", sha], + timeout=30, + text=False, + local_only=local_only, + ) assert isinstance(result.stdout, bytes) if result.returncode != 0: raise RepositoryEvidenceError("failed to enumerate repository tree") diff --git a/src/ocr_toolkit/local_incremental.py b/src/ocr_toolkit/local_incremental.py index 076db356..7caf5bb7 100644 --- a/src/ocr_toolkit/local_incremental.py +++ b/src/ocr_toolkit/local_incremental.py @@ -7,6 +7,7 @@ import hmac import re import sys +from collections import Counter from collections.abc import Collection, Sequence from dataclasses import dataclass, field, replace from pathlib import Path, PurePosixPath @@ -29,16 +30,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 +67,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 +80,15 @@ _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") +_DATA_SUFFIXES = {".json", ".markdown", ".md"} _RULE_FILE_SUFFIXES = {"md", "txt", "markdown"} _ISOLATED_GIT_SETTINGS = frozenset( { @@ -242,22 +259,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 +302,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 +344,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 +389,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 +458,48 @@ 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 _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() + if suffix not in _DATA_SUFFIXES: + raise IncrementalError("a changed file has unsupported shared source semantics") + 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, @@ -418,22 +511,44 @@ def _independent_paths( ) -> 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)} + modules = {} + references = {} + changed_texts = {} + 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) 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: + 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() } @@ -460,24 +575,28 @@ def load_imports(path: str) -> tuple[tuple[StaticImport, ...], bool]: 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( + path + for path in selected + if path in modules or PurePosixPath(path).suffix.lower() not in _DATA_SUFFIXES + ) 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 +682,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.""" @@ -641,7 +762,14 @@ def select(self, preview_stdout: bytes) -> list[str] | None: 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 +796,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 +817,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 +878,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 +891,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 +952,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 +994,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: @@ -877,6 +1037,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) @@ -953,6 +1116,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, @@ -1070,7 +1255,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 +1264,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..da6992e4 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,31 @@ 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) 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 +240,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 +273,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 +294,62 @@ 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 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 == 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 +358,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 +414,146 @@ 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 - or any( - group.diagram_called and diagram_owner not in groups[key] - for key, group in self.groups.items() - ) - ): - 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( + 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.comment_paths - set(groups[key]) + for key, group in self.groups.items() + ) + or 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, + ) + 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..fefc2550 --- /dev/null +++ b/src/ocr_toolkit/local_incremental_replay.py @@ -0,0 +1,248 @@ +"""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 = [] + for path in args["path_array"]: + if path not in self._diffs: + raise IncrementalError("native diff has a missing or ambiguous path") + parts.append(f"==== FILE: {path} ====\n{self._diffs[path]}\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/providers/local.py b/src/ocr_toolkit/providers/local.py index 78119345..c799fdeb 100644 --- a/src/ocr_toolkit/providers/local.py +++ b/src/ocr_toolkit/providers/local.py @@ -76,12 +76,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/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/review_runner.py b/src/ocr_toolkit/review_runner.py index 7477871e..c5d4a281 100644 --- a/src/ocr_toolkit/review_runner.py +++ b/src/ocr_toolkit/review_runner.py @@ -212,6 +212,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, @@ -285,6 +286,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): @@ -2121,6 +2125,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: @@ -4134,7 +4142,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, diff --git a/tests/federation/test_ocr_qualification.py b/tests/federation/test_ocr_qualification.py index 8729bbe6..ab8af7e5 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 ( @@ -31,6 +34,142 @@ 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": 2, + "servers": { + "tracker": { + "transport": { + "type": "stdio", + "command": sys.executable, + "args": ["-I", str(Path(__file__).with_name("sdk_peer.py").resolve())], + }, + "tools": {"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: diff --git a/tests/test_local_incremental.py b/tests/test_local_incremental.py index 6a53ce99..b07a1bec 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 @@ -202,7 +273,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 +297,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 +703,52 @@ 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("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 +813,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 +907,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 +929,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 +1050,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 +1083,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 +1120,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 +1132,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 +1185,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 +1243,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 +1272,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 +1287,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 +1332,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 From 1e402fb9185ca5f7a273232cd61d5a5607e064f4 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:38:29 +0100 Subject: [PATCH 05/25] Address review findings in protected workflows and use the canonical OCR executable name --- .github/workflows/codeql.yml | 1 + .github/workflows/contributor-intake.yml | 20 ++++- .github/workflows/dependency-review.yml | 1 + .github/workflows/ocr-compatibility.yml | 11 +++ .github/workflows/release.yml | 17 ++++- .github/workflows/scorecard.yml | 1 + .github/workflows/security.yml | 6 +- docs/compatibility.md | 11 ++- docs/contributor-intake.md | 8 +- docs/development.md | 5 +- docs/local.md | 10 +-- docs/release.md | 18 +++-- scripts/contributor_intake.py | 54 +++++++++---- scripts/ocr_qualification/delivery.py | 9 ++- src/ocr_toolkit/preflight.py | 30 ++++---- tests/test_contributor_intake.py | 97 ++++++++++++++++++++++++ tests/test_docs_only_ci.py | 64 ++++++++++++---- tests/test_native_capabilities.py | 67 ++++++++++++++++ tests/test_ocr_compat.py | 8 +- tests/test_operations_docs.py | 6 ++ tests/test_release_authorization.py | 19 +++-- 21 files changed, 389 insertions(+), 74 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 5ccf6ca1..0b189a88 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -25,6 +25,7 @@ jobs: (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. diff --git a/.github/workflows/contributor-intake.yml b/.github/workflows/contributor-intake.yml index 08a30ca3..6e15a738 100644 --- a/.github/workflows/contributor-intake.yml +++ b/.github/workflows/contributor-intake.yml @@ -48,9 +48,27 @@ jobs: with: ref: ${{ github.sha }} persist-credentials: false + - name: Validate optional check publisher configuration + id: publisher-config + shell: bash + env: + INTAKE_APP_ID: ${{ vars.INTAKE_APP_ID }} + INTAKE_APP_CLIENT_ID: ${{ vars.INTAKE_APP_CLIENT_ID }} + INTAKE_APP_PRIVATE_KEY: ${{ secrets.INTAKE_APP_PRIVATE_KEY }} + run: | + if [[ -z "$INTAKE_APP_ID" && -z "$INTAKE_APP_CLIENT_ID" && -z "$INTAKE_APP_PRIVATE_KEY" ]]; then + exit 0 + fi + if [[ ! "$INTAKE_APP_ID" =~ ^[1-9][0-9]{0,11}$ || + ! "$INTAKE_APP_CLIENT_ID" =~ [^[:space:]] || + ! "$INTAKE_APP_PRIVATE_KEY" =~ [^[:space:]] ]]; then + echo 'Configure INTAKE_APP_ID (numeric), INTAKE_APP_CLIENT_ID and INTAKE_APP_PRIVATE_KEY together, or clear all three for advisory mode.' >&2 + exit 1 + fi + echo 'enabled=true' >> "$GITHUB_OUTPUT" - uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 id: publisher - if: vars.INTAKE_APP_CLIENT_ID != '' || vars.INTAKE_APP_ID != '' + if: steps.publisher-config.outputs.enabled == 'true' with: client-id: ${{ vars.INTAKE_APP_CLIENT_ID }} private-key: ${{ secrets.INTAKE_APP_PRIVATE_KEY }} diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml index a95838c5..070c1bbd 100644 --- a/.github/workflows/dependency-review.yml +++ b/.github/workflows/dependency-review.yml @@ -17,6 +17,7 @@ jobs: 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: diff --git a/.github/workflows/ocr-compatibility.yml b/.github/workflows/ocr-compatibility.yml index c418ffaf..c146cbd3 100644 --- a/.github/workflows/ocr-compatibility.yml +++ b/.github/workflows/ocr-compatibility.yml @@ -30,6 +30,17 @@ 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' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f2a45a08..25e01f16 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -96,7 +96,15 @@ jobs: 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}$ ]] - gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}" | + 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 @@ -104,7 +112,7 @@ jobs: .head.repo.full_name == $repo and .head.ref == ("release/v" + $version) and .head.sha == $head and .title == ("Release v" + $version) ' >/dev/null - gh api "repos/${GITHUB_REPOSITORY}/commits/${MERGE}" | + 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 @@ -680,6 +688,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 diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml index 2cc8f085..51282d7a 100644 --- a/.github/workflows/scorecard.yml +++ b/.github/workflows/scorecard.yml @@ -20,6 +20,7 @@ jobs: name: analyze-supply-chain 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. diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 121b624f..7c337a7f 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -76,6 +76,7 @@ jobs: 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' @@ -134,7 +135,10 @@ jobs: [[ "${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" - test "$(git rev-parse FETCH_HEAD)" = "${PR_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 diff --git a/docs/compatibility.md b/docs/compatibility.md index abea4bf5..359da16f 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -72,8 +72,8 @@ 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 @@ -97,6 +97,13 @@ Classify a pin-only promotion and its machine or human qualification evidence as - `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`. - `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 the `ocr-compatibility-chain` artifact for `ocr-chain-update.patch` +before preparing a maintainer-owned compatibility PR. If the patch is absent +or expired, dispatch from `main` with `tag` and `after_tag` empty and +`qualification_only` off. Set `through_tag` to the last release in the +desired chain. Review the new classification 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 diff --git a/docs/contributor-intake.md b/docs/contributor-intake.md index e1f35d24..45288712 100644 --- a/docs/contributor-intake.md +++ b/docs/contributor-intake.md @@ -10,7 +10,7 @@ GitHub's authenticated base-repository metadata establishes the owner of this us Maintainers own dependency manifests and lockfiles, origins and integrity values, Actions and CI configuration, installer scripts, container sources and OCR qualification pins. A contributor can document a needed change and ask a maintainer to prepare the update. The gate checks both paths of a rename or copy, checks additions and removals, and checks changed lines for common installation, source and pin syntax outside the governed paths. Missing or incomplete comparison evidence requires a maintainer-owned revision. This file and text inspection supports a maintainer's review of the full diff and executable paths, including unfamiliar formats or dependencies assembled dynamically. [Dependency audit and upstream review](development.md#dependency-audit-before-push) -The configured Dependabot app can submit its `uv` dependency updates and fixed-SHA updates to the existing GitHub Actions references on `dev`. The gate requires GitHub's authenticated Dependabot user ID, a repository-owned updater branch, and a complete linear chain of GitHub-verified Dependabot commits through the PR head. Where GitHub supplies an app ID on the PR, it must be Dependabot's. Labels, branch names and display text carry no independent authority. A bot update still receives the same maintainer review and applicable tests. +The configured Dependabot app can submit `uv` dependency updates and replace existing GitHub Actions pins in place on `dev`. The replacement preserves each action's path, position and YAML structure. The gate requires GitHub's authenticated Dependabot user ID, a repository-owned updater branch, and a complete linear chain of GitHub-verified Dependabot commits through the PR head. Where GitHub supplies an app ID on the PR, it must be Dependabot's. Labels, branch names and display text carry no independent authority. A bot update still receives the same maintainer review and applicable tests. Dependabot's `target-branch: dev` applies to scheduled version updates. GitHub opens Dependabot security updates against the default branch. The maintainer retargets a genuine security update to `dev` for review or prepares 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) @@ -18,13 +18,13 @@ Dependabot's `target-branch: dev` applies to scheduled version updates. GitHub o 1. Land the reviewed maintainer bootstrap through the existing protected `main` procedure before activating the admission rules. In repository Actions settings, require workflow approval for all outside collaborators, retain GitHub-hosted pull-request validation with read-only effective permissions, and turn off automatic merge for intake. Keep publisher credentials and deployment environments restricted to their trusted `main` triggers. [Actions approval 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) 2. Pre-create the `contributor-intake` environment with **Selected branches and tags**, a single branch rule for `main` and no tag rule. Confirm the effective deployment policy before adding any secret. Protect `dev` from force pushes and deletion and require the protected PR and CI rules on it before retargeting any contributor PR. Retain the protected-main signature and release rules. Require current CI for both branches and keep any emergency administrator bypass limited to audited PR recovery. -3. If enabling server-enforced check provenance, register a private dedicated GitHub App with **Checks: read and write** and its implicit **Metadata: read** only. Disable webhooks and install it on this repository alone. Add its numeric app ID as environment variable `INTAKE_APP_ID`, its client ID as environment variable `INTAKE_APP_CLIENT_ID`, and its private key as environment secret `INTAKE_APP_PRIVATE_KEY`. The workflow requests a short-lived repository-scoped token with `checks: write`. Give this app no ruleset bypass or merge capability. [GitHub App permissions](https://docs.github.com/en/apps/creating-github-apps/registering-a-github-app/choosing-permissions-for-a-github-app) -4. Observe the app publish `Trusted admission / dev` and `Trusted admission / main`. Configure the matching required check on each branch's ruleset with the dedicated app's numeric `integration_id`. Confirm GitHub's effective rules list the correct check and app on both refs. Keep the existing required checks on `main` as check runs so the stable release authorizer can read them on the exact head. If the applicable GitHub plan or repository settings cannot require a check from the app, the protected-main workflow remains advisory and a maintainer must enforce its result at merge time. A same-name GitHub Actions job provides no independent app identity. [Selecting the source of a required status check](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets#require-status-checks-to-pass-before-merging) +3. If enabling server-enforced check provenance, register a private dedicated GitHub App with **Checks: read and write** and its implicit **Metadata: read** only. Disable webhooks and install it on this repository alone. Configure its numeric app ID as environment variable `INTAKE_APP_ID`, its client ID as environment variable `INTAKE_APP_CLIENT_ID`, and its private key as environment secret `INTAKE_APP_PRIVATE_KEY`. The workflow checks all three settings before requesting a short-lived repository-scoped token with `checks: write`. Leave all three empty for advisory mode. Give this app no ruleset bypass or merge capability. [GitHub App permissions](https://docs.github.com/en/apps/creating-github-apps/registering-a-github-app/choosing-permissions-for-a-github-app) +4. Observe the app publish `Trusted admission / dev` and `Trusted admission / main`. Configure the matching required check on each branch's ruleset with the dedicated app's numeric `integration_id` and verify the effective rules on both refs. The stable release authorizer verifies each required check's app, name, reviewed head and conclusion. The [intake record check below](#merging-a-reviewed-pr) is mandatory before merging every PR, including stable release PRs with a successful app-bound required check. If the applicable GitHub settings cannot require the check from the app, the protected-main workflow provides the advisory admission record for the same maintainer verification. [Selecting the source of a required status check](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets#require-status-checks-to-pass-before-merging) 5. Before opening `dev` to contributors, verify an ordinary fork PR targeting `dev`, a fork PR changing a manifest or pin, a mislabeled bot attempt, an external PR targeting `main`, genuine Dependabot retargeted to `dev`, a maintainer update, and a repository `dev` promotion to `main`. Confirm a changed head or base needs fresh evidence, a draft remains ineligible, and Ready for review runs new full validation. For the app mode, check the app identity and attempt to satisfy the requirement with a same-named ordinary workflow in a controlled test. Confirm read-only tokens on fork validation and rejection of publication from `dev` before opening intake. Use the existing protected release contracts for the stable route. ## Merging a reviewed PR -Before merging, fetch the live PR and confirm the intended PR number, source repository and branch, target branch, base SHA and head SHA. On the newest **Contributor intake policy** run from `main`, or in the dedicated app's check details if configured, verify the recorded PR number, target, revision pair and current policy SHA. GitHub required checks are commit-scoped. The app binding proves who produced a check, while the maintainer verifies the admission record describes this specific PR. Use manual merge after this verification and maintainer review. [GitHub required-check commit resolution](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks#required-check-needs-to-succeed-against-the-latest-commit-sha) +Before merging, fetch the live PR and confirm its number, source repository ID and branch, target branch, current base SHA and reviewed head SHA. Read the current protected `main` SHA, which owns the policy. Require a successful **Contributor intake policy** run from `main` for the live PR number, target, source repository ID, base, head and policy. If an app is configured, verify the `Trusted admission / ` check's app ID and successful conclusion, and match its `external_id` against `::::`. Verify the permitted source branch in the live PR. GitHub evaluates required checks by commit. The maintainer verifies the PR, base and policy values immediately before the manual merge, including for a stable release. Missing or stale evidence requires a fresh exact-revision run. [GitHub required-check commit resolution](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks#required-check-needs-to-succeed-against-the-latest-commit-sha) Review the changed head before approving its validation workflows. Confirm the PR is ready for review and inspect the workflow jobs to verify the full applicable protected CI ran and passed for the live base and head. If the base changed, run fresh checks against the new base. Recheck the revision pair before the actual merge. Stable publication follows the existing signed merge and release authorization process. diff --git a/docs/development.md b/docs/development.md index 1afb03b0..864248db 100644 --- a/docs/development.md +++ b/docs/development.md @@ -74,8 +74,9 @@ fetches GitHub's PR head, checks the event SHA, 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. Review changes to the hosted workflow before approving each -new external head. +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. `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. diff --git a/docs/local.md b/docs/local.md index bea920f5..9fbcc7f9 100644 --- a/docs/local.md +++ b/docs/local.md @@ -232,11 +232,11 @@ Analysis. Incremental reports are for local use. When the result-size limit requires compact JSON, Markdown still contains all admitted findings and their provenance. -Incremental review and continuation run a verified private copy of OCR. On a -machine with outbound network rules tied to the executable path, an installed -`ocr llm test` can succeed while the private copy times out before a model -response. Check the effective outbound decision for the failed process. Use -`ocr-ci review --local` for a fresh review through the installed binary when +Incremental review and continuation run a verified copy named `ocr` in a private +directory unique to the session. With outbound network rules tied to the +executable path, an installed `ocr llm test` can succeed while the private copy +times out before a model response. Check the outbound decision for that process. +Use `ocr-ci review --local` for a fresh review through the installed binary when that path can reach the provider. A failed run provides no review coverage. ## LLM authentication diff --git a/docs/release.md b/docs/release.md index f068b32f..a747d3a7 100644 --- a/docs/release.md +++ b/docs/release.md @@ -71,11 +71,14 @@ 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. 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. +current head and current `main` base. Before squash merge, verify the exact +intake record for the live release PR, including its number, target, base, head +and current protected policy SHA even when the app-bound check succeeded. +Follow the [protected intake procedure](contributor-intake.md#merging-a-reviewed-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`, @@ -129,7 +132,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. 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 +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/scripts/contributor_intake.py b/scripts/contributor_intake.py index c71db396..97ad808f 100644 --- a/scripts/contributor_intake.py +++ b/scripts/contributor_intake.py @@ -10,7 +10,6 @@ import urllib.error import urllib.parse import urllib.request -from collections import Counter from dataclasses import dataclass from datetime import UTC, datetime from pathlib import Path, PurePosixPath @@ -31,7 +30,10 @@ LOGIN_RE = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})") RELEASE_REF_RE = re.compile(r"release/v([0-9]+\.[0-9]+\.[0-9]+)") ACTION_PIN_RE = re.compile( - r"\s*(?:-\s+)?uses:\s+([\w.-]+/[\w.-]+(?:/[\w./-]+)?)@[0-9a-f]{40}(?:\s+#.*)?\s*" + r"( *(?:- +)?uses: +[\w.-]+/[\w.-]+(?:/[\w./-]+)?@)([0-9a-f]{40})(?: +#[^\r\n]*)? *" +) +HUNK_HEADER_RE = re.compile( + r"@@ -([0-9]{1,10})(?:,([0-9]{1,10}))? \+([0-9]{1,10})(?:,([0-9]{1,10}))? @@(?: .*)?" ) SUPPLY_LINE_RE = re.compile( r"(?:^\s*(?:-\s+)?(?:uses|image|include|index[-_]url|extra[-_]index[-_]url)\s*:" @@ -297,19 +299,45 @@ def ordinary_fork_change(files: list[Any]) -> bool: def only_action_pin_updates(file: dict[str, Any]) -> bool: - changes = patch_lines(file) - if changes is None: + patch = file.get("patch") + if not isinstance(patch, str) or patch_lines(file) is None: return False - actions: list[Counter[str]] = [] - for part in changes: - pins: Counter[str] = Counter() - for line in part: - match = ACTION_PIN_RE.fullmatch(line) - if not match: + next_line = 1 + for hunk in re.split(r"\n(?=@@ )", patch.removesuffix("\n")): + header, *body = hunk.split("\n") + ranges = HUNK_HEADER_RE.fullmatch(header) + if not ranges: + return False + old_start, old_length, new_start, new_length = ranges.groups() + if old_start != new_start or (old_length or "1") != (new_length or "1"): + return False + if int(old_start) < next_line: + return False + count = int(old_length or "1") + next_line = int(old_start) + count + # Keep context positions on both sides so a moved pin cannot pair across them. + previous: list[tuple[str, str] | None] = [] + updated: list[tuple[str, str] | None] = [] + for line in body: + prefix = line[:1] + if prefix == " ": + previous.append(None) + updated.append(None) + elif prefix in {"-", "+"}: + pin = ACTION_PIN_RE.fullmatch(line[1:]) + if not pin: + return False + (previous if prefix == "-" else updated).append((pin[1], pin[2])) + else: + return False + if len(previous) != count or len(updated) != count: + return False + for old, new in zip(previous, updated, strict=True): + if old is None and new is None: + continue + if old is None or new is None or old[0] != new[0] or old[1] == new[1]: return False - pins[match[1]] += 1 - actions.append(pins) - return actions[0] == actions[1] + return True def genuine_dependabot(api: GitHub, pull: PullRequest) -> bool: diff --git a/scripts/ocr_qualification/delivery.py b/scripts/ocr_qualification/delivery.py index 8853f449..db5b4f9b 100644 --- a/scripts/ocr_qualification/delivery.py +++ b/scripts/ocr_qualification/delivery.py @@ -359,8 +359,13 @@ 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" + "- Verify the run has the `ocr-compatibility-chain` artifact and that it contains " + "`ocr-chain-update.patch`. The aggregation job prepares a patch only when the " + "complete observed chain is automatic-safe. A maintainer reviews it and opens the PR.\n" + "- If the patch is missing or expired, 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 classification and artifact before applying the patch.\n" ) return body diff --git a/src/ocr_toolkit/preflight.py b/src/ocr_toolkit/preflight.py index 5fc50b49..098decee 100644 --- a/src/ocr_toolkit/preflight.py +++ b/src/ocr_toolkit/preflight.py @@ -10,7 +10,6 @@ import stat import subprocess import sys -import tempfile import time import urllib.error import urllib.parse @@ -307,35 +306,36 @@ def local_review_executable_qualified( def stage_local_review_executable( executable: str, version: str | None, capability: NativeCapability, session_home: Path ) -> str | None: - """Stage the verified bytes under the private home used for the whole review.""" + """Stage verified bytes as `ocr` under the session's unique private directory.""" assets = qualified_local_review_assets(version, capability) if not assets: return None - staged = None + staged = session_home / "ocr" + descriptor = -1 ready = False try: - with tempfile.NamedTemporaryFile( - mode="w+b", prefix="qualified-ocr-", dir=session_home, delete=False - ) as output: - staged = Path(output.name) + descriptor = os.open(staged, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600) + with os.fdopen(descriptor, "wb", closefd=False) as output: if not _check_local_review_asset(executable, assets, output): return None output.flush() - os.fchmod(output.fileno(), 0o500) - if not os.access(staged, os.X_OK): - return None - ready = True - return str(staged) + os.fchmod(descriptor, 0o500) + ready = os.path.samestat(os.fstat(descriptor), staged.lstat()) and os.access( + staged, os.X_OK + ) + return str(staged) if ready else None except OSError: return None finally: - if staged is not None and not ready: - # The review still owns teardown of the enclosing private home. + if descriptor >= 0: try: - staged.unlink(missing_ok=True) + if not ready and os.path.samestat(os.fstat(descriptor), staged.lstat()): + staged.unlink() except OSError: pass + finally: + os.close(descriptor) def _check_local_review_asset( diff --git a/tests/test_contributor_intake.py b/tests/test_contributor_intake.py index 847ae0a0..25aa8a17 100644 --- a/tests/test_contributor_intake.py +++ b/tests/test_contributor_intake.py @@ -2,12 +2,15 @@ import importlib.util import json +import os +import subprocess import sys from dataclasses import replace from pathlib import Path from typing import Any import pytest +import yaml ROOT = Path(__file__).resolve().parents[1] SPEC = importlib.util.spec_from_file_location( @@ -227,6 +230,100 @@ def test_dependabot_action_changes_are_same_action_pin_updates() -> None: )[0] +def action_patch(patch: str) -> dict[str, Any]: + lines = patch.split("\n") + return { + "filename": ".github/workflows/ci.yml", + "status": "modified", + "patch": patch, + "additions": sum(line.startswith("+") for line in lines), + "deletions": sum(line.startswith("-") for line in lines), + } + + +def test_dependabot_can_update_several_pins_in_place() -> None: + old = f" - uses: org/first@{BASE} # v1" + new = f" - uses: org/first@{HEAD} # v2" + old_second = old.replace("first", "second") + new_second = new.replace("first", "second") + patch = ( + f"@@ -2,2 +2,2 @@\n-{old}\n-{old_second}\n+{new}\n+{new_second}\n" + f"@@ -17 +17 @@ another job\n-{old_second}\n+{new_second}" + ) + pull = replace(bot_pr(), source="dependabot/github_actions/update") + assert gate.admission(comparison(action_patch(patch), commits=[signed_bot_commit()]), pull)[0] + + +@pytest.mark.parametrize("movement", ["reorder", "relocate", "different-hunk", "indent", "old-pin"]) +def test_dependabot_rejects_non_in_place_action_updates(movement: str) -> None: + old = f" - uses: org/first@{BASE} # v1" + new = f" - uses: org/first@{HEAD} # v2" + old_second = old.replace("first", "second") + new_second = new.replace("first", "second") + patches = { + "reorder": f"@@ -2,2 +2,2 @@\n-{old}\n-{old_second}\n+{new_second}\n+{new}", + "relocate": f"@@ -2,2 +2,2 @@\n-{old}\n - run: echo check\n+{new}", + "different-hunk": f"@@ -2 +1,0 @@\n-{old}\n@@ -13,0 +13 @@\n+{new}", + "indent": f"@@ -2 +2 @@\n-{old}\n+ {new}", + "old-pin": f"@@ -2 +2 @@\n-{old}\n+{old.replace('# v1', '# v2')}", + } + pull = replace(bot_pr(), source="dependabot/github_actions/update") + assert not gate.admission( + comparison(action_patch(patches[movement]), commits=[signed_bot_commit()]), pull + )[0] + + +@pytest.mark.parametrize( + "app_id,client_id,private_key,exit_code,enabled", + [ + ("", "", "", 0, False), + ("123", "client-id", "private-key", 0, True), + ("123", "", "", 1, False), + ("", "client-id", "private-key", 1, False), + ("", "", "private-key", 1, False), + ("123", "client-id", "", 1, False), + ("invalid-id", "client-id", "private-key", 1, False), + ], +) +def test_publisher_configuration_is_validated_before_requesting_a_token( + tmp_path: Path, app_id: str, client_id: str, private_key: str, exit_code: int, enabled: bool +) -> None: + workflow = ROOT / ".github/workflows/contributor-intake.yml" + steps = yaml.load(workflow.read_text(), Loader=yaml.BaseLoader)["jobs"]["evaluate"]["steps"] + validation, publisher = ( + next(step for step in steps if step.get("id") == target) + for target in ( + "publisher-config", + "publisher", + ) + ) + assert steps.index(validation) < steps.index(publisher) + assert publisher["if"] == "steps.publisher-config.outputs.enabled == 'true'" + output = tmp_path / "output" + result = subprocess.run( + ["bash", "--noprofile", "--norc", "-eo", "pipefail", "-c", validation["run"]], + env={ + **os.environ, + "GITHUB_OUTPUT": str(output), + "INTAKE_APP_ID": app_id, + "INTAKE_APP_CLIENT_ID": client_id, + "INTAKE_APP_PRIVATE_KEY": private_key, + }, + capture_output=True, + check=False, + text=True, + timeout=10, + ) + assert result.returncode == exit_code + if enabled: + assert output.read_text() == "enabled=true\n" + else: + assert not output.exists() + if exit_code: + assert "or clear all three for advisory mode" in result.stderr + assert "private-key" not in result.stderr + result.stdout + + def pull_json(pull: Any, *, title: str = "Change") -> dict[str, Any]: return { "number": pull.number, diff --git a/tests/test_docs_only_ci.py b/tests/test_docs_only_ci.py index b8e502dc..a36efdb6 100644 --- a/tests/test_docs_only_ci.py +++ b/tests/test_docs_only_ci.py @@ -2,6 +2,8 @@ import importlib.util import os +import secrets +import shutil import subprocess import sys from pathlib import Path @@ -281,12 +283,30 @@ def test_draft_check_contexts_cannot_supply_ready_check_results( assert "pull_request.draft" not in jobs[dependency].get("if", "") -def test_hosted_secrets_scan_fetches_the_exact_pr_without_checking_it_out(tmp_path: Path) -> None: +@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") + synthetic_value = secrets.token_hex(24) + 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") @@ -301,17 +321,20 @@ def test_hosted_secrets_scan_fetches_the_exact_pr_without_checking_it_out(tmp_pa runner_temp = tmp_path / "runner" runner_temp.mkdir() scanner = runner_temp / "gitleaks" - 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' - ) + 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, @@ -322,14 +345,29 @@ def test_hosted_secrets_scan_fetches_the_exact_pr_without_checking_it_out(tmp_pa "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, check=False) + 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() diff --git a/tests/test_native_capabilities.py b/tests/test_native_capabilities.py index d0bcc8e1..490dbb66 100644 --- a/tests/test_native_capabilities.py +++ b/tests/test_native_capabilities.py @@ -2,6 +2,7 @@ import hashlib import os +import stat import pytest from hypothesis import given @@ -121,6 +122,72 @@ def test_reuse_requires_the_exact_verified_executable_bytes(tmp_path, monkeypatc assert not preflight.local_review_executable_qualified(str(binary), version, capability) +def test_staging_uses_the_canonical_basename_and_verified_bytes(tmp_path, monkeypatch): + asset = b"verified bytes" + binary = tmp_path / "release-asset" + binary.write_bytes(asset) + session = tmp_path / "session" + session.mkdir(mode=0o700) + identity = (len(asset), hashlib.sha256(asset).hexdigest()) + capability = "local_review_incremental" + monkeypatch.setitem( + native_capabilities._QUALIFIED_LOCAL_ASSETS, "1.14.9", {capability: frozenset({identity})} + ) + + staged = session / "ocr" + assert preflight.stage_local_review_executable( + str(binary), "1.14.9", capability, session + ) == str(staged) + assert staged.read_bytes() == asset + assert stat.S_IMODE(staged.stat().st_mode) == 0o500 + assert list(session.iterdir()) == [staged] + + other_session = tmp_path / "other-session" + other_session.mkdir(mode=0o700) + binary.write_bytes(b"incorrect byte") + assert ( + preflight.stage_local_review_executable(str(binary), "1.14.9", capability, other_session) + is None + ) + assert list(other_session.iterdir()) == [] + assert staged.read_bytes() == asset + + +@pytest.mark.parametrize("existing", ["file", "symlink", "dangling"]) +def test_staging_preserves_a_preexisting_basename(tmp_path, monkeypatch, existing): + asset = b"verified bytes" + binary = tmp_path / "release-asset" + binary.write_bytes(asset) + session = tmp_path / "session" + session.mkdir(mode=0o700) + identity = (len(asset), hashlib.sha256(asset).hexdigest()) + capability = "local_review_continuation" + monkeypatch.setitem( + native_capabilities._QUALIFIED_LOCAL_ASSETS, "1.14.9", {capability: frozenset({identity})} + ) + target = tmp_path / "existing-target" + staged = session / "ocr" + if existing == "file": + staged.write_bytes(b"existing bytes") + else: + if existing == "symlink": + target.write_bytes(b"existing bytes") + staged.symlink_to(target) + + assert ( + preflight.stage_local_review_executable(str(binary), "1.14.9", capability, session) is None + ) + assert list(session.iterdir()) == [staged] + if existing == "file": + assert staged.read_bytes() == b"existing bytes" + else: + assert staged.readlink() == target + if existing == "symlink": + assert target.read_bytes() == b"existing bytes" + else: + assert not target.exists() + + def test_qualification_closes_descriptor_if_fdopen_fails(tmp_path, monkeypatch): binary = tmp_path / "ocr" binary.write_bytes(b"verified bytes") diff --git a/tests/test_ocr_compat.py b/tests/test_ocr_compat.py index 7cdf3f03..b7b99c7b 100644 --- a/tests/test_ocr_compat.py +++ b/tests/test_ocr_compat.py @@ -1201,7 +1201,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_operations_docs.py b/tests/test_operations_docs.py index 08f784f0..7b98c42c 100644 --- a/tests/test_operations_docs.py +++ b/tests/test_operations_docs.py @@ -908,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 ( diff --git a/tests/test_release_authorization.py b/tests/test_release_authorization.py index 3e04b7dd..b19b2a22 100644 --- a/tests/test_release_authorization.py +++ b/tests/test_release_authorization.py @@ -360,21 +360,26 @@ def test_manual_recovery_verifies_protected_policy_before_checkout( parent = "d" * 40 if scenario == "wrong_parent" else "b" * 40 (tmp_path / "pr.json").write_text(json.dumps(pr)) (tmp_path / "merge.json").write_text(json.dumps(commit_payload("a" * 40, "e" * 40, [parent]))) - fake_gh = tmp_path / "gh" - fake_gh.write_text( + fake_curl = tmp_path / "curl" + fake_curl.write_text( "#!/bin/sh\n" - '[ "$1" = api ] || exit 1\n' - 'case "$2" in\n' - ' "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER") cat pr.json ;;\n' - ' "repos/$GITHUB_REPOSITORY/commits/$MERGE") cat merge.json ;;\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_gh.chmod(0o700) + fake_curl.chmod(0o700) environment = { **os.environ, "PATH": f"{tmp_path}{os.pathsep}{os.environ['PATH']}", "GITHUB_REPOSITORY": repository, + "GH_TOKEN": "synthetic-token", "PR_NUMBER": "5", "VERSION": "0.1.0", "HEAD": "c" * 40, From 04bd76328d8fcd043242633fb044ee8680c21d6e Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:43:09 +0100 Subject: [PATCH 06/25] Preserve the runtime limit for streamed Git metadata --- src/ocr_toolkit/evidence/repository.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/ocr_toolkit/evidence/repository.py b/src/ocr_toolkit/evidence/repository.py index 653d4986..04b99e74 100644 --- a/src/ocr_toolkit/evidence/repository.py +++ b/src/ocr_toolkit/evidence/repository.py @@ -216,10 +216,11 @@ def _run_streamed( timeout: float, text: bool, local_only: bool = False, - max_bytes: int = MAX_GIT_TEXT_BYTES, + max_bytes: int | 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() if local_only: @@ -241,11 +242,11 @@ def _run_streamed( "Git metadata acquisition deadline exceeded" ) for key, _events in selector.select(remaining): - part = os.read(key.fd, min(65_536, max_bytes - len(key.data) + 1)) + 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_bytes: + if len(key.data) + len(part) > limit: raise RepositoryEvidenceError( "Git plumbing output exceeds the bounded byte limit" ) From fe64e757e03e80afe3f29f1f9d7c4e1e0b8a449f Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:51:40 +0100 Subject: [PATCH 07/25] Bind protected admission and release recovery to verified inputs and qualify replay boundaries --- .github/workflows/ci.yml | 57 +++ .github/workflows/contributor-intake.yml | 1 + .github/workflows/release.yml | 28 ++ PLANS.md | 6 + docs/compatibility.md | 18 +- docs/contributor-intake.md | 6 +- docs/development.md | 14 +- docs/local.md | 9 +- docs/release.md | 21 +- docs/review-decision-flow.md | 6 +- scripts/contributor_intake.py | 19 +- scripts/gitleaks.sh | 45 ++- scripts/ocr_qualification/delivery.py | 14 +- scripts/release_authorization.py | 30 +- src/ocr_toolkit/local_incremental.py | 96 ++++- src/ocr_toolkit/local_incremental_replay.py | 11 +- tests/test_contributor_intake.py | 18 + tests/test_docs_only_ci.py | 110 +++++ tests/test_local_incremental.py | 60 +++ tests/test_local_incremental_replay.py | 419 ++++++++++++++++++++ tests/test_ocr_compat.py | 15 + tests/test_quality_script.py | 145 ++++--- tests/test_release_authorization.py | 122 +++++- 23 files changed, 1152 insertions(+), 118 deletions(-) create mode 100644 tests/test_local_incremental_replay.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b927f71f..c09be127 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -102,6 +102,60 @@ jobs: with: fetch-depth: 0 persist-credentials: false + - 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 }} + PR_HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }} + 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 && "${PR_HEAD_REPOSITORY}" != "${GITHUB_REPOSITORY}" ]]; then + pin=$(read_native_pin "${PR_BASE}") + if [[ "$(read_native_pin "${GITHUB_SHA}")" != "${pin}" ]]; then + echo "The recommended OCR version or Linux asset changed. A maintainer must submit the pin update." >&2 + exit 1 + fi + 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: @@ -128,6 +182,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 diff --git a/.github/workflows/contributor-intake.yml b/.github/workflows/contributor-intake.yml index 6e15a738..1eee931f 100644 --- a/.github/workflows/contributor-intake.yml +++ b/.github/workflows/contributor-intake.yml @@ -77,5 +77,6 @@ jobs: env: GH_TOKEN: ${{ github.token }} INTAKE_APP_ID: ${{ vars.INTAKE_APP_ID }} + INTAKE_APP_SLUG: ${{ steps.publisher.outputs.app-slug }} INTAKE_CHECK_TOKEN: ${{ steps.publisher.outputs.token }} run: python3 scripts/contributor_intake.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 25e01f16..e1e63f39 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -83,6 +83,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' + 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: @@ -96,6 +104,14 @@ jobs: 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 \ @@ -195,6 +211,18 @@ jobs: --requested-head "${REQUESTED_HEAD}" \ --requested-base "${REQUESTED_BASE}" \ --github-output "${GITHUB_OUTPUT}" + - name: Require bound intake evidence when configured + env: + INTAKE_VERIFIED: ${{ steps.authorize.outputs.intake-verified }} + run: | + required=$(jq -r ' + [.rules[] | select(.type == "required_status_checks") | + .parameters.required_status_checks[].context] | index("Trusted admission / main") != null + ' /tmp/main-ruleset.json) + if [ "${required}" = true ] && [ "${INTAKE_VERIFIED}" != true ]; then + echo 'The required intake check must be verified by the historical release policy.' >&2 + exit 1 + fi - name: Validate tracked release issues before publication env: GH_TOKEN: ${{ github.token }} diff --git a/PLANS.md b/PLANS.md index f2377e25..e9a735a9 100644 --- a/PLANS.md +++ b/PLANS.md @@ -97,8 +97,14 @@ The maintainer branch integrates #346–350, qualifies OCR 1.14.6 with official 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. +Advisory intake is available for bootstrap evaluation. Retarget external work only after the app-bound required check is active on both branches and its exact decision is verified. + 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. 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. diff --git a/docs/compatibility.md b/docs/compatibility.md index 359da16f..39f17055 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -97,12 +97,18 @@ Classify a pin-only promotion and its machine or human qualification evidence as - `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`. - `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 the `ocr-compatibility-chain` artifact for `ocr-chain-update.patch` -before preparing a maintainer-owned compatibility PR. If the patch is absent -or expired, dispatch from `main` with `tag` and `after_tag` empty and -`qualification_only` off. Set `through_tag` to the last release in the -desired chain. Review the new classification and artifact before applying -the patch. +Check `ocr-chain-assessment.json` and `ocr-chain-update.patch` in the +`ocr-compatibility-chain` artifact before preparing a maintainer-owned +compatibility PR. Use the `assess-complete-chain` job summary if the artifact has +expired. A patch requires a complete automatic-safe chain and successful +candidate jobs. 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. diff --git a/docs/contributor-intake.md b/docs/contributor-intake.md index 45288712..f3e00fce 100644 --- a/docs/contributor-intake.md +++ b/docs/contributor-intake.md @@ -18,8 +18,8 @@ Dependabot's `target-branch: dev` applies to scheduled version updates. GitHub o 1. Land the reviewed maintainer bootstrap through the existing protected `main` procedure before activating the admission rules. In repository Actions settings, require workflow approval for all outside collaborators, retain GitHub-hosted pull-request validation with read-only effective permissions, and turn off automatic merge for intake. Keep publisher credentials and deployment environments restricted to their trusted `main` triggers. [Actions approval 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) 2. Pre-create the `contributor-intake` environment with **Selected branches and tags**, a single branch rule for `main` and no tag rule. Confirm the effective deployment policy before adding any secret. Protect `dev` from force pushes and deletion and require the protected PR and CI rules on it before retargeting any contributor PR. Retain the protected-main signature and release rules. Require current CI for both branches and keep any emergency administrator bypass limited to audited PR recovery. -3. If enabling server-enforced check provenance, register a private dedicated GitHub App with **Checks: read and write** and its implicit **Metadata: read** only. Disable webhooks and install it on this repository alone. Configure its numeric app ID as environment variable `INTAKE_APP_ID`, its client ID as environment variable `INTAKE_APP_CLIENT_ID`, and its private key as environment secret `INTAKE_APP_PRIVATE_KEY`. The workflow checks all three settings before requesting a short-lived repository-scoped token with `checks: write`. Leave all three empty for advisory mode. Give this app no ruleset bypass or merge capability. [GitHub App permissions](https://docs.github.com/en/apps/creating-github-apps/registering-a-github-app/choosing-permissions-for-a-github-app) -4. Observe the app publish `Trusted admission / dev` and `Trusted admission / main`. Configure the matching required check on each branch's ruleset with the dedicated app's numeric `integration_id` and verify the effective rules on both refs. The stable release authorizer verifies each required check's app, name, reviewed head and conclusion. The [intake record check below](#merging-a-reviewed-pr) is mandatory before merging every PR, including stable release PRs with a successful app-bound required check. If the applicable GitHub settings cannot require the check from the app, the protected-main workflow provides the advisory admission record for the same maintainer verification. [Selecting the source of a required status check](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets#require-status-checks-to-pass-before-merging) +3. For protected contributor intake, register a private dedicated GitHub App with **Checks: read and write** and its implicit **Metadata: read** only. Disable webhooks and install it on this repository alone. Configure its numeric app ID as environment variable `INTAKE_APP_ID`, its client ID as environment variable `INTAKE_APP_CLIENT_ID`, and its private key as environment secret `INTAKE_APP_PRIVATE_KEY`. The workflow checks all three settings before requesting a short-lived repository-scoped token with `checks: write`. It verifies the token's app against `INTAKE_APP_ID` before writing any check. Leave all three empty for advisory mode. Give this app no ruleset bypass or merge capability. [GitHub App permissions](https://docs.github.com/en/apps/creating-github-apps/registering-a-github-app/choosing-permissions-for-a-github-app) +4. Observe the app publish `Trusted admission / dev` and `Trusted admission / main`. Reconcile outstanding historical releases before making admission required on `main`. Configure the matching required check on each branch's ruleset with the dedicated app's numeric `integration_id` and verify the effective rules on both refs. The stable release authorizer verifies each required check's app, name, reviewed head and conclusion. When intake is required, it also verifies the check's exact release PR, target, base, head and protected policy record. The [intake record check below](#merging-a-reviewed-pr) applies before merging every PR, including release PRs. If the applicable GitHub settings cannot require the check from the app, the protected-main workflow provides the advisory admission record for the same maintainer verification. [Historical recovery limits](release.md#external-reconciliation-and-plan-archiving) · [Selecting the source of a required status check](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets#require-status-checks-to-pass-before-merging) 5. Before opening `dev` to contributors, verify an ordinary fork PR targeting `dev`, a fork PR changing a manifest or pin, a mislabeled bot attempt, an external PR targeting `main`, genuine Dependabot retargeted to `dev`, a maintainer update, and a repository `dev` promotion to `main`. Confirm a changed head or base needs fresh evidence, a draft remains ineligible, and Ready for review runs new full validation. For the app mode, check the app identity and attempt to satisfy the requirement with a same-named ordinary workflow in a controlled test. Confirm read-only tokens on fork validation and rejection of publication from `dev` before opening intake. Use the existing protected release contracts for the stable route. ## Merging a reviewed PR @@ -30,4 +30,6 @@ Review the changed head before approving its validation workflows. Confirm the P GitHub may omit the PR association for fork CI. Missing, ambiguous or stale CI metadata calls for manual dispatch. Run **Contributor intake policy** from `main` with the open PR number, exact `main` or `dev` target, current full base SHA and reviewed full head SHA. Use a fresh dispatch after a base move or policy update and read the resulting decision for that exact revision. Retargeting, reopening and marking a PR ready start normal PR CI. The automatic intake runs when that CI completes. +Follow the selected manual run in the Actions tab until it completes. GitHub serializes admission runs for the same head and a newer run can replace a pending refresh. If the selected refresh shows **Cancelled**, dispatch it again with the current exact revision and verify the new result. A CI completion with missing PR metadata still calls for a manual refresh. [GitHub Actions concurrency](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency) + Squash-merge eligible fork changes into `dev` with contributor attribution. Promote the reviewed tree using a separate repository-owned `dev` PR into `main`. For a protected squash merge with the CLI, supply the reviewed head as `gh pr merge "$PR_NUMBER" --squash --match-head-commit "$REVIEWED_HEAD"` after confirming the live base. Protect the long-lived `dev` ref and keep it available for subsequent promotions. Enable merge commits for the `dev` synchronization route and retain linear history on `main`. Synchronize `main` back to `dev` after promotion or release through a reviewed signed merge so the next promotion includes the current `main` ancestry. [GitHub CLI merge options](https://cli.github.com/manual/gh_pr_merge) diff --git a/docs/development.md b/docs/development.md index 864248db..12b4ca3a 100644 --- a/docs/development.md +++ b/docs/development.md @@ -43,6 +43,14 @@ not block a Linux-priority release. Bandit scans only the supported runtime pack 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. Fork PRs use the committed target-base pin. +A maintainer PR can exercise a newly qualified pin from its committed candidate. +Native tests use isolated workspaces and synthetic peers. Keep the compatibility +manifest and capability records synchronized when promoting OCR. + 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 @@ -64,8 +72,10 @@ Before every commit, run `scripts/gitleaks.sh --staged` on the intended index. Before every push, run `scripts/gitleaks.sh --tree` and `scripts/gitleaks.sh`, plus 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. The history mode scans the complete first-parent -feature history. Failed or incomplete scanning blocks the commit or push. +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 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 diff --git a/docs/local.md b/docs/local.md index 9fbcc7f9..3b6901dd 100644 --- a/docs/local.md +++ b/docs/local.md @@ -176,12 +176,13 @@ with status 1 after writing the available findings. 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 -checks Python dependencies around edited function bodies. It can narrow a +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 edit with unsupported source -semantics, or a change to the shared selection, context, rules or model can -require a full review. +files that refer to affected keys. Unresolved Markdown links and +unsupported source semantics can require fresh review. Changes to the +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 diff --git a/docs/release.md b/docs/release.md index a747d3a7..73e6fd4f 100644 --- a/docs/release.md +++ b/docs/release.md @@ -78,7 +78,9 @@ Follow the [protected intake procedure](contributor-intake.md#merging-a-reviewed 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. +squash parent and tree against the reviewed pair. When the main ruleset +requires trusted admission, the authorizer verifies the exact admission record +with the historical reviewed main base as its protected policy SHA. The focused release set includes `tests/test_release_authorization.py`, `tests/test_release_receipt.py`, `tests/test_release_notes.py`, @@ -130,10 +132,19 @@ 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. When -a prior dispatch created the receipt, resume through a new recovery dispatch +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 requiring a new context such as +the app-bound `Trusted admission / main` check. When that check is required, +ordinary recovery needs both a matching admission record and a historical +authorizer that verifies its exact tuple. An immutable receipt confirms +publication identity and bytes, and those requirements still apply. + +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 diff --git a/docs/review-decision-flow.md b/docs/review-decision-flow.md index 8acefad0..c03815e2 100644 --- a/docs/review-decision-flow.md +++ b/docs/review-decision-flow.md @@ -151,7 +151,9 @@ flowchart TD 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 --> review + 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 @@ -184,7 +186,7 @@ flowchart TD 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;
label carried findings or record the federated fallback] + mode -- Local --> local_result[Validated receipt-less local result;
revalidate carried findings before delivery;
record the full-review reason on federated runs] 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?} diff --git a/scripts/contributor_intake.py b/scripts/contributor_intake.py index 97ad808f..f6cf0f24 100644 --- a/scripts/contributor_intake.py +++ b/scripts/contributor_intake.py @@ -17,7 +17,8 @@ REPOSITORY = "xeonvs/open-code-review-toolkit" REPOSITORY_ID = 1303814119 -API_URL = f"https://api.github.com/repos/{REPOSITORY}/" +API_ORIGIN = "https://api.github.com" +API_URL = f"{API_ORIGIN}/repos/{REPOSITORY}/" CI_WORKFLOW_ID = 315030197 CI_WORKFLOW_PATH = ".github/workflows/ci.yml" MAX_RESPONSE_BYTES = 4_194_304 @@ -97,8 +98,9 @@ def __init__(self, token: str) -> None: def request( self, endpoint: str, *, method: str = "GET", body: dict[str, Any] | None = None ) -> Any: + url = API_ORIGIN + endpoint if endpoint.startswith("/apps/") else API_URL + endpoint request = urllib.request.Request( - API_URL + endpoint, + url, method=method, data=json.dumps(body).encode() if body is not None else None, headers={ @@ -228,7 +230,12 @@ def is_control_path(path: str) -> bool: return ( path.startswith((".github/", "scripts/", "compatibility/", "examples/gitlab/", ".codex/")) or path.startswith(".release-") - or path in {"src/ocr_toolkit/_version.py", "src/ocr_toolkit/preflight.py"} + or path + in { + "src/ocr_toolkit/_qualified_handoffs.json", + "src/ocr_toolkit/_version.py", + "src/ocr_toolkit/preflight.py", + } or name in CONTROL_FILES or name.startswith(("dockerfile", "containerfile", "requirements", "constraints")) or name.endswith((".lock", "-lock.json", "-lock.yaml", "-lock.yml", ".lock.json")) @@ -547,6 +554,12 @@ def publish(api: GitHub, pull: PullRequest, policy: str, approved: bool, message app_id = os.environ.get("INTAKE_APP_ID", "") if not re.fullmatch(r"[1-9][0-9]{0,11}", app_id): raise IntakeError("check publisher numeric app ID is missing or malformed") + app_slug = os.environ.get("INTAKE_APP_SLUG", "") + if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,99}", app_slug): + raise IntakeError("check publisher app slug is missing or malformed") + app = as_object(api.request(f"/apps/{app_slug}")) + if app.get("slug") != app_slug or as_count(app.get("id"), minimum=1) != int(app_id): + raise IntakeError("check publisher app identity does not match INTAKE_APP_ID") checks = as_object(api.request(f"commits/{pull.head}/check-runs?{query}&app_id={app_id}")) runs = checks.get("check_runs") if not isinstance(runs, list) or checks.get("total_count") != len(runs) or len(runs) > 1: 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/ocr_qualification/delivery.py b/scripts/ocr_qualification/delivery.py index db5b4f9b..8b8cbebf 100644 --- a/scripts/ocr_qualification/delivery.py +++ b/scripts/ocr_qualification/delivery.py @@ -359,13 +359,17 @@ 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 += ( - "- Verify the run has the `ocr-compatibility-chain` artifact and that it contains " - "`ocr-chain-update.patch`. The aggregation job prepares a patch only when the " - "complete observed chain is automatic-safe. A maintainer reviews it and opens the PR.\n" - "- If the patch is missing or expired, dispatch **OCR compatibility** from `main`. " + "- Check `ocr-chain-assessment.json` in the `ocr-compatibility-chain` artifact. " + "Use the `assess-complete-chain` job summary if the artifact has expired. " + "The aggregation job prepares `ocr-chain-update.patch` only after all " + "candidate jobs succeed and the complete observed chain is automatic-safe. " + "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 classification and artifact before applying the patch.\n" + "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..5590a5bf 100644 --- a/scripts/release_authorization.py +++ b/scripts/release_authorization.py @@ -13,6 +13,7 @@ COMMIT_RE = re.compile(r"^[0-9a-f]{40}$") VERSION_RE = re.compile(r"^[0-9]+(?:\.[0-9]+)+$") RELEASE_METADATA_SCHEMA = "ocr-toolkit.release-authorization/v1" +INTAKE_CHECK_CONTEXT = "Trusted admission / main" class AuthorizationError(ValueError): @@ -150,8 +151,12 @@ def _required_checks(ruleset: dict[str, Any]) -> dict[tuple[str, int], None]: def _validate_check_runs( - checks_payload: dict[str, Any], ruleset: dict[str, Any], expected_head: str -) -> None: + checks_payload: dict[str, Any], + ruleset: dict[str, Any], + expected_head: str, + *, + expected_intake: str, +) -> bool: """Require one complete exact-app run for every live ruleset context.""" required = _required_checks(ruleset) @@ -185,10 +190,15 @@ def _validate_check_runs( ) if run.get("status") != "completed" or run.get("conclusion") != "success": raise AuthorizationError(f"reviewed head has unsuccessful required check: {identity}") + if name == INTAKE_CHECK_CONTEXT and run.get("external_id") != expected_intake: + raise AuthorizationError( + "required admission check does not match the reviewed release PR tuple" + ) matched[identity] = None missing = [identity for identity in required if identity not in matched] if missing: raise AuthorizationError(f"reviewed head is missing required checks: {missing}") + return any(name == INTAKE_CHECK_CONTEXT for name, _ in matched) def authorize_release( @@ -239,7 +249,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") @@ -257,9 +267,16 @@ def authorize_release( if merge_parents != [base_sha]: raise AuthorizationError("release merge parent does not match the reviewed base") issues = _release_metadata(_release_metadata_contents(release_metadata_contents), version) - _validate_check_runs(check_runs_payload, ruleset_payload, head_sha) + intake_verified = _validate_check_runs( + check_runs_payload, + ruleset_payload, + head_sha, + # A main-target intake run verifies that its policy SHA equals the live + # main base. On recovery that same SHA is the historical reviewed base. + expected_intake=f"{number}:main:{base_sha}:{head_sha}:{base_sha}", + ) - return { + outputs = { "approved": "true", "branch": branch, "commit": commit, @@ -272,6 +289,9 @@ def authorize_release( "title": title, "version": version, } + if intake_verified: + outputs["intake-verified"] = "true" + return outputs def main() -> int: diff --git a/src/ocr_toolkit/local_incremental.py b/src/ocr_toolkit/local_incremental.py index 7caf5bb7..f9691756 100644 --- a/src/ocr_toolkit/local_incremental.py +++ b/src/ocr_toolkit/local_incremental.py @@ -5,15 +5,17 @@ import ast import hashlib import hmac +import posixpath import re import sys from collections import Counter -from collections.abc import Collection, Sequence +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 @@ -21,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 @@ -88,7 +91,9 @@ _DYNAMIC_BINDINGS = {"__builtins__", "__import__", "exec", "eval"} _PYTHON_SUFFIXES = {".py", ".pyw", ".pyi"} _PYTHON_SHEBANG = re.compile(r"\bpython(?:[0-9.]*)\b") -_DATA_SUFFIXES = {".json", ".markdown", ".md"} +_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( { @@ -476,6 +481,58 @@ def _text_references(text: str, module: _PythonModule | None) -> frozenset[str]: 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, tree: Mapping[str, RepositoryObject]) -> set[str]: + """Resolve local CommonMark links and references without accessing their targets.""" + + try: + markup = interpret_markdown(text) + if ( + "[[" in text + or "{{" in text + or any(item.lstrip().startswith("<") for item in markup.hidden) + ): + raise IncrementalError("Markdown dependency syntax is ambiguous") + references = set() + for value in markup.links: + destination = urlsplit(value) + if destination.scheme in _EXTERNAL_LINK_SCHEMES or ( + destination.netloc and not destination.scheme + ): + continue + if destination.scheme: + raise IncrementalError("Markdown link scope is ambiguous") + 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) + ) + entry = tree.get(resolved) + if ( + target.endswith("/") + or not literal_path(resolved) + or entry is None + or not _regular(entry) + ): + raise IncrementalError("Markdown link path is ambiguous") + references.update((resolved.casefold(), posixpath.basename(resolved).casefold())) + return references + except (ValueError, RepresentationLimit, RecursionError) as exc: + raise IncrementalError("Markdown dependency syntax could not be qualified") from exc + + def _json_interface(value: object, names: set[str]) -> object: if isinstance(value, dict): for key in value: @@ -488,8 +545,6 @@ def _json_interface(value: object, names: set[str]) -> object: def _data_edit_bindings(path: str, previous: str, current: str) -> set[str]: suffix = PurePosixPath(path).suffix.lower() - if suffix not in _DATA_SUFFIXES: - raise IncrementalError("a changed file has unsupported shared source semantics") names: set[str] = set() if suffix == ".json": prior_json, current_json = (unique_json(text.encode()) for text in (previous, current)) @@ -507,13 +562,17 @@ 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.""" + 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: @@ -522,6 +581,13 @@ def _independent_paths( 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: + try: + references[path] |= _markdown_references(path, text, current_tree) + except IncrementalError: + uncertain.add(path) bindings = { path: {name.casefold() for name in _binding_tokens(path)} | (set(modules[path].declared) if path in modules else set()) @@ -535,6 +601,12 @@ def _independent_paths( 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: + previous_references[path] |= _markdown_references(path, previous_text, current_tree) bindings[path].update(_data_edit_bindings(path, previous_text, changed_texts[path])) json_changed |= PurePosixPath(path).suffix.lower() == ".json" continue @@ -568,9 +640,7 @@ 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, ) @@ -582,11 +652,7 @@ def load_imports(path: str) -> tuple[tuple[StaticImport, ...], bool]: changes = set(changed) if json_changed: # A selected program may load JSON implicitly without naming the file. - changes.update( - path - for path in selected - if path in modules or PurePosixPath(path).suffix.lower() not in _DATA_SUFFIXES - ) + changes.update(selected - data_paths) active = set(changes) while active: identifiers = set().union(*(bindings[path] for path in active)) @@ -601,7 +667,7 @@ def load_imports(path: str) -> tuple[tuple[StaticImport, ...], bool]: if dependencies is not None: active = (dependencies.dependants(active) & selected) - changes changes.update(active) - return selected - changes - unconfirmed + return selected - changes - unconfirmed - uncertain def _manifest_paths(coverage: dict[str, Any], key: str) -> dict[str, tuple[str, str]]: @@ -757,7 +823,7 @@ 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." diff --git a/src/ocr_toolkit/local_incremental_replay.py b/src/ocr_toolkit/local_incremental_replay.py index fefc2550..66e593f0 100644 --- a/src/ocr_toolkit/local_incremental_replay.py +++ b/src/ocr_toolkit/local_incremental_replay.py @@ -223,10 +223,19 @@ def _execute(self, tool: str, args: dict[str, Any]) -> str: 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") - parts.append(f"==== FILE: {path} ====\n{self._diffs[path]}\n") + 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 diff --git a/tests/test_contributor_intake.py b/tests/test_contributor_intake.py index 25aa8a17..458c7c39 100644 --- a/tests/test_contributor_intake.py +++ b/tests/test_contributor_intake.py @@ -107,6 +107,7 @@ def test_fork_routes_depend_on_repository_identity_and_exact_target() -> None: [ change("uv.lock", status="added", old=""), change("pyproject.toml", status="removed", new=""), + change("src/ocr_toolkit/_qualified_handoffs.json", old='"size": 1', new='"size": 2'), change(".python-version", old="3.14", new="3.15"), change(".tool-versions", old="uv 0.13.8", new="uv 0.13.10"), change("new-file.txt", status="renamed", old="", new="", previous_filename="uv.lock"), @@ -358,6 +359,7 @@ def test_app_published_result_names_target_and_identifies_pr_base_head_and_polic ) -> None: pull = candidate() monkeypatch.setenv("INTAKE_APP_ID", "888") + monkeypatch.setenv("INTAKE_APP_SLUG", "intake-publisher") def post(*, method: str, body: dict[str, Any]) -> dict[str, Any]: assert method == "POST" @@ -368,6 +370,7 @@ def post(*, method: str, body: dict[str, Any]) -> dict[str, Any]: api = Api( { + "/apps/intake-publisher": {"slug": "intake-publisher", "id": 888}, f"commits/{HEAD}/check-runs?check_name=Trusted+admission+%2F+dev&filter=latest&per_page=100&app_id=888": { "total_count": 0, "check_runs": [], @@ -383,6 +386,7 @@ def test_app_refresh_updates_the_existing_same_revision_check( ) -> None: pull = replace(candidate(), target="main", source_repo=gate.REPOSITORY_ID, source="dev") monkeypatch.setenv("INTAKE_APP_ID", "888") + monkeypatch.setenv("INTAKE_APP_SLUG", "intake-publisher") existing = {"id": 17, "name": "Trusted admission / main", "head_sha": HEAD, "app": {"id": 888}} def update(*, method: str, body: dict[str, Any]) -> dict[str, Any]: @@ -393,6 +397,7 @@ def update(*, method: str, body: dict[str, Any]) -> dict[str, Any]: api = Api( { + "/apps/intake-publisher": {"slug": "intake-publisher", "id": 888}, f"commits/{HEAD}/check-runs?check_name=Trusted+admission+%2F+main&filter=latest&per_page=100&app_id=888": { "total_count": 1, "check_runs": [existing], @@ -406,6 +411,19 @@ def update(*, method: str, body: dict[str, Any]) -> dict[str, Any]: gate.publish(api, pull, POLICY, True, "Approved.") +def test_publish_rejects_mismatched_app_identity_before_check_write( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("INTAKE_APP_ID", "888") + monkeypatch.setenv("INTAKE_APP_SLUG", "different-app") + api = Api({"/apps/different-app": {"slug": "different-app", "id": 999}}) + with pytest.raises(gate.IntakeError, match="identity does not match INTAKE_APP_ID"): + gate.publish(api, candidate(), POLICY, True, "Approved.") + monkeypatch.setenv("INTAKE_APP_SLUG", "../untrusted") + with pytest.raises(gate.IntakeError, match="slug is missing or malformed"): + gate.publish(Api({}), candidate(), POLICY, True, "Approved.") + + def run_json(pull: Any) -> dict[str, Any]: data = pull_json(pull) return { diff --git a/tests/test_docs_only_ci.py b/tests/test_docs_only_ci.py index a36efdb6..1af62e34 100644 --- a/tests/test_docs_only_ci.py +++ b/tests/test_docs_only_ci.py @@ -1,6 +1,8 @@ """The documentation shortcut is narrow and keeps protected check identities.""" +import hashlib import importlib.util +import json import os import secrets import shutil @@ -283,6 +285,114 @@ def test_draft_check_contexts_cannot_supply_ready_check_results( assert "pull_request.draft" not in jobs[dependency].get("if", "") +@pytest.mark.parametrize( + ("fork", "pin_update", "valid_download", "expected"), + [ + (True, False, True, True), + (True, True, True, False), + (False, True, True, True), + (False, True, False, False), + ], +) +def test_native_coverage_install_checks_the_committed_pin_and_download( + tmp_path: Path, fork: bool, pin_update: bool, valid_download: bool, expected: 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_update else "1.14.5" + 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" "$1" > "$RUNNER_TEMP/requested"\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" + payload = versions[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": "pull_request", + "GITHUB_REPOSITORY": "example/toolkit", + "PR_HEAD_REPOSITORY": "fork/toolkit" if fork else "example/toolkit", + "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{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 expected, result.stderr + assert output.exists() is expected + if expected: + 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 + elif fork and pin_update: + assert not (runner_temp / "requested").exists() + 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 diff --git a/tests/test_local_incremental.py b/tests/test_local_incremental.py index b07a1bec..15409a7c 100644 --- a/tests/test_local_incremental.py +++ b/tests/test_local_incremental.py @@ -749,6 +749,66 @@ def test_json_edit_rechecks_executable_consumers_and_dot_prefixed_file_reference ) +@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"} + + @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" diff --git a/tests/test_local_incremental_replay.py b/tests/test_local_incremental_replay.py new file mode 100644 index 00000000..fb0afb54 --- /dev/null +++ b/tests/test_local_incremental_replay.py @@ -0,0 +1,419 @@ +"""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 [] + ) diff --git a/tests/test_ocr_compat.py b/tests/test_ocr_compat.py index b7b99c7b..69b7c6bc 100644 --- a/tests/test_ocr_compat.py +++ b/tests/test_ocr_compat.py @@ -909,6 +909,21 @@ 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 ( + "candidate jobs succeed and the complete observed chain is automatic-safe" 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 + def test_failed_qualification_status_is_closed_and_consistent() -> None: """Public failure status accepts only reviewed enum values and exact keys.""" diff --git a/tests/test_quality_script.py b/tests/test_quality_script.py index daad69b5..86b671f0 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,110 @@ 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 conflict resolutions with base policy even after the finding is removed.""" + + 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("# trusted base policy\ntrusted.txt:generic-api-key:1\n", encoding="utf-8") + git("add", "tracked.txt", ".gitleaksignore") + git("commit", "-qm", "base") + base = git("rev-parse", "HEAD") + git("switch", "-qc", "feature-side") + tracked.write_text("side update\n", encoding="utf-8") + git("commit", "-qam", "side update") + git("switch", "-q", "main") + 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']}" + completed = subprocess.run( + [wrapper, base, head], 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"], - cwd=repository, - text=True, - ).splitlines()[0] - assert "detect" in arguments - assert f"--no-merges --first-parent {first_feature_commit}^.." in arguments + 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 b19b2a22..d3589d83 100644 --- a/tests/test_release_authorization.py +++ b/tests/test_release_authorization.py @@ -282,6 +282,81 @@ def test_required_checks_must_succeed_from_the_exact_ruleset_app() -> None: authorize(checks=wrong_app) +def intake_rules() -> dict[str, Any]: + protection = ruleset() + protection["rules"][0]["parameters"]["required_status_checks"].append( + {"context": "Trusted admission / main", "integration_id": 4242} + ) + return protection + + +def intake_check(external_id: str | None) -> dict[str, Any]: + checks = check_runs() + checks["total_count"] += 1 + checks["check_runs"].append( + { + "name": "Trusted admission / main", + "head_sha": "c" * 40, + "app": {"id": 4242}, + "status": "completed", + "conclusion": "success", + "external_id": external_id, + } + ) + return checks + + +def test_required_intake_check_matches_the_historical_release_pr_and_base_policy() -> None: + base = "b" * 40 + head = "c" * 40 + checks = intake_check(f"5:main:{base}:{head}:{base}") + assert authorize(checks=checks, protection=intake_rules())["intake-verified"] == "true" + assert "intake-verified" not in authorize(checks=checks) + with pytest.raises(release.AuthorizationError, match="missing required checks"): + authorize(protection=intake_rules()) + + +@pytest.mark.parametrize("part", [None, 0, 1, 2, 3, 4]) +def test_required_intake_rejects_incomplete_or_reused_check(part: int | None) -> None: + identity = ["5", "main", "b" * 40, "c" * 40, "b" * 40] + record = None + if part is not None: + identity[part] = "different" + record = ":".join(identity) + with pytest.raises( + release.AuthorizationError, match="does not match the reviewed release PR tuple" + ): + authorize(checks=intake_check(record), protection=intake_rules()) + + +@pytest.mark.parametrize( + ("required", "proof", "exit_code"), + [(False, "", 0), (True, "true", 0), (True, "", 1)], +) +def test_release_workflow_requires_proof_from_the_historical_authorizer_when_configured( + tmp_path: Path, required: bool, proof: str, exit_code: int +) -> None: + workflow = yaml.load(WORKFLOW.read_text(), Loader=yaml.BaseLoader) + step = next( + step + for step in workflow["jobs"]["authorize"]["steps"] + if step.get("name") == "Require bound intake evidence when configured" + ) + assert step["env"]["INTAKE_VERIFIED"] == "${{ steps.authorize.outputs.intake-verified }}" + rules = tmp_path / "rules.json" + rules.write_text(json.dumps(intake_rules() if required else ruleset())) + command = step["run"].replace("/tmp/main-ruleset.json", f'"{rules}"') + result = subprocess.run( + ["bash", "-e", "-c", command], + env={**os.environ, "INTAKE_VERIFIED": proof}, + capture_output=True, + text=True, + timeout=10, + check=False, + ) + assert result.returncode == exit_code, result.stderr + + @pytest.mark.parametrize("conclusion", ["skipped", "neutral"]) def test_draft_or_skipped_checks_are_not_release_authorization(conclusion: str) -> None: checks = check_runs() @@ -342,24 +417,56 @@ 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"]) +@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"] - gate, checkout = job["steps"][:2] + 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 = "d" * 40 if scenario == "wrong_parent" else "b" * 40 + 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("a" * 40, "e" * 40, [parent]))) + (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" @@ -379,12 +486,13 @@ def test_manual_recovery_verifies_protected_policy_before_checkout( **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": "a" * 40, - "BASE": "d" * 40 if scenario == "wrong_base" else "b" * 40, + "MERGE": merge, + "BASE": dispatch_sha if scenario == "wrong_base" else base, } completed = subprocess.run( ["bash", "-e", "-o", "pipefail", "-c", gate["run"]], @@ -396,6 +504,8 @@ def test_manual_recovery_verifies_protected_policy_before_checkout( 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: From 5f532b248e2c64e21b967ac4e246d291f05dcd93 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:52:34 +0100 Subject: [PATCH 08/25] Verify fork coverage cannot replace the protected OCR checksum --- tests/test_docs_only_ci.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/tests/test_docs_only_ci.py b/tests/test_docs_only_ci.py index 1af62e34..5aa534c8 100644 --- a/tests/test_docs_only_ci.py +++ b/tests/test_docs_only_ci.py @@ -286,16 +286,17 @@ def test_draft_check_contexts_cannot_supply_ready_check_results( @pytest.mark.parametrize( - ("fork", "pin_update", "valid_download", "expected"), + ("fork", "pin_change", "valid_download", "expected"), [ - (True, False, True, True), - (True, True, True, False), - (False, True, True, True), - (False, True, False, False), + (True, "unchanged", True, True), + (True, "version", True, False), + (True, "digest", True, False), + (False, "version", True, True), + (False, "version", False, False), ], ) def test_native_coverage_install_checks_the_committed_pin_and_download( - tmp_path: Path, fork: bool, pin_update: bool, valid_download: bool, expected: bool + tmp_path: Path, fork: bool, pin_change: str, valid_download: bool, expected: bool ) -> None: _git(tmp_path, "init", "-q") _git(tmp_path, "config", "user.email", "test@example.invalid") @@ -322,7 +323,9 @@ def test_native_coverage_install_checks_the_committed_pin_and_download( _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_update else "1.14.5" + 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") @@ -387,7 +390,7 @@ def test_native_coverage_install_checks_the_committed_pin_and_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 - elif fork and pin_update: + elif fork and pin_change != "unchanged": assert not (runner_temp / "requested").exists() else: assert "digest does not match" in result.stderr From 5fd3631023ed322e72864539fadb5d097db29932 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:57:28 +0100 Subject: [PATCH 09/25] Use native GitHub protections and maintainer review for external contributions --- .github/workflows/contributor-intake.yml | 82 --- .github/workflows/release.yml | 12 - PLANS.md | 14 +- docs/contributor-intake.md | 38 +- docs/release.md | 18 +- scripts/contributor_intake.py | 643 ----------------------- scripts/release_authorization.py | 28 +- tests/test_contributor_intake.py | 547 ------------------- tests/test_release_authorization.py | 75 --- 9 files changed, 26 insertions(+), 1431 deletions(-) delete mode 100644 .github/workflows/contributor-intake.yml delete mode 100644 scripts/contributor_intake.py delete mode 100644 tests/test_contributor_intake.py diff --git a/.github/workflows/contributor-intake.yml b/.github/workflows/contributor-intake.yml deleted file mode 100644 index 1eee931f..00000000 --- a/.github/workflows/contributor-intake.yml +++ /dev/null @@ -1,82 +0,0 @@ -name: Contributor intake policy - -on: - workflow_run: - workflows: [CI] - types: [completed] - workflow_dispatch: - inputs: - pull-request-number: - description: Open pull request number - required: true - type: string - target: - description: Exact protected base branch - required: true - type: choice - options: [dev, main] - base: - description: Full current base commit SHA - required: true - type: string - head: - description: Full reviewed head commit SHA - required: true - type: string - -permissions: - actions: read - contents: read - pull-requests: read - -concurrency: - group: intake-${{ github.event.workflow_run.head_sha || inputs.head }} - cancel-in-progress: false - -jobs: - evaluate: - name: Evaluate protected intake policy - if: >- - github.repository == 'xeonvs/open-code-review-toolkit' && github.ref == 'refs/heads/main' && - (github.event_name == 'workflow_dispatch' || - (github.event.workflow_run.workflow_id == 315030197 && github.event.workflow_run.event == 'pull_request')) - runs-on: ubuntu-latest - timeout-minutes: 5 - environment: contributor-intake - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ github.sha }} - persist-credentials: false - - name: Validate optional check publisher configuration - id: publisher-config - shell: bash - env: - INTAKE_APP_ID: ${{ vars.INTAKE_APP_ID }} - INTAKE_APP_CLIENT_ID: ${{ vars.INTAKE_APP_CLIENT_ID }} - INTAKE_APP_PRIVATE_KEY: ${{ secrets.INTAKE_APP_PRIVATE_KEY }} - run: | - if [[ -z "$INTAKE_APP_ID" && -z "$INTAKE_APP_CLIENT_ID" && -z "$INTAKE_APP_PRIVATE_KEY" ]]; then - exit 0 - fi - if [[ ! "$INTAKE_APP_ID" =~ ^[1-9][0-9]{0,11}$ || - ! "$INTAKE_APP_CLIENT_ID" =~ [^[:space:]] || - ! "$INTAKE_APP_PRIVATE_KEY" =~ [^[:space:]] ]]; then - echo 'Configure INTAKE_APP_ID (numeric), INTAKE_APP_CLIENT_ID and INTAKE_APP_PRIVATE_KEY together, or clear all three for advisory mode.' >&2 - exit 1 - fi - echo 'enabled=true' >> "$GITHUB_OUTPUT" - - uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 - id: publisher - if: steps.publisher-config.outputs.enabled == 'true' - with: - client-id: ${{ vars.INTAKE_APP_CLIENT_ID }} - private-key: ${{ secrets.INTAKE_APP_PRIVATE_KEY }} - permission-checks: write - - name: Evaluate GitHub metadata - env: - GH_TOKEN: ${{ github.token }} - INTAKE_APP_ID: ${{ vars.INTAKE_APP_ID }} - INTAKE_APP_SLUG: ${{ steps.publisher.outputs.app-slug }} - INTAKE_CHECK_TOKEN: ${{ steps.publisher.outputs.token }} - run: python3 scripts/contributor_intake.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e1e63f39..8cb9f5bb 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -211,18 +211,6 @@ jobs: --requested-head "${REQUESTED_HEAD}" \ --requested-base "${REQUESTED_BASE}" \ --github-output "${GITHUB_OUTPUT}" - - name: Require bound intake evidence when configured - env: - INTAKE_VERIFIED: ${{ steps.authorize.outputs.intake-verified }} - run: | - required=$(jq -r ' - [.rules[] | select(.type == "required_status_checks") | - .parameters.required_status_checks[].context] | index("Trusted admission / main") != null - ' /tmp/main-ruleset.json) - if [ "${required}" = true ] && [ "${INTAKE_VERIFIED}" != true ]; then - echo 'The required intake check must be verified by the historical release policy.' >&2 - exit 1 - fi - name: Validate tracked release issues before publication env: GH_TOKEN: ${{ github.token }} diff --git a/PLANS.md b/PLANS.md index e9a735a9..96b15f38 100644 --- a/PLANS.md +++ b/PLANS.md @@ -52,7 +52,7 @@ Prepare the full maintainer-owned implementation on `maintainer/0.16.1-intake`, 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. WQ-02 must enforce updater identity from trusted server metadata (maintainer permission or genuine Dependabot app origin, repository and revision), 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. +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/). @@ -67,7 +67,7 @@ At b93ec7d the three changed files cover local opt-in qualification, its tests a | 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 | Land maintainer-owned bootstrap on protected 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 dev protections, runnable Build/CodeQL on dev, and a required base-controlled source/target admission gate. Permit external forks only into dev, maintainer-owned dev promotion and authorized release branches into main. Account explicitly for maintenance bots and bootstrap. Test denial and intended paths before retargeting #354. Synchronize contribution guide and template with rollout. | REQ-002, REQ-005 | in_progress | +| WQ-02 | Land maintainer-owned bootstrap on protected 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 | in_progress | | 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 | @@ -77,15 +77,15 @@ At b93ec7d the three changed files cover local opt-in qualification, its tests a 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 the intake checks. 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). +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. Main requires linear history and a current base; the repository currently disables merge commits. For repeated direct promotions, propose allowing merge commits at repository level while retaining main's squash/rebase restrictions and signed linear history. Permit a reviewed signed main-to-dev synchronization merge on dev 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. Gitleaks policy, version selector and required admission checks must come from trusted policy. 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. +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, external-to-main denial, eligible dev promotion, changed-head reapproval, and dev exclusion from both registry environments. Check release authorization on its existing protected path. Bind the admission gate to policy an external workflow cannot override; a same-named check from any Actions workflow alone is insufficient. 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. +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. @@ -97,7 +97,7 @@ The maintainer branch integrates #346–350, qualifies OCR 1.14.6 with official 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. -Advisory intake is available for bootstrap evaluation. Retarget external work only after the app-bound required check is active on both branches and its exact decision is verified. +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. @@ -117,7 +117,7 @@ The active main ruleset requires PRs, signatures, strict checks and thread resol ### 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 admission checks 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. +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 diff --git a/docs/contributor-intake.md b/docs/contributor-intake.md index f3e00fce..909712e1 100644 --- a/docs/contributor-intake.md +++ b/docs/contributor-intake.md @@ -1,35 +1,15 @@ # Protected contributor intake -External pull requests target `dev` once the maintainer opens it for intake. The protected admission routes into `main` are maintainer promotion from repository-owned `dev` and a maintainer release PR from a repository-owned `release/vX.Y.Z` branch with the matching title. [Contributor guide](../CONTRIBUTING.md) · [Stable release authorization](release.md#stable-release) +## Configure GitHub -The **Contributor intake policy** workflow runs from protected `main` after the repository's PR CI completes, or through an exact-revision manual dispatch. The automatic path checks GitHub's numeric CI workflow identity, workflow path, run attempt and unique PR association. It compares the source repository and branch and both revision SHAs with current GitHub metadata. Candidate files enter the workflow only as REST data. Checkout and execution are limited to the trusted policy, and the optional publisher can write admission checks. This trigger works under GitHub's default public-repository event policy. [GitHub `workflow_run` behavior](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows#workflow_run) · [GitHub public-repository policy](https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target#default-policy-for-pull_request_target) +1. Keep `main` as the default branch. Land the reviewed maintainer bootstrap through the existing protected `main` procedure, then create `dev` from that reviewed state. 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. 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) +2. 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) +3. 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`. Verify fresh PR checks after retargeting to `dev`, a repository-owned promotion, and the absence of publication from `dev` before opening intake. [Release configuration](release.md#required-configuration) · [GitHub deployment environments](https://docs.github.com/en/actions/concepts/workflows-and-actions/deployment-environments) -GitHub's authenticated base-repository metadata establishes the owner of this user-owned repository. For other submitters on repository-owned branches, the read-only installation token queries GitHub's current `admin` or `maintain` role. If GitHub cannot supply those permissions, the collaborator route stays blocked until the lookup recovers or the verified owner prepares and submits the change. [GitHub App metadata permission](https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps#repository-permissions-for-metadata) +## Review and merge a PR -## Dependency ownership +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. 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"`. Protect the long-lived `dev` ref and synchronize it with a reviewed signed merge from `main` before the next promotion when `main` has moved. [GitHub CLI merge options](https://cli.github.com/manual/gh_pr_merge) -Maintainers own dependency manifests and lockfiles, origins and integrity values, Actions and CI configuration, installer scripts, container sources and OCR qualification pins. A contributor can document a needed change and ask a maintainer to prepare the update. The gate checks both paths of a rename or copy, checks additions and removals, and checks changed lines for common installation, source and pin syntax outside the governed paths. Missing or incomplete comparison evidence requires a maintainer-owned revision. This file and text inspection supports a maintainer's review of the full diff and executable paths, including unfamiliar formats or dependencies assembled dynamically. [Dependency audit and upstream review](development.md#dependency-audit-before-push) - -The configured Dependabot app can submit `uv` dependency updates and replace existing GitHub Actions pins in place on `dev`. The replacement preserves each action's path, position and YAML structure. The gate requires GitHub's authenticated Dependabot user ID, a repository-owned updater branch, and a complete linear chain of GitHub-verified Dependabot commits through the PR head. Where GitHub supplies an app ID on the PR, it must be Dependabot's. Labels, branch names and display text carry no independent authority. A bot update still receives the same maintainer review and applicable tests. - -Dependabot's `target-branch: dev` applies to scheduled version updates. GitHub opens Dependabot security updates against the default branch. The maintainer retargets a genuine security update to `dev` for review or prepares 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) - -## Configuration and activation - -1. Land the reviewed maintainer bootstrap through the existing protected `main` procedure before activating the admission rules. In repository Actions settings, require workflow approval for all outside collaborators, retain GitHub-hosted pull-request validation with read-only effective permissions, and turn off automatic merge for intake. Keep publisher credentials and deployment environments restricted to their trusted `main` triggers. [Actions approval 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) -2. Pre-create the `contributor-intake` environment with **Selected branches and tags**, a single branch rule for `main` and no tag rule. Confirm the effective deployment policy before adding any secret. Protect `dev` from force pushes and deletion and require the protected PR and CI rules on it before retargeting any contributor PR. Retain the protected-main signature and release rules. Require current CI for both branches and keep any emergency administrator bypass limited to audited PR recovery. -3. For protected contributor intake, register a private dedicated GitHub App with **Checks: read and write** and its implicit **Metadata: read** only. Disable webhooks and install it on this repository alone. Configure its numeric app ID as environment variable `INTAKE_APP_ID`, its client ID as environment variable `INTAKE_APP_CLIENT_ID`, and its private key as environment secret `INTAKE_APP_PRIVATE_KEY`. The workflow checks all three settings before requesting a short-lived repository-scoped token with `checks: write`. It verifies the token's app against `INTAKE_APP_ID` before writing any check. Leave all three empty for advisory mode. Give this app no ruleset bypass or merge capability. [GitHub App permissions](https://docs.github.com/en/apps/creating-github-apps/registering-a-github-app/choosing-permissions-for-a-github-app) -4. Observe the app publish `Trusted admission / dev` and `Trusted admission / main`. Reconcile outstanding historical releases before making admission required on `main`. Configure the matching required check on each branch's ruleset with the dedicated app's numeric `integration_id` and verify the effective rules on both refs. The stable release authorizer verifies each required check's app, name, reviewed head and conclusion. When intake is required, it also verifies the check's exact release PR, target, base, head and protected policy record. The [intake record check below](#merging-a-reviewed-pr) applies before merging every PR, including release PRs. If the applicable GitHub settings cannot require the check from the app, the protected-main workflow provides the advisory admission record for the same maintainer verification. [Historical recovery limits](release.md#external-reconciliation-and-plan-archiving) · [Selecting the source of a required status check](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets#require-status-checks-to-pass-before-merging) -5. Before opening `dev` to contributors, verify an ordinary fork PR targeting `dev`, a fork PR changing a manifest or pin, a mislabeled bot attempt, an external PR targeting `main`, genuine Dependabot retargeted to `dev`, a maintainer update, and a repository `dev` promotion to `main`. Confirm a changed head or base needs fresh evidence, a draft remains ineligible, and Ready for review runs new full validation. For the app mode, check the app identity and attempt to satisfy the requirement with a same-named ordinary workflow in a controlled test. Confirm read-only tokens on fork validation and rejection of publication from `dev` before opening intake. Use the existing protected release contracts for the stable route. - -## Merging a reviewed PR - -Before merging, fetch the live PR and confirm its number, source repository ID and branch, target branch, current base SHA and reviewed head SHA. Read the current protected `main` SHA, which owns the policy. Require a successful **Contributor intake policy** run from `main` for the live PR number, target, source repository ID, base, head and policy. If an app is configured, verify the `Trusted admission / ` check's app ID and successful conclusion, and match its `external_id` against `::::`. Verify the permitted source branch in the live PR. GitHub evaluates required checks by commit. The maintainer verifies the PR, base and policy values immediately before the manual merge, including for a stable release. Missing or stale evidence requires a fresh exact-revision run. [GitHub required-check commit resolution](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks#required-check-needs-to-succeed-against-the-latest-commit-sha) - -Review the changed head before approving its validation workflows. Confirm the PR is ready for review and inspect the workflow jobs to verify the full applicable protected CI ran and passed for the live base and head. If the base changed, run fresh checks against the new base. Recheck the revision pair before the actual merge. Stable publication follows the existing signed merge and release authorization process. - -GitHub may omit the PR association for fork CI. Missing, ambiguous or stale CI metadata calls for manual dispatch. Run **Contributor intake policy** from `main` with the open PR number, exact `main` or `dev` target, current full base SHA and reviewed full head SHA. Use a fresh dispatch after a base move or policy update and read the resulting decision for that exact revision. Retargeting, reopening and marking a PR ready start normal PR CI. The automatic intake runs when that CI completes. - -Follow the selected manual run in the Actions tab until it completes. GitHub serializes admission runs for the same head and a newer run can replace a pending refresh. If the selected refresh shows **Cancelled**, dispatch it again with the current exact revision and verify the new result. A CI completion with missing PR metadata still calls for a manual refresh. [GitHub Actions concurrency](https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency) - -Squash-merge eligible fork changes into `dev` with contributor attribution. Promote the reviewed tree using a separate repository-owned `dev` PR into `main`. For a protected squash merge with the CLI, supply the reviewed head as `gh pr merge "$PR_NUMBER" --squash --match-head-commit "$REVIEWED_HEAD"` after confirming the live base. Protect the long-lived `dev` ref and keep it available for subsequent promotions. Enable merge commits for the `dev` synchronization route and retain linear history on `main`. Synchronize `main` back to `dev` after promotion or release through a reviewed signed merge so the next promotion includes the current `main` ancestry. [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/release.md b/docs/release.md index 73e6fd4f..a24d4ce7 100644 --- a/docs/release.md +++ b/docs/release.md @@ -71,16 +71,13 @@ 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 exact -intake record for the live release PR, including its number, target, base, head -and current protected policy SHA even when the app-bound check succeeded. -Follow the [protected intake procedure](contributor-intake.md#merging-a-reviewed-pr). +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. When the main ruleset -requires trusted admission, the authorizer verifies the exact admission record -with the historical reviewed main base as its protected policy SHA. +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`, @@ -136,11 +133,8 @@ 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 requiring a new context such as -the app-bound `Trusted admission / main` check. When that check is required, -ordinary recovery needs both a matching admission record and a historical -authorizer that verifies its exact tuple. An immutable receipt confirms -publication identity and bytes, and those requirements still apply. +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 diff --git a/scripts/contributor_intake.py b/scripts/contributor_intake.py deleted file mode 100644 index f6cf0f24..00000000 --- a/scripts/contributor_intake.py +++ /dev/null @@ -1,643 +0,0 @@ -#!/usr/bin/env python3 -"""Evaluate contributor intake using bounded GitHub metadata and immutable diffs.""" - -from __future__ import annotations - -import json -import os -import re -import sys -import urllib.error -import urllib.parse -import urllib.request -from dataclasses import dataclass -from datetime import UTC, datetime -from pathlib import Path, PurePosixPath -from typing import Any - -REPOSITORY = "xeonvs/open-code-review-toolkit" -REPOSITORY_ID = 1303814119 -API_ORIGIN = "https://api.github.com" -API_URL = f"{API_ORIGIN}/repos/{REPOSITORY}/" -CI_WORKFLOW_ID = 315030197 -CI_WORKFLOW_PATH = ".github/workflows/ci.yml" -MAX_RESPONSE_BYTES = 4_194_304 -MAX_COMPARE_FILES = 300 # GitHub truncates the compare result here. -MAX_BOT_COMMITS = 25 -DEPENDABOT = (49699333, "dependabot[bot]", "Bot") -DEPENDABOT_APP_ID = 29110 -GITHUB_WEB_FLOW = (19864447, "web-flow", "User") -SHA_RE = re.compile(r"[0-9a-f]{40}") -LOGIN_RE = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})") -RELEASE_REF_RE = re.compile(r"release/v([0-9]+\.[0-9]+\.[0-9]+)") -ACTION_PIN_RE = re.compile( - r"( *(?:- +)?uses: +[\w.-]+/[\w.-]+(?:/[\w./-]+)?@)([0-9a-f]{40})(?: +#[^\r\n]*)? *" -) -HUNK_HEADER_RE = re.compile( - r"@@ -([0-9]{1,10})(?:,([0-9]{1,10}))? \+([0-9]{1,10})(?:,([0-9]{1,10}))? @@(?: .*)?" -) -SUPPLY_LINE_RE = re.compile( - r"(?:^\s*(?:-\s+)?(?:uses|image|include|index[-_]url|extra[-_]index[-_]url)\s*:" - r"|^\s*(?-i:FROM)\s+|(?:@|\b)sha256:[0-9a-f]{64}\b" - r"|\bgit\+https?://|\s@\s+https?://|/releases/download/" - r"|--(?:extra-)?index-url\b|--find-links\b|--(?:require-)?hash(?:es)?\b" - r"|\b(?:curl|wget|uvx|pipx)\s|\b(?:pip[0-9.]*|uv\s+pip|npm|pnpm|yarn|apt(?:-get)?|brew)" - r"\s+(?:install|add|ci|sync)\b|\buv\s+(?:sync|tool\s+install)\b" - r"|\b(?:docker|podman)\s+(?:pull|build)\b)", - re.IGNORECASE, -) -CONTROL_FILES = frozenset( - { - ".gitmodules", - ".python-version", - ".tool-versions", - "codeowners", - "pyproject.toml", - "setup.py", - "setup.cfg", - "pip.conf", - "pip.ini", - "pipfile", - "uv.toml", - "tox.ini", - "makefile", - "mise.toml", - "justfile", - "package.json", - "npm-shrinkwrap.json", - ".npmrc", - "gemfile", - "go.mod", - "go.sum", - "cargo.toml", - "composer.json", - "pom.xml", - "nuget.config", - "global.json", - "packages.config", - } -) - - -class IntakeError(ValueError): - """GitHub state could not establish an admission result.""" - - -class NoRedirect(urllib.request.HTTPRedirectHandler): - def redirect_request(self, *args: Any, **kwargs: Any) -> None: - return None - - -class GitHub: - def __init__(self, token: str) -> None: - if not token: - raise IntakeError("GitHub API credentials are unavailable") - self.token = token - self.opener = urllib.request.build_opener(NoRedirect()) - - def request( - self, endpoint: str, *, method: str = "GET", body: dict[str, Any] | None = None - ) -> Any: - url = API_ORIGIN + endpoint if endpoint.startswith("/apps/") else API_URL + endpoint - request = urllib.request.Request( - url, - method=method, - data=json.dumps(body).encode() if body is not None else None, - headers={ - "Accept": "application/vnd.github+json", - "Authorization": f"Bearer {self.token}", - "Content-Type": "application/json", - "X-GitHub-Api-Version": "2026-03-10", - }, - ) - try: - with self.opener.open(request, timeout=15) as response: - raw = response.read(MAX_RESPONSE_BYTES + 1) - if len(raw) > MAX_RESPONSE_BYTES: - raise IntakeError("GitHub API response exceeds the intake byte limit") - return json.loads(raw) - except urllib.error.HTTPError as error: - raise IntakeError(f"GitHub API returned HTTP {error.code}") from None - except (OSError, UnicodeDecodeError, json.JSONDecodeError, RecursionError): - raise IntakeError("GitHub API response is unavailable or malformed") from None - - -def as_object(value: Any) -> dict[str, Any]: - if not isinstance(value, dict): - raise IntakeError("GitHub metadata is missing or malformed") - return value - - -def as_count(value: Any, *, minimum: int = 0) -> int: - if type(value) is not int or value < minimum: - raise IntakeError("GitHub metadata contains an invalid count or ID") - return value - - -def as_sha(value: Any) -> str: - if not isinstance(value, str) or not SHA_RE.fullmatch(value): - raise IntakeError("GitHub metadata contains an invalid revision") - return value - - -def identity(value: Any) -> tuple[Any, Any, Any]: - user = as_object(value) - return (user.get("id"), user.get("login"), user.get("type")) - - -@dataclass(frozen=True) -class PullRequest: - number: int - target: str - base: str - source: str - source_repo: int - head: str - author: tuple[Any, Any, Any] - base_owner: tuple[Any, Any, Any] - source_app: int | None - release_title_matches: bool - draft: bool - changed_files: int - commits: int - - @classmethod - def from_api(cls, data: Any) -> PullRequest: - pull = as_object(data) - base = as_object(pull.get("base")) - base_repo = as_object(base.get("repo")) - head = as_object(pull.get("head")) - target = base.get("ref") - source = head.get("ref") - if ( - pull.get("state") != "open" - or base_repo.get("id") != REPOSITORY_ID - or target not in {"main", "dev"} - or not isinstance(source, str) - or not 1 <= len(source) <= 255 - or type(pull.get("draft")) is not bool - ): - raise IntakeError("pull request has no open protected intake route") - app = pull.get("performed_via_github_app") - release = RELEASE_REF_RE.fullmatch(source) - return cls( - number=as_count(pull.get("number"), minimum=1), - target=target, - base=as_sha(base.get("sha")), - source=source, - source_repo=as_count(as_object(head.get("repo")).get("id"), minimum=1), - head=as_sha(head.get("sha")), - author=identity(pull.get("user")), - base_owner=identity(base_repo.get("owner")), - source_app=as_count(as_object(app).get("id"), minimum=1) if app is not None else None, - release_title_matches=bool(release and pull.get("title") == f"Release v{release[1]}"), - draft=pull["draft"], - changed_files=as_count(pull.get("changed_files")), - commits=as_count(pull.get("commits")), - ) - - @property - def proof(self) -> str: - return ( - f"PR #{self.number} into {self.target}, base {self.base}, " - f"head {self.head}, source repository ID {self.source_repo}" - ) - - -def is_maintainer(api: GitHub, pull: PullRequest) -> bool: - account_id, login, account_type = pull.author - if ( - type(account_id) is not int - or account_id < 1 - or account_type != "User" - or not isinstance(login, str) - or not LOGIN_RE.fullmatch(login) - ): - return False - # GitHub's authenticated base-repository owner record establishes ownership - # independently of the collaborator endpoint for this user-owned repository. - if pull.author == pull.base_owner: - return True - permission = as_object(api.request(f"collaborators/{login}/permission")) - # GitHub calls both maintain and write the `write` permission value. - user = as_object(permission.get("user")) if permission.get("user") is not None else {} - return user.get("id") == account_id and permission.get("role_name") in {"admin", "maintain"} - - -def is_control_path(path: str) -> bool: - path = path.casefold() - name = PurePosixPath(path).name - return ( - path.startswith((".github/", "scripts/", "compatibility/", "examples/gitlab/", ".codex/")) - or path.startswith(".release-") - or path - in { - "src/ocr_toolkit/_qualified_handoffs.json", - "src/ocr_toolkit/_version.py", - "src/ocr_toolkit/preflight.py", - } - or name in CONTROL_FILES - or name.startswith(("dockerfile", "containerfile", "requirements", "constraints")) - or name.endswith((".lock", "-lock.json", "-lock.yaml", "-lock.yml", ".lock.json")) - or name.endswith((".sh", ".bash", ".zsh", ".ps1", ".cmd", ".bat", ".csproj", ".props")) - or name.endswith((".gradle", ".gradle.kts", ".gitlab-ci.yml", ".gitlab-ci.yaml")) - or re.search(r"(?:^|[-_.])(?:install|bootstrap)(?:[-_.]|$)", name) is not None - ) - - -def patch_lines(file: dict[str, Any]) -> tuple[list[str], list[str]] | None: - added = as_count(file.get("additions")) - deleted = as_count(file.get("deletions")) - if added == deleted == 0 and file.get("status") == "renamed": - return ([], []) - patch = file.get("patch") - if not isinstance(patch, str) or not patch.startswith("@@ "): - return None - lines = patch.split("\n") - additions = [line[1:] for line in lines if line.startswith("+")] - deletions = [line[1:] for line in lines if line.startswith("-")] - if (len(additions), len(deletions)) != (added, deleted) or added + deleted == 0: - return None - return additions, deletions - - -def path_from(file: dict[str, Any], key: str) -> str: - path = file.get(key) - if not isinstance(path, str) or not path or len(path) > 4096: - raise IntakeError("GitHub comparison contains an invalid path") - return path - - -def compare(api: GitHub, pull: PullRequest, *, accept_bot_commits: bool = False) -> dict[str, Any]: - if not 0 < pull.changed_files < MAX_COMPARE_FILES: - raise IntakeError("GitHub cannot prove the complete nonempty comparison within its limit") - per_page = MAX_BOT_COMMITS if accept_bot_commits else 1 - data = as_object(api.request(f"compare/{pull.base}...{pull.head}?per_page={per_page}")) - files = data.get("files") - if ( - as_object(data.get("base_commit")).get("sha") != pull.base - or not isinstance(files, list) - or len(files) != pull.changed_files - or as_count(data.get("total_commits")) != pull.commits - ): - raise IntakeError("GitHub immutable comparison disagrees with the pull request") - as_sha(as_object(data.get("merge_base_commit")).get("sha")) - names = {path_from(as_object(file), "filename") for file in files} - if len(names) != len(files): - raise IntakeError("GitHub comparison has duplicated paths") - return data - - -def ordinary_fork_change(files: list[Any]) -> bool: - for raw in files: - file = as_object(raw) - status = file.get("status") - if status not in {"added", "modified", "removed", "renamed", "copied"}: - return False - paths = [path_from(file, "filename")] - if status in {"renamed", "copied"} or "previous_filename" in file: - paths.append(path_from(file, "previous_filename")) - if any(is_control_path(path) for path in paths): - return False - changes = patch_lines(file) - if changes is None or any(SUPPLY_LINE_RE.search(line) for part in changes for line in part): - return False - return True - - -def only_action_pin_updates(file: dict[str, Any]) -> bool: - patch = file.get("patch") - if not isinstance(patch, str) or patch_lines(file) is None: - return False - next_line = 1 - for hunk in re.split(r"\n(?=@@ )", patch.removesuffix("\n")): - header, *body = hunk.split("\n") - ranges = HUNK_HEADER_RE.fullmatch(header) - if not ranges: - return False - old_start, old_length, new_start, new_length = ranges.groups() - if old_start != new_start or (old_length or "1") != (new_length or "1"): - return False - if int(old_start) < next_line: - return False - count = int(old_length or "1") - next_line = int(old_start) + count - # Keep context positions on both sides so a moved pin cannot pair across them. - previous: list[tuple[str, str] | None] = [] - updated: list[tuple[str, str] | None] = [] - for line in body: - prefix = line[:1] - if prefix == " ": - previous.append(None) - updated.append(None) - elif prefix in {"-", "+"}: - pin = ACTION_PIN_RE.fullmatch(line[1:]) - if not pin: - return False - (previous if prefix == "-" else updated).append((pin[1], pin[2])) - else: - return False - if len(previous) != count or len(updated) != count: - return False - for old, new in zip(previous, updated, strict=True): - if old is None and new is None: - continue - if old is None or new is None or old[0] != new[0] or old[1] == new[1]: - return False - return True - - -def genuine_dependabot(api: GitHub, pull: PullRequest) -> bool: - ecology = pull.source.split("/", 2) - if ( - pull.source_app not in {None, DEPENDABOT_APP_ID} - or len(ecology) != 3 - or ecology[0] != "dependabot" - or ecology[1] not in {"uv", "github_actions"} - or not 0 < pull.commits <= MAX_BOT_COMMITS - ): - return False - data = compare(api, pull, accept_bot_commits=True) - commits = data.get("commits") - if not isinstance(commits, list) or len(commits) != pull.commits: - return False - parent = as_sha(as_object(data.get("merge_base_commit")).get("sha")) - for raw in commits: - commit = as_object(raw) - verification = as_object(as_object(commit.get("commit")).get("verification")) - parents = commit.get("parents") - if ( - identity(commit.get("author")) != DEPENDABOT - or identity(commit.get("committer")) != GITHUB_WEB_FLOW - or verification.get("verified") is not True - or verification.get("reason") != "valid" - or not verification.get("signature") - or not isinstance(parents, list) - or len(parents) != 1 - or as_object(parents[0]).get("sha") != parent - ): - return False - parent = as_sha(commit.get("sha")) - if parent != pull.head: - return False - for raw in data["files"]: - file = as_object(raw) - name = path_from(file, "filename") - if file.get("status") != "modified" or "previous_filename" in file: - return False - if ecology[1] == "uv": - if name not in {"pyproject.toml", "uv.lock"}: - return False - elif ( - not name.startswith((".github/workflows/", ".github/actions/")) - or not name.endswith((".yml", ".yaml")) - or not only_action_pin_updates(file) - ): - return False - return True - - -def admission(api: GitHub, pull: PullRequest) -> tuple[bool, str]: - if pull.draft: - return False, "Mark the pull request ready for review and run full checks." - if pull.source_repo != REPOSITORY_ID: - if pull.target == "main": - return False, "Fork pull requests target dev." - if not ordinary_fork_change(compare(api, pull)["files"]): - return ( - False, - "A maintainer must submit governed changes or resolve incomplete diff evidence.", - ) - return True, "Ordinary fork change eligible for maintainer review on dev." - - if pull.target == "dev" and pull.author == DEPENDABOT: - if genuine_dependabot(api, pull): - return True, "Verified Dependabot update eligible for maintainer review on dev." - return False, "Dependabot source or revision evidence did not match the repository policy." - if not is_maintainer(api, pull): - return ( - False, - "Repository-owned intake requires a current maintainer or verified Dependabot.", - ) - if pull.target == "dev": - return True, "Maintainer branch eligible for review on dev." - if pull.source == "dev": - return True, "Repository dev promotion eligible for review on main." - if pull.release_title_matches: - return True, "Repository release PR eligible for review on main." - return False, "Main accepts the repository dev branch and the version-matched release route." - - -def branch_sha(api: GitHub, target: str) -> str: - if target not in {"main", "dev"}: - raise IntakeError("intake base must be main or dev") - ref = f"refs/heads/{target}" - live = as_object(api.request(f"git/ref/heads/{target}")) - if live.get("ref") != ref: - raise IntakeError("GitHub returned an unexpected base branch") - return as_sha(as_object(live.get("object")).get("sha")) - - -def verify_policy(api: GitHub) -> str: - policy = as_sha(os.environ.get("GITHUB_SHA")) - if ( - os.environ.get("GITHUB_REPOSITORY") != REPOSITORY - or os.environ.get("GITHUB_REF") != "refs/heads/main" - or branch_sha(api, "main") != policy - ): - raise IntakeError("intake policy is stale or outside protected main; dispatch a fresh run") - return policy - - -@dataclass(frozen=True) -class ExpectedPull: - number: int - target: str - base: str - head: str - source: str | None = None - source_repo: int | None = None - - def matches(self, pull: PullRequest) -> bool: - return ( - (pull.number, pull.target, pull.base, pull.head) - == (self.number, self.target, self.base, self.head) - and (self.source is None or self.source == pull.source) - and (self.source_repo is None or self.source_repo == pull.source_repo) - ) - - def verify_base(self, api: GitHub, policy: str) -> None: - live = policy if self.target == "main" else branch_sha(api, self.target) - if self.base != live: - raise IntakeError("protected base moved; dispatch a fresh exact-revision run") - - -def ci_subject(data: Any) -> tuple[int, int, ExpectedPull]: - run = as_object(data) - if ( - run.get("workflow_id") != CI_WORKFLOW_ID - or run.get("path") != CI_WORKFLOW_PATH - or run.get("event") != "pull_request" - or run.get("status") != "completed" - or as_object(run.get("repository")).get("id") != REPOSITORY_ID - ): - raise IntakeError("completed run is outside the configured pull-request CI workflow") - associations = run.get("pull_requests") - if not isinstance(associations, list) or len(associations) != 1: - raise IntakeError("CI has no unique PR association; dispatch a fresh exact-revision run") - pull = as_object(associations[0]) - base = as_object(pull.get("base")) - head = as_object(pull.get("head")) - source = head.get("ref") - target = base.get("ref") - head_sha = as_sha(head.get("sha")) - source_repo = as_count(as_object(head.get("repo")).get("id"), minimum=1) - if ( - as_object(base.get("repo")).get("id") != REPOSITORY_ID - or target not in {"dev", "main"} - or not isinstance(source, str) - or not 1 <= len(source) <= 255 - or run.get("head_sha") != head_sha - or run.get("head_branch") != source - or as_object(run.get("head_repository")).get("id") != source_repo - ): - raise IntakeError("CI run and PR metadata disagree; dispatch a fresh exact-revision run") - expected = ExpectedPull( - as_count(pull.get("number"), minimum=1), - target, - as_sha(base.get("sha")), - head_sha, - source, - source_repo, - ) - return as_count(run.get("id"), minimum=1), as_count(run.get("run_attempt"), minimum=1), expected - - -def requested_pull(api: GitHub) -> ExpectedPull: - event_path = Path(os.environ["GITHUB_EVENT_PATH"]) - with event_path.open("rb") as payload: - raw = payload.read(MAX_RESPONSE_BYTES + 1) - if len(raw) > MAX_RESPONSE_BYTES: - raise IntakeError("GitHub event exceeds the intake byte limit") - event = as_object(json.loads(raw)) - if as_object(event.get("repository")).get("id") != REPOSITORY_ID: - raise IntakeError("GitHub event is from a different repository") - if os.environ.get("GITHUB_EVENT_NAME") == "workflow_run" and event.get("action") == "completed": - subject = ci_subject(event.get("workflow_run")) - run_id, _, expected = subject - if ci_subject(api.request(f"actions/runs/{run_id}")) != subject: - raise IntakeError( - "CI attempt or PR association changed; dispatch a fresh exact-revision run" - ) - return expected - if os.environ.get("GITHUB_EVENT_NAME") == "workflow_dispatch": - inputs = as_object(event.get("inputs")) - number = inputs.get("pull-request-number") - target = inputs.get("target") - if ( - not isinstance(number, str) - or not re.fullmatch(r"[1-9][0-9]{0,9}", number) - or target not in {"dev", "main"} - ): - raise IntakeError("manual refresh requires an exact PR and protected target") - return ExpectedPull( - int(number), target, as_sha(inputs.get("base")), as_sha(inputs.get("head")) - ) - raise IntakeError("unsupported contributor intake event") - - -def publish(api: GitHub, pull: PullRequest, policy: str, approved: bool, message: str) -> None: - name = f"Trusted admission / {pull.target}" - external_id = f"{pull.number}:{pull.target}:{pull.base}:{pull.head}:{policy}" - output = {"title": message, "summary": f"{pull.proof}\n\nProtected main policy {policy}"} - query = urllib.parse.urlencode({"check_name": name, "filter": "latest", "per_page": 100}) - app_id = os.environ.get("INTAKE_APP_ID", "") - if not re.fullmatch(r"[1-9][0-9]{0,11}", app_id): - raise IntakeError("check publisher numeric app ID is missing or malformed") - app_slug = os.environ.get("INTAKE_APP_SLUG", "") - if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,99}", app_slug): - raise IntakeError("check publisher app slug is missing or malformed") - app = as_object(api.request(f"/apps/{app_slug}")) - if app.get("slug") != app_slug or as_count(app.get("id"), minimum=1) != int(app_id): - raise IntakeError("check publisher app identity does not match INTAKE_APP_ID") - checks = as_object(api.request(f"commits/{pull.head}/check-runs?{query}&app_id={app_id}")) - runs = checks.get("check_runs") - if not isinstance(runs, list) or checks.get("total_count") != len(runs) or len(runs) > 1: - raise IntakeError("check publisher could not identify an unambiguous previous result") - data = { - "name": name, - "status": "completed", - "conclusion": "success" if approved else "failure", - "completed_at": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), - "external_id": external_id, - "output": output, - } - run_id = os.environ.get("GITHUB_RUN_ID", "") - if re.fullmatch(r"[1-9][0-9]{0,15}", run_id): - data["details_url"] = f"https://github.com/{REPOSITORY}/actions/runs/{run_id}" - if runs: - run = as_object(runs[0]) - if ( - run.get("head_sha") != pull.head - or run.get("name") != name - or as_object(run.get("app")).get("id") != int(app_id) - ): - raise IntakeError("previous check did not match the revision or publisher") - check_id = as_count(run.get("id"), minimum=1) - result = api.request(f"check-runs/{check_id}", method="PATCH", body=data) - else: - result = api.request("check-runs", method="POST", body={**data, "head_sha": pull.head}) - published = as_object(result) - if ( - published.get("name") != name - or published.get("head_sha") != pull.head - or published.get("external_id") != external_id - or published.get("status") != "completed" - or published.get("conclusion") != data["conclusion"] - or as_object(published.get("app")).get("id") != int(app_id) - ): - raise IntakeError("published check did not match the intake decision") - - -def main() -> int: - try: - api = GitHub(os.environ.get("GH_TOKEN", "")) - policy = verify_policy(api) - expected = requested_pull(api) - expected.verify_base(api, policy) - endpoint = f"pulls/{expected.number}" - pull = PullRequest.from_api(api.request(endpoint)) - if not expected.matches(pull): - raise IntakeError("pull request changed after the event; dispatch a fresh run") - try: - approved, message = admission(api, pull) - except IntakeError as error: - approved, message = False, str(error) - if PullRequest.from_api(api.request(endpoint)) != pull: - raise IntakeError("pull request changed while being checked; dispatch a fresh run") - policy = verify_policy(api) - expected.verify_base(api, policy) - check_token = os.environ.get("INTAKE_CHECK_TOKEN", "") - if check_token or os.environ.get("INTAKE_APP_ID"): - publish(GitHub(check_token), pull, policy, approved, message) - print(f"{pull.proof}\nProtected main policy {policy}\n{message}") - return 0 if approved else 1 - except ( - IntakeError, - KeyError, - OSError, - UnicodeDecodeError, - json.JSONDecodeError, - RecursionError, - ) as error: - message = ( - str(error) - if isinstance(error, IntakeError) - else "GitHub event is unavailable or malformed" - ) - print(f"Contributor intake could not establish admission. {message}", file=sys.stderr) - return 1 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/release_authorization.py b/scripts/release_authorization.py index 5590a5bf..c79594b6 100644 --- a/scripts/release_authorization.py +++ b/scripts/release_authorization.py @@ -13,7 +13,6 @@ COMMIT_RE = re.compile(r"^[0-9a-f]{40}$") VERSION_RE = re.compile(r"^[0-9]+(?:\.[0-9]+)+$") RELEASE_METADATA_SCHEMA = "ocr-toolkit.release-authorization/v1" -INTAKE_CHECK_CONTEXT = "Trusted admission / main" class AuthorizationError(ValueError): @@ -151,12 +150,8 @@ def _required_checks(ruleset: dict[str, Any]) -> dict[tuple[str, int], None]: def _validate_check_runs( - checks_payload: dict[str, Any], - ruleset: dict[str, Any], - expected_head: str, - *, - expected_intake: str, -) -> bool: + checks_payload: dict[str, Any], ruleset: dict[str, Any], expected_head: str +) -> None: """Require one complete exact-app run for every live ruleset context.""" required = _required_checks(ruleset) @@ -190,15 +185,10 @@ def _validate_check_runs( ) if run.get("status") != "completed" or run.get("conclusion") != "success": raise AuthorizationError(f"reviewed head has unsuccessful required check: {identity}") - if name == INTAKE_CHECK_CONTEXT and run.get("external_id") != expected_intake: - raise AuthorizationError( - "required admission check does not match the reviewed release PR tuple" - ) matched[identity] = None missing = [identity for identity in required if identity not in matched] if missing: raise AuthorizationError(f"reviewed head is missing required checks: {missing}") - return any(name == INTAKE_CHECK_CONTEXT for name, _ in matched) def authorize_release( @@ -267,16 +257,9 @@ def authorize_release( if merge_parents != [base_sha]: raise AuthorizationError("release merge parent does not match the reviewed base") issues = _release_metadata(_release_metadata_contents(release_metadata_contents), version) - intake_verified = _validate_check_runs( - check_runs_payload, - ruleset_payload, - head_sha, - # A main-target intake run verifies that its policy SHA equals the live - # main base. On recovery that same SHA is the historical reviewed base. - expected_intake=f"{number}:main:{base_sha}:{head_sha}:{base_sha}", - ) + _validate_check_runs(check_runs_payload, ruleset_payload, head_sha) - outputs = { + return { "approved": "true", "branch": branch, "commit": commit, @@ -289,9 +272,6 @@ def authorize_release( "title": title, "version": version, } - if intake_verified: - outputs["intake-verified"] = "true" - return outputs def main() -> int: diff --git a/tests/test_contributor_intake.py b/tests/test_contributor_intake.py deleted file mode 100644 index 458c7c39..00000000 --- a/tests/test_contributor_intake.py +++ /dev/null @@ -1,547 +0,0 @@ -from __future__ import annotations - -import importlib.util -import json -import os -import subprocess -import sys -from dataclasses import replace -from pathlib import Path -from typing import Any - -import pytest -import yaml - -ROOT = Path(__file__).resolve().parents[1] -SPEC = importlib.util.spec_from_file_location( - "contributor_intake", ROOT / "scripts/contributor_intake.py" -) -assert SPEC is not None and SPEC.loader is not None -gate = importlib.util.module_from_spec(SPEC) -sys.modules[SPEC.name] = gate -SPEC.loader.exec_module(gate) - -BASE = "a" * 40 -HEAD = "b" * 40 -POLICY = "c" * 40 - - -class Api: - def __init__(self, responses: dict[str, Any]) -> None: - self.responses = responses - - def request(self, endpoint: str, **kwargs: Any) -> Any: - response = self.responses[endpoint] - return response(**kwargs) if callable(response) else response - - -def user(account: tuple[int, str, str]) -> dict[str, Any]: - account_id, login, account_type = account - return {"id": account_id, "login": login, "type": account_type} - - -def candidate() -> Any: - return gate.PullRequest( - number=1, - target="dev", - base=BASE, - source="contribution", - source_repo=456, - head=HEAD, - author=(123, "contributor", "User"), - base_owner=(987, "owner", "User"), - source_app=None, - release_title_matches=False, - draft=False, - changed_files=1, - commits=1, - ) - - -def change( - filename: str, - *, - status: str = "modified", - old: str = "existing_text", - new: str = "revised_text", - **metadata: Any, -) -> dict[str, Any]: - patch = "@@ -1 +1 @@" - if old: - patch += f"\n-{old}" - if new: - patch += f"\n+{new}" - return { - "filename": filename, - "status": status, - "additions": int(bool(new)), - "deletions": int(bool(old)), - "patch": patch, - **metadata, - } - - -def comparison(file: dict[str, Any], *, commits: list[Any] | None = None) -> Api: - data = { - "base_commit": {"sha": BASE}, - "merge_base_commit": {"sha": BASE}, - "total_commits": 1, - "files": [file], - "commits": commits, - } - return Api({f"compare/{BASE}...{HEAD}?per_page={gate.MAX_BOT_COMMITS if commits else 1}": data}) - - -def test_fork_routes_depend_on_repository_identity_and_exact_target() -> None: - fork = candidate() - ordinary = change("src/ocr_toolkit/feature.py", new="from pathlib import Path") - assert gate.admission(comparison(ordinary), fork)[0] - # A maintainer account and reserved ref on a fork confer no promotion authority. - wrong_repo = replace(fork, source="dev", target="main", author=(789, "maintainer", "User")) - assert not gate.admission(Api({}), wrong_repo)[0] - assert not gate.admission(Api({}), replace(fork, draft=True))[0] - - -@pytest.mark.parametrize( - "file", - [ - change("uv.lock", status="added", old=""), - change("pyproject.toml", status="removed", new=""), - change("src/ocr_toolkit/_qualified_handoffs.json", old='"size": 1', new='"size": 2'), - change(".python-version", old="3.14", new="3.15"), - change(".tool-versions", old="uv 0.13.8", new="uv 0.13.10"), - change("new-file.txt", status="renamed", old="", new="", previous_filename="uv.lock"), - change("scripts/setup.sh", status="renamed", previous_filename="src/feature.py"), - change("examples/gitlab/ocr-review.gitlab-ci.yml"), - change(".github/WORKFLOWS/added.yml", status="added", old=""), - change("nested/action.yaml", old=" uses: org/action@reference"), - change("misc/unknown.txt", new="wget https://downloads.example.invalid/app"), - change("misc/unknown.txt", old="git+https://git.example.invalid/project", new=""), - change("misc/file.txt", new=" index-url: https://pypi.example.invalid"), - change("misc/file.txt", new=" --extra-index-url https://pypi.example.invalid"), - change("misc/file.txt", new=" FROM python:3.13"), - {"filename": "file.bin", "status": "modified", "additions": 0, "deletions": 0}, - {**change("file.txt"), "additions": 2}, - ], -) -def test_fork_governed_or_incomplete_change_is_rejected(file: dict[str, Any]) -> None: - assert not gate.admission(comparison(file), candidate())[0] - - -def test_incomplete_or_wrong_comparison_cannot_allow_intake() -> None: - api = comparison(change("file.txt")) - with pytest.raises(gate.IntakeError, match="disagrees"): - gate.admission(api, replace(candidate(), changed_files=2)) - with pytest.raises(gate.IntakeError, match="limit"): - gate.admission(api, replace(candidate(), changed_files=gate.MAX_COMPARE_FILES)) - - -@pytest.mark.parametrize("role, approved", [("admin", True), ("maintain", True), ("write", False)]) -def test_same_repo_dependency_updates_require_current_maintainer_role( - role: str, approved: bool -) -> None: - author = (789, "maintainer", "User") - pull = replace(candidate(), source_repo=gate.REPOSITORY_ID, author=author) - permission = {"role_name": role, "user": user(author)} - assert ( - gate.admission(Api({"collaborators/maintainer/permission": permission}), pull)[0] - is approved - ) - bad_id = {**permission, "user": user((790, "maintainer", "User"))} - assert not gate.admission(Api({"collaborators/maintainer/permission": bad_id}), pull)[0] - - -def test_maintainer_main_routes_require_promotion_or_exact_release() -> None: - author = (789, "maintainer", "User") - api = Api({"collaborators/maintainer/permission": {"role_name": "admin", "user": user(author)}}) - pull = replace(candidate(), target="main", source_repo=gate.REPOSITORY_ID, author=author) - assert gate.admission(api, replace(pull, source="dev"))[0] - assert gate.admission(api, replace(pull, source="release/v0.16.1", release_title_matches=True))[ - 0 - ] - assert not gate.admission(api, replace(pull, source="release/v0.16.1"))[0] - assert not gate.admission(api, replace(pull, source="maintainer/0.16.1-intake"))[0] - assert not gate.admission(api, replace(pull, source="maintainer/other"))[0] - - -def test_repo_owner_is_admitted_from_authenticated_base_metadata_without_collaborator_lookup() -> ( - None -): - pull = replace(candidate(), source_repo=gate.REPOSITORY_ID, target="main", source="dev") - assert gate.admission(Api({}), replace(pull, author=pull.base_owner))[0] - assert not gate.admission(Api({}), replace(pull, author=pull.base_owner, source_repo=9876))[0] - - -def signed_bot_commit() -> dict[str, Any]: - return { - "sha": HEAD, - "author": user(gate.DEPENDABOT), - "committer": user(gate.GITHUB_WEB_FLOW), - "parents": [{"sha": BASE}], - "commit": {"verification": {"verified": True, "reason": "valid", "signature": "signature"}}, - } - - -def bot_pr() -> Any: - return replace( - candidate(), - source_repo=gate.REPOSITORY_ID, - source="dependabot/uv/update", - author=gate.DEPENDABOT, - ) - - -def test_dependabot_requires_authenticated_author_and_verified_exact_head() -> None: - pull = bot_pr() - lock = change("uv.lock") - signed = signed_bot_commit() - api = comparison(lock, commits=[signed]) - assert gate.admission(api, pull)[0] - assert gate.admission(api, replace(pull, source_app=gate.DEPENDABOT_APP_ID))[0] - assert not gate.admission(Api({}), replace(pull, source_app=999))[0] - assert not gate.admission(Api({}), replace(pull, target="main"))[0] - assert not gate.admission(Api({}), replace(pull, author=(1234, "dependabot[bot]", "Bot")))[0] - assert not gate.admission(comparison(lock), replace(pull, source_repo=1234))[0] - assert not gate.admission(comparison(lock, commits=[{**signed, "sha": POLICY}]), pull)[0] - assert not gate.admission( - comparison(lock, commits=[{**signed, "commit": {"verification": {"verified": False}}}]), - pull, - )[0] - assert not gate.admission( - comparison(lock, commits=[{**signed, "parents": [{"sha": POLICY}]}]), pull - )[0] - - -def test_dependabot_action_changes_are_same_action_pin_updates() -> None: - pull = replace(bot_pr(), source="dependabot/github_actions/update") - workflow = ".github/workflows/ci.yml" - old = f" - uses: org/action@{BASE} # v1" - new = f" - uses: org/action@{HEAD} # v2" - files = [ - change(workflow, old=old, new=new), - change(workflow, old=old, new=new.replace("org/", "other/")), - ] - for file, approved in zip(files, (True, False), strict=True): - assert gate.admission(comparison(file, commits=[signed_bot_commit()]), pull)[0] is approved - assert not gate.admission( - comparison( - change(workflow, old=old, new=" - run: echo check"), commits=[signed_bot_commit()] - ), - pull, - )[0] - - -def action_patch(patch: str) -> dict[str, Any]: - lines = patch.split("\n") - return { - "filename": ".github/workflows/ci.yml", - "status": "modified", - "patch": patch, - "additions": sum(line.startswith("+") for line in lines), - "deletions": sum(line.startswith("-") for line in lines), - } - - -def test_dependabot_can_update_several_pins_in_place() -> None: - old = f" - uses: org/first@{BASE} # v1" - new = f" - uses: org/first@{HEAD} # v2" - old_second = old.replace("first", "second") - new_second = new.replace("first", "second") - patch = ( - f"@@ -2,2 +2,2 @@\n-{old}\n-{old_second}\n+{new}\n+{new_second}\n" - f"@@ -17 +17 @@ another job\n-{old_second}\n+{new_second}" - ) - pull = replace(bot_pr(), source="dependabot/github_actions/update") - assert gate.admission(comparison(action_patch(patch), commits=[signed_bot_commit()]), pull)[0] - - -@pytest.mark.parametrize("movement", ["reorder", "relocate", "different-hunk", "indent", "old-pin"]) -def test_dependabot_rejects_non_in_place_action_updates(movement: str) -> None: - old = f" - uses: org/first@{BASE} # v1" - new = f" - uses: org/first@{HEAD} # v2" - old_second = old.replace("first", "second") - new_second = new.replace("first", "second") - patches = { - "reorder": f"@@ -2,2 +2,2 @@\n-{old}\n-{old_second}\n+{new_second}\n+{new}", - "relocate": f"@@ -2,2 +2,2 @@\n-{old}\n - run: echo check\n+{new}", - "different-hunk": f"@@ -2 +1,0 @@\n-{old}\n@@ -13,0 +13 @@\n+{new}", - "indent": f"@@ -2 +2 @@\n-{old}\n+ {new}", - "old-pin": f"@@ -2 +2 @@\n-{old}\n+{old.replace('# v1', '# v2')}", - } - pull = replace(bot_pr(), source="dependabot/github_actions/update") - assert not gate.admission( - comparison(action_patch(patches[movement]), commits=[signed_bot_commit()]), pull - )[0] - - -@pytest.mark.parametrize( - "app_id,client_id,private_key,exit_code,enabled", - [ - ("", "", "", 0, False), - ("123", "client-id", "private-key", 0, True), - ("123", "", "", 1, False), - ("", "client-id", "private-key", 1, False), - ("", "", "private-key", 1, False), - ("123", "client-id", "", 1, False), - ("invalid-id", "client-id", "private-key", 1, False), - ], -) -def test_publisher_configuration_is_validated_before_requesting_a_token( - tmp_path: Path, app_id: str, client_id: str, private_key: str, exit_code: int, enabled: bool -) -> None: - workflow = ROOT / ".github/workflows/contributor-intake.yml" - steps = yaml.load(workflow.read_text(), Loader=yaml.BaseLoader)["jobs"]["evaluate"]["steps"] - validation, publisher = ( - next(step for step in steps if step.get("id") == target) - for target in ( - "publisher-config", - "publisher", - ) - ) - assert steps.index(validation) < steps.index(publisher) - assert publisher["if"] == "steps.publisher-config.outputs.enabled == 'true'" - output = tmp_path / "output" - result = subprocess.run( - ["bash", "--noprofile", "--norc", "-eo", "pipefail", "-c", validation["run"]], - env={ - **os.environ, - "GITHUB_OUTPUT": str(output), - "INTAKE_APP_ID": app_id, - "INTAKE_APP_CLIENT_ID": client_id, - "INTAKE_APP_PRIVATE_KEY": private_key, - }, - capture_output=True, - check=False, - text=True, - timeout=10, - ) - assert result.returncode == exit_code - if enabled: - assert output.read_text() == "enabled=true\n" - else: - assert not output.exists() - if exit_code: - assert "or clear all three for advisory mode" in result.stderr - assert "private-key" not in result.stderr + result.stdout - - -def pull_json(pull: Any, *, title: str = "Change") -> dict[str, Any]: - return { - "number": pull.number, - "state": "open", - "draft": pull.draft, - "title": title, - "user": user(pull.author), - "base": { - "ref": pull.target, - "sha": pull.base, - "repo": {"id": gate.REPOSITORY_ID, "owner": user(pull.base_owner)}, - }, - "head": {"ref": pull.source, "sha": pull.head, "repo": {"id": pull.source_repo}}, - "changed_files": pull.changed_files, - "commits": pull.commits, - "performed_via_github_app": {"id": pull.source_app} - if pull.source_app is not None - else None, - } - - -def test_release_title_must_match_branch_version_exactly() -> None: - pull = replace(candidate(), target="main", source="release/v0.16.1") - assert gate.PullRequest.from_api(pull_json(pull, title="Release v0.16.1")).release_title_matches - assert not gate.PullRequest.from_api( - pull_json(pull, title="Release v0.16.2") - ).release_title_matches - - -def test_app_published_result_names_target_and_identifies_pr_base_head_and_policy( - monkeypatch: pytest.MonkeyPatch, -) -> None: - pull = candidate() - monkeypatch.setenv("INTAKE_APP_ID", "888") - monkeypatch.setenv("INTAKE_APP_SLUG", "intake-publisher") - - def post(*, method: str, body: dict[str, Any]) -> dict[str, Any]: - assert method == "POST" - assert body["name"] == "Trusted admission / dev" - assert body["external_id"] == f"1:dev:{BASE}:{HEAD}:{POLICY}" - assert body["conclusion"] == "failure" - return {**body, "app": {"id": 888}} - - api = Api( - { - "/apps/intake-publisher": {"slug": "intake-publisher", "id": 888}, - f"commits/{HEAD}/check-runs?check_name=Trusted+admission+%2F+dev&filter=latest&per_page=100&app_id=888": { - "total_count": 0, - "check_runs": [], - }, - "check-runs": post, - } - ) - gate.publish(api, pull, POLICY, False, "Denied.") - - -def test_app_refresh_updates_the_existing_same_revision_check( - monkeypatch: pytest.MonkeyPatch, -) -> None: - pull = replace(candidate(), target="main", source_repo=gate.REPOSITORY_ID, source="dev") - monkeypatch.setenv("INTAKE_APP_ID", "888") - monkeypatch.setenv("INTAKE_APP_SLUG", "intake-publisher") - existing = {"id": 17, "name": "Trusted admission / main", "head_sha": HEAD, "app": {"id": 888}} - - def update(*, method: str, body: dict[str, Any]) -> dict[str, Any]: - assert method == "PATCH" - assert body["external_id"] == f"1:main:{BASE}:{HEAD}:{POLICY}" - assert body["conclusion"] == "success" - return {**existing, **body} - - api = Api( - { - "/apps/intake-publisher": {"slug": "intake-publisher", "id": 888}, - f"commits/{HEAD}/check-runs?check_name=Trusted+admission+%2F+main&filter=latest&per_page=100&app_id=888": { - "total_count": 1, - "check_runs": [existing], - }, - "check-runs/17": update, - } - ) - gate.publish(api, pull, POLICY, True, "Approved.") - existing["app"] = {"id": 999} - with pytest.raises(gate.IntakeError, match="previous check did not match"): - gate.publish(api, pull, POLICY, True, "Approved.") - - -def test_publish_rejects_mismatched_app_identity_before_check_write( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.setenv("INTAKE_APP_ID", "888") - monkeypatch.setenv("INTAKE_APP_SLUG", "different-app") - api = Api({"/apps/different-app": {"slug": "different-app", "id": 999}}) - with pytest.raises(gate.IntakeError, match="identity does not match INTAKE_APP_ID"): - gate.publish(api, candidate(), POLICY, True, "Approved.") - monkeypatch.setenv("INTAKE_APP_SLUG", "../untrusted") - with pytest.raises(gate.IntakeError, match="slug is missing or malformed"): - gate.publish(Api({}), candidate(), POLICY, True, "Approved.") - - -def run_json(pull: Any) -> dict[str, Any]: - data = pull_json(pull) - return { - "id": 8, - "run_attempt": 3, - "workflow_id": gate.CI_WORKFLOW_ID, - "path": gate.CI_WORKFLOW_PATH, - "event": "pull_request", - "status": "completed", - "repository": {"id": gate.REPOSITORY_ID}, - "head_repository": {"id": pull.source_repo}, - "head_branch": pull.source, - "head_sha": pull.head, - "pull_requests": [{key: data[key] for key in ("number", "base", "head")}], - } - - -def set_event( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, name: str, payload: dict[str, Any] -) -> Path: - event_path = tmp_path / "event.json" - event_path.write_text(json.dumps({"repository": {"id": gate.REPOSITORY_ID}, **payload})) - monkeypatch.setenv("GITHUB_EVENT_PATH", str(event_path)) - monkeypatch.setenv("GITHUB_EVENT_NAME", name) - return event_path - - -def test_workflow_rechecks_exact_event_and_live_revision_before_publishing( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] -) -> None: - pull = candidate() - run = run_json(pull) - set_event(monkeypatch, tmp_path, "workflow_run", {"action": "completed", "workflow_run": run}) - monkeypatch.setenv("GITHUB_REPOSITORY", gate.REPOSITORY) - monkeypatch.setenv("GITHUB_REF", "refs/heads/main") - monkeypatch.setenv("GITHUB_SHA", POLICY) - monkeypatch.setenv("INTAKE_CHECK_TOKEN", "install-token") - api = comparison(change("src/feature.py")) - api.responses.update( - { - "git/ref/heads/main": {"ref": "refs/heads/main", "object": {"sha": POLICY}}, - "git/ref/heads/dev": {"ref": "refs/heads/dev", "object": {"sha": BASE}}, - "actions/runs/8": run, - "pulls/1": lambda: next(snapshots), - } - ) - snapshots = iter([pull_json(pull), pull_json(replace(pull, head=POLICY))]) - monkeypatch.setattr(gate, "GitHub", lambda _token: api) - assert gate.main() == 1 - assert "changed while being checked" in capsys.readouterr().err - - api.responses["pulls/1"] = pull_json(replace(pull, target="main")) - assert gate.main() == 1 - assert "changed after the event" in capsys.readouterr().err - - api.responses["git/ref/heads/dev"]["object"]["sha"] = HEAD - assert gate.main() == 1 - assert "protected base moved" in capsys.readouterr().err - - api.responses["git/ref/heads/main"]["object"]["sha"] = BASE - assert gate.main() == 1 - assert "policy is stale" in capsys.readouterr().err - - -@pytest.mark.parametrize( - "field,value", - [ - ("workflow_id", 999), - ("path", ".github/workflows/other.yml"), - ("event", "pull_request_target"), - ("status", "queued"), - ("head_repository", {"id": 9999}), - ("head_branch", "different"), - ("head_sha", POLICY), - ("pull_requests", []), - ], -) -def test_ci_requires_exact_workflow_and_immutable_pr_association(field: str, value: Any) -> None: - run = run_json(candidate()) - with pytest.raises(gate.IntakeError): - gate.ci_subject({**run, field: value}) - with pytest.raises(gate.IntakeError, match="no unique PR association"): - gate.ci_subject({**run, "pull_requests": run["pull_requests"] * 2}) - - -def test_no_fork_association_can_be_refreshed_by_exact_manual_dispatch( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] -) -> None: - pull = candidate() - run = {**run_json(pull), "pull_requests": []} - set_event(monkeypatch, tmp_path, "workflow_run", {"action": "completed", "workflow_run": run}) - with pytest.raises(gate.IntakeError, match="no unique PR association"): - gate.requested_pull(Api({})) - - run["pull_requests"] = run_json(pull)["pull_requests"] - set_event(monkeypatch, tmp_path, "workflow_run", {"action": "completed", "workflow_run": run}) - with pytest.raises(gate.IntakeError, match="attempt or PR association changed"): - gate.requested_pull(Api({"actions/runs/8": {**run, "run_attempt": 4}})) - - set_event( - monkeypatch, - tmp_path, - "workflow_dispatch", - {"inputs": {"pull-request-number": "1", "target": "dev", "base": BASE, "head": HEAD}}, - ) - monkeypatch.setenv("GITHUB_REPOSITORY", gate.REPOSITORY) - monkeypatch.setenv("GITHUB_REF", "refs/heads/main") - monkeypatch.setenv("GITHUB_SHA", POLICY) - monkeypatch.delenv("INTAKE_APP_ID", raising=False) - monkeypatch.delenv("INTAKE_CHECK_TOKEN", raising=False) - api = comparison(change("src/feature.py")) - api.responses.update( - { - "git/ref/heads/main": {"ref": "refs/heads/main", "object": {"sha": POLICY}}, - "git/ref/heads/dev": {"ref": "refs/heads/dev", "object": {"sha": BASE}}, - "pulls/1": pull_json(pull), - } - ) - monkeypatch.setattr(gate, "GitHub", lambda _token: api) - assert gate.main() == 0 - assert "eligible for maintainer review on dev" in capsys.readouterr().out diff --git a/tests/test_release_authorization.py b/tests/test_release_authorization.py index d3589d83..17f8d5d1 100644 --- a/tests/test_release_authorization.py +++ b/tests/test_release_authorization.py @@ -282,81 +282,6 @@ def test_required_checks_must_succeed_from_the_exact_ruleset_app() -> None: authorize(checks=wrong_app) -def intake_rules() -> dict[str, Any]: - protection = ruleset() - protection["rules"][0]["parameters"]["required_status_checks"].append( - {"context": "Trusted admission / main", "integration_id": 4242} - ) - return protection - - -def intake_check(external_id: str | None) -> dict[str, Any]: - checks = check_runs() - checks["total_count"] += 1 - checks["check_runs"].append( - { - "name": "Trusted admission / main", - "head_sha": "c" * 40, - "app": {"id": 4242}, - "status": "completed", - "conclusion": "success", - "external_id": external_id, - } - ) - return checks - - -def test_required_intake_check_matches_the_historical_release_pr_and_base_policy() -> None: - base = "b" * 40 - head = "c" * 40 - checks = intake_check(f"5:main:{base}:{head}:{base}") - assert authorize(checks=checks, protection=intake_rules())["intake-verified"] == "true" - assert "intake-verified" not in authorize(checks=checks) - with pytest.raises(release.AuthorizationError, match="missing required checks"): - authorize(protection=intake_rules()) - - -@pytest.mark.parametrize("part", [None, 0, 1, 2, 3, 4]) -def test_required_intake_rejects_incomplete_or_reused_check(part: int | None) -> None: - identity = ["5", "main", "b" * 40, "c" * 40, "b" * 40] - record = None - if part is not None: - identity[part] = "different" - record = ":".join(identity) - with pytest.raises( - release.AuthorizationError, match="does not match the reviewed release PR tuple" - ): - authorize(checks=intake_check(record), protection=intake_rules()) - - -@pytest.mark.parametrize( - ("required", "proof", "exit_code"), - [(False, "", 0), (True, "true", 0), (True, "", 1)], -) -def test_release_workflow_requires_proof_from_the_historical_authorizer_when_configured( - tmp_path: Path, required: bool, proof: str, exit_code: int -) -> None: - workflow = yaml.load(WORKFLOW.read_text(), Loader=yaml.BaseLoader) - step = next( - step - for step in workflow["jobs"]["authorize"]["steps"] - if step.get("name") == "Require bound intake evidence when configured" - ) - assert step["env"]["INTAKE_VERIFIED"] == "${{ steps.authorize.outputs.intake-verified }}" - rules = tmp_path / "rules.json" - rules.write_text(json.dumps(intake_rules() if required else ruleset())) - command = step["run"].replace("/tmp/main-ruleset.json", f'"{rules}"') - result = subprocess.run( - ["bash", "-e", "-c", command], - env={**os.environ, "INTAKE_VERIFIED": proof}, - capture_output=True, - text=True, - timeout=10, - check=False, - ) - assert result.returncode == exit_code, result.stderr - - @pytest.mark.parametrize("conclusion", ["skipped", "neutral"]) def test_draft_or_skipped_checks_are_not_release_authorization(conclusion: str) -> None: checks = check_runs() From 10d67fdca3b9c0062f45867c1342b4e40d85cc5c Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:13:24 +0100 Subject: [PATCH 10/25] Close review gaps in local proof, native CI inputs and maintainer rollout --- .github/workflows/ci.yml | 7 +- .github/workflows/ocr-compatibility.yml | 32 ++++- .github/workflows/security.yml | 1 + PLANS.md | 4 +- docs/compatibility.md | 17 ++- docs/contributor-intake.md | 8 +- docs/development.md | 40 ++++-- docs/local.md | 13 +- docs/review-decision-flow.md | 2 +- scripts/ocr_qualification/delivery.py | 6 +- src/ocr_toolkit/evidence/repository.py | 23 ++-- src/ocr_toolkit/evidence/source_reader.py | 3 + src/ocr_toolkit/local_incremental.py | 65 +++++----- .../local_incremental_dependencies.py | 21 ++- tests/test_docs_only_ci.py | 117 ++++++++++++++--- tests/test_local_incremental.py | 26 ++++ tests/test_local_incremental_replay.py | 120 ++++++++++++++++++ tests/test_ocr_compat.py | 53 +++++++- tests/test_quality_script.py | 29 ++++- 19 files changed, 482 insertions(+), 105 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c09be127..bc5d6ab2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -107,7 +107,6 @@ jobs: if: ${{ needs.classify.outputs.docs_only != 'true' && matrix.coverage }} env: PR_BASE: ${{ github.event.pull_request.base.sha }} - PR_HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }} shell: bash run: | read_native_pin() { @@ -125,12 +124,8 @@ jobs: [$version, .sha256, .size] | @tsv ' } - if [[ "${GITHUB_EVENT_NAME}" == pull_request && "${PR_HEAD_REPOSITORY}" != "${GITHUB_REPOSITORY}" ]]; then + if [[ "${GITHUB_EVENT_NAME}" == pull_request ]]; then pin=$(read_native_pin "${PR_BASE}") - if [[ "$(read_native_pin "${GITHUB_SHA}")" != "${pin}" ]]; then - echo "The recommended OCR version or Linux asset changed. A maintainer must submit the pin update." >&2 - exit 1 - fi else pin=$(read_native_pin "${GITHUB_SHA}") fi diff --git a/.github/workflows/ocr-compatibility.yml b/.github/workflows/ocr-compatibility.yml index c146cbd3..a7e3a977 100644 --- a/.github/workflows/ocr-compatibility.yml +++ b/.github/workflows/ocr-compatibility.yml @@ -50,6 +50,12 @@ jobs: 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 @@ -220,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 }} @@ -252,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 @@ -260,3 +273,20 @@ jobs: /tmp/ocr-chain-update.patch if-no-files-found: error retention-days: 2 + - name: Summarize chain and patch outcomes + if: ${{ !cancelled() && steps.chain.outcome != 'skipped' }} + env: + 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: | + { + printf '\n### Release chain and patch\n\n' + 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/security.yml b/.github/workflows/security.yml index 7c337a7f..fbaec132 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -110,6 +110,7 @@ jobs: - name: Install checksum-pinned Gitleaks without a cache run: | 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 ;; diff --git a/PLANS.md b/PLANS.md index 96b15f38..9e17b24e 100644 --- a/PLANS.md +++ b/PLANS.md @@ -79,7 +79,7 @@ Keep #354 open against its original fork head. The maintainer posted [two reques 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. Main requires linear history and a current base; the repository currently disables merge commits. For repeated direct promotions, propose allowing merge commits at repository level while retaining main's squash/rebase restrictions and signed linear history. Permit a reviewed signed main-to-dev synchronization merge on dev 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. +Protect the long-lived dev ref from automatic deletion. Main requires linear history and a current base; the repository currently disables merge commits. For repeated direct promotions, propose allowing merge commits at repository level while retaining main's squash/rebase restrictions and signed linear history. 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. @@ -121,7 +121,7 @@ Protect dev before admitting any external code. A PR from dev in the same reposi ### Resume Point -Review the maintainer bootstrap draft. Before enabling dev intake or retargeting #354, restrict both registry environments to named main, migrate the site credential, configure protected intake and verify both branch routes using docs/contributor-intake.md. Recheck the contributor head and outstanding requests. +Review the maintainer bootstrap draft. Before creating or protecting dev, restrict the three deployment environments to named main, migrate the site credential and remove its repository-level copy. Then configure protected intake and verify both branch routes using docs/contributor-intake.md. Recheck the contributor head and outstanding requests. ### Plan Fidelity Check diff --git a/docs/compatibility.md b/docs/compatibility.md index 39f17055..c3e6632f 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -94,15 +94,16 @@ 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. Use the `assess-complete-chain` job summary if the artifact has -expired. A patch requires a complete automatic-safe chain and successful -candidate jobs. Investigate failed, missing or human-review-required chain -results through their qualification evidence. +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`. @@ -224,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. -For an automatic-safe result, 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. +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 diff --git a/docs/contributor-intake.md b/docs/contributor-intake.md index 909712e1..444f75ec 100644 --- a/docs/contributor-intake.md +++ b/docs/contributor-intake.md @@ -2,14 +2,14 @@ ## Configure GitHub -1. Keep `main` as the default branch. Land the reviewed maintainer bootstrap through the existing protected `main` procedure, then create `dev` from that reviewed state. 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. 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) -2. 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) -3. 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`. Verify fresh PR checks after retargeting to `dev`, a repository-owned promotion, and the absence of publication from `dev` before opening intake. [Release configuration](release.md#required-configuration) · [GitHub deployment environments](https://docs.github.com/en/actions/concepts/workflows-and-actions/deployment-environments) +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. Land the reviewed maintainer bootstrap through the existing protected `main` procedure, then create `dev` from that reviewed state. 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) Verify the actual draft and ready checks on both routes before opening intake. ## 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. 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"`. Protect the long-lived `dev` ref and synchronize it with a reviewed signed merge from `main` before the next promotion when `main` has moved. [GitHub CLI merge options](https://cli.github.com/manual/gh_pr_merge) +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"`. After a squash promotion, 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 12b4ca3a..2c8d27a0 100644 --- a/docs/development.md +++ b/docs/development.md @@ -46,10 +46,12 @@ 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. Fork PRs use the committed target-base pin. -A maintainer PR can exercise a newly qualified pin from its committed candidate. -Native tests use isolated workspaces and synthetic peers. Keep the compatibility -manifest and capability records synchronized when promoting OCR. +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. Draft pull requests to `main` and `dev` run formatting, lint, type checking, dependency review, and the secret scan under distinct draft check names. @@ -69,25 +71,39 @@ Repository-only qualification tools and evidence live under `scripts/` and `comp 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, run `scripts/gitleaks.sh --tree` and `scripts/gitleaks.sh`, -plus 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 base commit and scans through candidate inline +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 PR head, checks the event SHA, and scans the complete candidate -range as Git objects while leaving the base policy checked out. Trusted base +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 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. diff --git a/docs/local.md b/docs/local.md index 3b6901dd..108a149f 100644 --- a/docs/local.md +++ b/docs/local.md @@ -180,9 +180,10 @@ 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. Unresolved Markdown links and -unsupported source semantics can require fresh review. Changes to the -shared selection, context, rules or model can require a full review. +files that refer to affected keys. An unresolved link or a link outside the +selected files requires fresh review for connected groups. 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 @@ -193,9 +194,9 @@ 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 runs locally before OCR. 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 +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. diff --git a/docs/review-decision-flow.md b/docs/review-decision-flow.md index c03815e2..e72d884b 100644 --- a/docs/review-decision-flow.md +++ b/docs/review-decision-flow.md @@ -186,7 +186,7 @@ flowchart TD 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 carried findings before delivery;
record the full-review reason on federated runs] + 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?} diff --git a/scripts/ocr_qualification/delivery.py b/scripts/ocr_qualification/delivery.py index 8b8cbebf..e9feb44b 100644 --- a/scripts/ocr_qualification/delivery.py +++ b/scripts/ocr_qualification/delivery.py @@ -360,9 +360,11 @@ def render_workflow_issue(evidence: dict[str, Any], run_url: str) -> str: if classification == "automatic-safe": body += ( "- Check `ocr-chain-assessment.json` in the `ocr-compatibility-chain` artifact. " - "Use the `assess-complete-chain` job summary if the artifact has expired. " + "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 and the complete observed chain is automatic-safe. " + "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`. " diff --git a/src/ocr_toolkit/evidence/repository.py b/src/ocr_toolkit/evidence/repository.py index 04b99e74..2f4e2694 100644 --- a/src/ocr_toolkit/evidence/repository.py +++ b/src/ocr_toolkit/evidence/repository.py @@ -49,10 +49,13 @@ 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]: @@ -139,6 +142,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.""" @@ -150,6 +154,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: @@ -203,7 +208,7 @@ def _run( ) -> 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 or local_only: + if self.command_timeout is not None or local_only or self._local_only: return self._run_streamed( args, timeout=self._timeout(timeout), text=text, local_only=local_only ) @@ -222,9 +227,7 @@ def _run_streamed( limit = MAX_GIT_TEXT_BYTES if max_bytes is None else max_bytes command = [*_git_prefix(self.root), *args] - environment = _git_environment() - if local_only: - environment.update(GIT_ALLOW_PROTOCOL="", GIT_NO_LAZY_FETCH="1") + environment = _git_environment(local_only=local_only or self._local_only) output, errors = bytearray(), bytearray() deadline = time.monotonic() + timeout with subprocess.Popen( @@ -379,6 +382,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( [ @@ -670,7 +675,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), @@ -716,7 +721,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( @@ -754,7 +759,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( 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/local_incremental.py b/src/ocr_toolkit/local_incremental.py index f9691756..8e88f40a 100644 --- a/src/ocr_toolkit/local_incremental.py +++ b/src/ocr_toolkit/local_incremental.py @@ -491,26 +491,27 @@ def _data_source(entry: RepositoryObject, text: str) -> bool: ) -def _markdown_references(path: str, text: str, tree: Mapping[str, RepositoryObject]) -> set[str]: +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) - if ( - "[[" in text - or "{{" in text - or any(item.lstrip().startswith("<") for item in markup.hidden) - ): - raise IncrementalError("Markdown dependency syntax is ambiguous") - references = set() - for value in markup.links: + 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: - raise IncrementalError("Markdown link scope is ambiguous") + uncertain = True + continue target = unquote(destination.path, errors="strict") if not target: continue @@ -519,18 +520,13 @@ def _markdown_references(path: str, text: str, tree: Mapping[str, RepositoryObje if target.startswith("/") else posixpath.join(posixpath.dirname(path), target) ) - entry = tree.get(resolved) - if ( - target.endswith("/") - or not literal_path(resolved) - or entry is None - or not _regular(entry) - ): - raise IncrementalError("Markdown link path is ambiguous") - references.update((resolved.casefold(), posixpath.basename(resolved).casefold())) - return references - except (ValueError, RepresentationLimit, RecursionError) as exc: - raise IncrementalError("Markdown dependency syntax could not be qualified") from exc + 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: @@ -584,9 +580,9 @@ def _independent_paths( if module is None and _data_source(current_tree[path], text): data_paths.add(path) if PurePosixPath(path).suffix.lower() in _MARKDOWN_SUFFIXES: - try: - references[path] |= _markdown_references(path, text, current_tree) - except IncrementalError: + 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)} @@ -606,7 +602,10 @@ def _independent_paths( if path in uncertain: raise IncrementalError("a changed Markdown file has ambiguous dependencies") if PurePosixPath(path).suffix.lower() in _MARKDOWN_SUFFIXES: - previous_references[path] |= _markdown_references(path, previous_text, current_tree) + 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 @@ -653,6 +652,7 @@ def load_imports(path: str) -> tuple[tuple[StaticImport, ...], bool]: 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)) @@ -667,7 +667,7 @@ def load_imports(path: str) -> tuple[tuple[StaticImport, ...], bool]: if dependencies is not None: active = (dependencies.dependants(active) & selected) - changes changes.update(active) - return selected - changes - unconfirmed - uncertain + return selected - changes - unconfirmed def _manifest_paths(coverage: dict[str, Any], key: str) -> dict[str, tuple[str, str]]: @@ -762,6 +762,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} @@ -1089,7 +1090,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") @@ -1124,7 +1127,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(): @@ -1234,7 +1237,9 @@ 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() diff --git a/src/ocr_toolkit/local_incremental_dependencies.py b/src/ocr_toolkit/local_incremental_dependencies.py index da6992e4..e7fc9bd2 100644 --- a/src/ocr_toolkit/local_incremental_dependencies.py +++ b/src/ocr_toolkit/local_incremental_dependencies.py @@ -208,6 +208,8 @@ class _GroupObservation: 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) @@ -313,6 +315,8 @@ def _requested_tools(value: object, group: _GroupObservation) -> None: 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") @@ -322,6 +326,12 @@ def _tool(self, record: dict[str, Any], group: _GroupObservation) -> None: 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.reasons.add("diagram") @@ -462,12 +472,18 @@ def all_unqualified(reason: str) -> DependencyAssessment: warnings = payload.get("warnings", []) if ( any( - "comment_attribution" in group.reasons or group.comment_paths - set(groups[key]) + "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 "comment_refiled" in warning.values() + not isinstance(warning, dict) + or any( + name in warning.values() + for name in ("comment_refiled", "comment_args_repaired") + ) for warning in warnings ) ): @@ -512,6 +528,7 @@ def all_unqualified(reason: str) -> DependencyAssessment: 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") diff --git a/tests/test_docs_only_ci.py b/tests/test_docs_only_ci.py index 5aa534c8..ab10e176 100644 --- a/tests/test_docs_only_ci.py +++ b/tests/test_docs_only_ci.py @@ -286,17 +286,16 @@ def test_draft_check_contexts_cannot_supply_ready_check_results( @pytest.mark.parametrize( - ("fork", "pin_change", "valid_download", "expected"), + ("event", "pin_change", "valid_download"), [ - (True, "unchanged", True, True), - (True, "version", True, False), - (True, "digest", True, False), - (False, "version", True, True), - (False, "version", False, False), + ("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, fork: bool, pin_change: str, valid_download: bool, expected: bool + 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") @@ -343,7 +342,6 @@ def test_native_coverage_install_checks_the_committed_pin_and_download( " shift\n" "done\n" 'test "$1" = "$EXPECTED_URL"\n' - 'printf "%s" "$1" > "$RUNNER_TEMP/requested"\n' 'printf "%s" "$ASSET_BYTES" > "$out"\n' 'printf "%s" "$1"\n' ) @@ -359,23 +357,22 @@ def test_native_coverage_install_checks_the_committed_pin_and_download( } output = runner_temp / "output" - payload = versions[version].decode() + 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": "pull_request", - "GITHUB_REPOSITORY": "example/toolkit", - "PR_HEAD_REPOSITORY": "fork/toolkit" if fork else "example/toolkit", + "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{version}/opencodereview-linux-amd64" + f"v{selected_version}/opencodereview-linux-amd64" ), "ASSET_BYTES": payload if valid_download else payload.replace("verified", "modified"), }, @@ -384,14 +381,12 @@ def test_native_coverage_install_checks_the_committed_pin_and_download( timeout=10, check=False, ) - assert (result.returncode == 0) is expected, result.stderr - assert output.exists() is expected - if expected: + 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 - elif fork and pin_change != "unchanged": - assert not (runner_temp / "requested").exists() else: assert "digest does not match" in result.stderr @@ -484,6 +479,92 @@ def test_hosted_secrets_scan_fetches_the_exact_pr_without_checking_it_out( 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_local_incremental.py b/tests/test_local_incremental.py index 15409a7c..ff4e523d 100644 --- a/tests/test_local_incremental.py +++ b/tests/test_local_incremental.py @@ -809,6 +809,32 @@ def test_markdown_rechecks_resolved_or_ambiguous_link_dependencies(tmp_path, lin ) == {"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" diff --git a/tests/test_local_incremental_replay.py b/tests/test_local_incremental_replay.py index fb0afb54..ad61701a 100644 --- a/tests/test_local_incremental_replay.py +++ b/tests/test_local_incremental_replay.py @@ -417,3 +417,123 @@ def tool_call(tool, args, result, *, ok=True): 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_ocr_compat.py b/tests/test_ocr_compat.py index 69b7c6bc..a34114d5 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 @@ -917,14 +918,64 @@ def test_issue_body_uses_stable_marker_and_safe_release_changes() -> None: workflow_body = module.delivery.render_workflow_issue(evidence, run_url) assert "`ocr-chain-assessment.json`" in workflow_body assert ( - "candidate jobs succeed and the complete observed chain is automatic-safe" in workflow_body + "`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["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, + "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()[-5:] == [ + 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.""" diff --git a/tests/test_quality_script.py b/tests/test_quality_script.py index 86b671f0..5ab11996 100644 --- a/tests/test_quality_script.py +++ b/tests/test_quality_script.py @@ -255,7 +255,7 @@ def test_quality_script_preserves_failure_status_and_stops( def test_gitleaks_wrapper_scans_the_complete_feature_history( tmp_path: Path, real_scanner: bool ) -> None: - """Scan conflict resolutions with base policy even after the finding is removed.""" + """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() @@ -277,14 +277,22 @@ def git(*args: str) -> str: tracked = repository / "tracked.txt" tracked.write_text("base\n", encoding="utf-8") ignore = repository / ".gitleaksignore" - ignore.write_text("# trusted base policy\ntrusted.txt:generic-api-key:1\n", encoding="utf-8") + ignore.write_text("tracked.txt:generic-api-key:1\n", encoding="utf-8") git("add", "tracked.txt", ".gitleaksignore") - git("commit", "-qm", "base") + 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", "main") + git("switch", "-q", "feature") tracked.write_text("first-parent update\n", encoding="utf-8") git("commit", "-qam", "first-parent update") conflict = subprocess.run( @@ -333,8 +341,19 @@ def git(*args: str) -> str: ) fake_gitleaks.chmod(0o755) environment["PATH"] = f"{binary_dir}{os.pathsep}{environment['PATH']}" + wrong_target = subprocess.run( + [wrapper, "origin/main"], + cwd=repository, + env=environment, + capture_output=True, + text=True, + timeout=30, + check=False, + ) + assert wrong_target.returncode == 2 + assert "gitleaks base ref must be an ancestor" in wrong_target.stderr completed = subprocess.run( - [wrapper, base, head], + [wrapper, "origin/dev"], cwd=repository, env=environment, capture_output=True, From f7f79e9c64f1b80f4cdbce079d479ce5a47e3574 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:21:33 +0100 Subject: [PATCH 11/25] Keep local firewall behavior outside the toolkit release --- PLANS.md | 2 +- docs/local.md | 7 ---- src/ocr_toolkit/preflight.py | 30 +++++++------- tests/test_native_capabilities.py | 67 ------------------------------- 4 files changed, 16 insertions(+), 90 deletions(-) diff --git a/PLANS.md b/PLANS.md index 9e17b24e..882cbc3a 100644 --- a/PLANS.md +++ b/PLANS.md @@ -103,7 +103,7 @@ The contributor replied and updated #354 to 26080da. Static review on that revis 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. A controlled provider exercised reuse of 21 of 23 files in a separate official-binary test. +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. diff --git a/docs/local.md b/docs/local.md index 108a149f..605565af 100644 --- a/docs/local.md +++ b/docs/local.md @@ -234,13 +234,6 @@ Analysis. Incremental reports are for local use. When the result-size limit requires compact JSON, Markdown still contains all admitted findings and their provenance. -Incremental review and continuation run a verified copy named `ocr` in a private -directory unique to the session. With outbound network rules tied to the -executable path, an installed `ocr llm test` can succeed while the private copy -times out before a model response. Check the outbound decision for that process. -Use `ocr-ci review --local` for a fresh review through the installed binary when -that path can reach the provider. A failed run provides no review coverage. - ## LLM authentication Local review uses the configured API provider by default, including custom diff --git a/src/ocr_toolkit/preflight.py b/src/ocr_toolkit/preflight.py index 098decee..5fc50b49 100644 --- a/src/ocr_toolkit/preflight.py +++ b/src/ocr_toolkit/preflight.py @@ -10,6 +10,7 @@ import stat import subprocess import sys +import tempfile import time import urllib.error import urllib.parse @@ -306,36 +307,35 @@ def local_review_executable_qualified( def stage_local_review_executable( executable: str, version: str | None, capability: NativeCapability, session_home: Path ) -> str | None: - """Stage verified bytes as `ocr` under the session's unique private directory.""" + """Stage the verified bytes under the private home used for the whole review.""" assets = qualified_local_review_assets(version, capability) if not assets: return None - staged = session_home / "ocr" - descriptor = -1 + staged = None ready = False try: - descriptor = os.open(staged, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600) - with os.fdopen(descriptor, "wb", closefd=False) as output: + with tempfile.NamedTemporaryFile( + mode="w+b", prefix="qualified-ocr-", dir=session_home, delete=False + ) as output: + staged = Path(output.name) if not _check_local_review_asset(executable, assets, output): return None output.flush() - os.fchmod(descriptor, 0o500) - ready = os.path.samestat(os.fstat(descriptor), staged.lstat()) and os.access( - staged, os.X_OK - ) - return str(staged) if ready else None + os.fchmod(output.fileno(), 0o500) + if not os.access(staged, os.X_OK): + return None + ready = True + return str(staged) except OSError: return None finally: - if descriptor >= 0: + if staged is not None and not ready: + # The review still owns teardown of the enclosing private home. try: - if not ready and os.path.samestat(os.fstat(descriptor), staged.lstat()): - staged.unlink() + staged.unlink(missing_ok=True) except OSError: pass - finally: - os.close(descriptor) def _check_local_review_asset( diff --git a/tests/test_native_capabilities.py b/tests/test_native_capabilities.py index 490dbb66..d0bcc8e1 100644 --- a/tests/test_native_capabilities.py +++ b/tests/test_native_capabilities.py @@ -2,7 +2,6 @@ import hashlib import os -import stat import pytest from hypothesis import given @@ -122,72 +121,6 @@ def test_reuse_requires_the_exact_verified_executable_bytes(tmp_path, monkeypatc assert not preflight.local_review_executable_qualified(str(binary), version, capability) -def test_staging_uses_the_canonical_basename_and_verified_bytes(tmp_path, monkeypatch): - asset = b"verified bytes" - binary = tmp_path / "release-asset" - binary.write_bytes(asset) - session = tmp_path / "session" - session.mkdir(mode=0o700) - identity = (len(asset), hashlib.sha256(asset).hexdigest()) - capability = "local_review_incremental" - monkeypatch.setitem( - native_capabilities._QUALIFIED_LOCAL_ASSETS, "1.14.9", {capability: frozenset({identity})} - ) - - staged = session / "ocr" - assert preflight.stage_local_review_executable( - str(binary), "1.14.9", capability, session - ) == str(staged) - assert staged.read_bytes() == asset - assert stat.S_IMODE(staged.stat().st_mode) == 0o500 - assert list(session.iterdir()) == [staged] - - other_session = tmp_path / "other-session" - other_session.mkdir(mode=0o700) - binary.write_bytes(b"incorrect byte") - assert ( - preflight.stage_local_review_executable(str(binary), "1.14.9", capability, other_session) - is None - ) - assert list(other_session.iterdir()) == [] - assert staged.read_bytes() == asset - - -@pytest.mark.parametrize("existing", ["file", "symlink", "dangling"]) -def test_staging_preserves_a_preexisting_basename(tmp_path, monkeypatch, existing): - asset = b"verified bytes" - binary = tmp_path / "release-asset" - binary.write_bytes(asset) - session = tmp_path / "session" - session.mkdir(mode=0o700) - identity = (len(asset), hashlib.sha256(asset).hexdigest()) - capability = "local_review_continuation" - monkeypatch.setitem( - native_capabilities._QUALIFIED_LOCAL_ASSETS, "1.14.9", {capability: frozenset({identity})} - ) - target = tmp_path / "existing-target" - staged = session / "ocr" - if existing == "file": - staged.write_bytes(b"existing bytes") - else: - if existing == "symlink": - target.write_bytes(b"existing bytes") - staged.symlink_to(target) - - assert ( - preflight.stage_local_review_executable(str(binary), "1.14.9", capability, session) is None - ) - assert list(session.iterdir()) == [staged] - if existing == "file": - assert staged.read_bytes() == b"existing bytes" - else: - assert staged.readlink() == target - if existing == "symlink": - assert target.read_bytes() == b"existing bytes" - else: - assert not target.exists() - - def test_qualification_closes_descriptor_if_fdopen_fails(tmp_path, monkeypatch): binary = tmp_path / "ocr" binary.write_bytes(b"verified bytes") From 7a159ecc466f4ca852592d494c7579bf3e18ade4 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:22:22 +0100 Subject: [PATCH 12/25] Clarify maintainer rollout and report skipped qualification steps --- .github/workflows/ocr-compatibility.yml | 4 +++- docs/contributor-intake.md | 4 ++-- docs/development.md | 4 +++- docs/local.md | 5 +++-- tests/test_ocr_compat.py | 7 ++++++- 5 files changed, 17 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ocr-compatibility.yml b/.github/workflows/ocr-compatibility.yml index a7e3a977..ebd9ae4c 100644 --- a/.github/workflows/ocr-compatibility.yml +++ b/.github/workflows/ocr-compatibility.yml @@ -274,8 +274,9 @@ jobs: if-no-files-found: error retention-days: 2 - name: Summarize chain and patch outcomes - if: ${{ !cancelled() && steps.chain.outcome != 'skipped' }} + if: ${{ !cancelled() }} env: + CHAIN_OUTCOME: ${{ steps.chain.outcome }} CHAIN_CLASSIFICATION: ${{ steps.chain.outputs.classification }} CANDIDATE_OUTCOME: ${{ needs.qualify.result }} QUALIFICATION_ONLY: ${{ inputs.qualification_only || false }} @@ -284,6 +285,7 @@ jobs: run: | { 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}" diff --git a/docs/contributor-intake.md b/docs/contributor-intake.md index 444f75ec..94d9e467 100644 --- a/docs/contributor-intake.md +++ b/docs/contributor-intake.md @@ -4,12 +4,12 @@ 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. Land the reviewed maintainer bootstrap through the existing protected `main` procedure, then create `dev` from that reviewed state. 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) Verify the actual draft and ready checks on both routes before opening intake. +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"`. After a squash promotion, 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) +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 2c8d27a0..4c970cd9 100644 --- a/docs/development.md +++ b/docs/development.md @@ -51,7 +51,9 @@ 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. +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. diff --git a/docs/local.md b/docs/local.md index 605565af..ef426707 100644 --- a/docs/local.md +++ b/docs/local.md @@ -180,8 +180,9 @@ 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 link or a link outside the -selected files requires fresh review for connected groups. Unsupported +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. diff --git a/tests/test_ocr_compat.py b/tests/test_ocr_compat.py index a34114d5..d3521ec6 100644 --- a/tests/test_ocr_compat.py +++ b/tests/test_ocr_compat.py @@ -948,6 +948,9 @@ def test_chain_summary_reports_patch_preparation_and_upload_independently( 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 }}" @@ -958,6 +961,7 @@ def test_chain_summary_reports_patch_preparation_and_upload_independently( **os.environ, "GITHUB_STEP_SUMMARY": str(output), "CHAIN_CLASSIFICATION": classification, + "CHAIN_OUTCOME": chain, "CANDIDATE_OUTCOME": candidate_status, "QUALIFICATION_ONLY": qualification_only, "PATCH_OUTCOME": patch, @@ -967,7 +971,8 @@ def test_chain_summary_reports_patch_preparation_and_upload_independently( check=True, timeout=10, ) - assert output.read_text().splitlines()[-5:] == [ + 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}`", From dedaa54ca29fc4e2862c3ee91ad4eb457aef3eb4 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:58:58 +0100 Subject: [PATCH 13/25] Prepare both pull requests for protected dev intake --- PLANS.md | 8 ++++---- docs/contributor-intake.md | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/PLANS.md b/PLANS.md index 882cbc3a..63a367c6 100644 --- a/PLANS.md +++ b/PLANS.md @@ -34,7 +34,7 @@ Review the new contributor's entire repository history, fix incremental qualific ### Explicit Non-Goals -This implementation handoff ends at a maintainer-owned draft PR against the current protected main, before merge or publication. Keep the external #354 branch and its implementation separate while the contributor prepares the requested changes. +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 @@ -67,7 +67,7 @@ At b93ec7d the three changed files cover local opt-in qualification, its tests a | 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 | Land maintainer-owned bootstrap on protected 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-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 | in_progress | | 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 | @@ -79,7 +79,7 @@ Keep #354 open against its original fork head. The maintainer posted [two reques 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. Main requires linear history and a current base; the repository currently disables merge commits. For repeated direct promotions, propose allowing merge commits at repository level while retaining main's squash/rebase restrictions and signed linear history. 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. +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. @@ -121,7 +121,7 @@ Protect dev before admitting any external code. A PR from dev in the same reposi ### Resume Point -Review the maintainer bootstrap draft. Before creating or protecting dev, restrict the three deployment environments to named main, migrate the site credential and remove its repository-level copy. Then configure protected intake and verify both branch routes using docs/contributor-intake.md. Recheck the contributor head and outstanding requests. +All three environments now select only the main branch. Both ref rulesets have twelve strict required checks, and outside collaborators require workflow approval. PR #357 is ready. Finish the site credential migration, remove its repository-level copy, create dev at current main and retarget #357 and #354. Verify fresh checks against dev and the reviewed base CI before approving fork execution. Two local signed promotion and synchronization cycles preserved ancestry and isolated the second change. ### Plan Fidelity Check diff --git a/docs/contributor-intake.md b/docs/contributor-intake.md index 94d9e467..7bc0490a 100644 --- a/docs/contributor-intake.md +++ b/docs/contributor-intake.md @@ -3,7 +3,7 @@ ## 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. Land the reviewed maintainer bootstrap through the existing protected `main` procedure, then create `dev` from that reviewed state. 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) +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 From aad2b03f27c9067ae67afa592a1017bd57f454bc Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:19:26 +0100 Subject: [PATCH 14/25] Preserve proven technical literals during publication phone checks --- changelog.d/358.bugfix.md | 1 + docs/security.md | 8 +- src/ocr_toolkit/context/dlp/admission.py | 22 +++- src/ocr_toolkit/context/dlp/arithmetic.py | 55 ++++++++++ src/ocr_toolkit/context/dlp/datetimes.py | 77 ++++++++++++- src/ocr_toolkit/context/dlp/markup.py | 26 ++++- src/ocr_toolkit/context/dlp/numeric.py | 7 +- src/ocr_toolkit/context/dlp/projection.py | 14 ++- tests/test_dlp_arithmetic.py | 123 +++++++++++++++++++++ tests/test_dlp_audit.py | 40 +++++++ tests/test_dlp_date_ranges.py | 117 ++++++++++++++++++++ tests/test_review_runner.py | 127 ++++++++++++++++++++++ 12 files changed, 601 insertions(+), 16 deletions(-) create mode 100644 changelog.d/358.bugfix.md create mode 100644 src/ocr_toolkit/context/dlp/arithmetic.py create mode 100644 tests/test_dlp_arithmetic.py create mode 100644 tests/test_dlp_date_ranges.py diff --git a/changelog.d/358.bugfix.md b/changelog.d/358.bugfix.md new file mode 100644 index 00000000..5056b4f1 --- /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 integer size calculations. Phone numbers and sensitive material elsewhere in the finding still prevent publication. diff --git a/docs/security.md b/docs/security.md index e2f422ae..0b1293a1 100644 --- a/docs/security.md +++ b/docs/security.md @@ -467,7 +467,13 @@ 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. A dated local Markdown heading can retain Unicode letters in +its destination. A complete assignment such as `size = 16 * 1024 * 1024` +preserves its multiplication operators during phone checks, including when +quoted in a supported inline code span. 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. diff --git a/src/ocr_toolkit/context/dlp/admission.py b/src/ocr_toolkit/context/dlp/admission.py index 9701cf4d..c5b68501 100644 --- a/src/ocr_toolkit/context/dlp/admission.py +++ b/src/ocr_toolkit/context/dlp/admission.py @@ -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 ( @@ -244,9 +246,13 @@ def _markup_phone(value: str, *, literal: bool) -> bool: # 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. + hidden = ( + markup.hidden + if literal + else (*markup.hidden_nonlinks, *(dated_anchor_phone_view(link) for link in markup.links)) + ) 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 + _contains_phone(phone_markup_view(_literal_normalize(fragment))) for fragment in hidden ) @@ -409,6 +415,11 @@ 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) + 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 +443,10 @@ 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) or _markup_phone(phone_candidate, literal=literal): 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 +458,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 diff --git a/src/ocr_toolkit/context/dlp/arithmetic.py b/src/ocr_toolkit/context/dlp/arithmetic.py new file mode 100644 index 00000000..2e893ee0 --- /dev/null +++ b/src/ocr_toolkit/context/dlp/arithmetic.py @@ -0,0 +1,55 @@ +"""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.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 + prefix = strip_format_markers(value[max(0, opening - 256) : opening]) + if _explicit_context(prefix, len(prefix)): + 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..d7ba6cb5 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 @@ -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 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..a25bf0f9 100644 --- a/src/ocr_toolkit/context/dlp/projection.py +++ b/src/ocr_toolkit/context/dlp/projection.py @@ -12,6 +12,7 @@ from mistune.renderers.markdown import MarkdownRenderer from ocr_toolkit.context.contracts import TextBudgets +from ocr_toolkit.context.dlp.datetimes import dated_anchor_phone_view from ocr_toolkit.context.dlp.decoding import RepresentationLimit, _html_decode from ocr_toolkit.context.dlp.markup import _PARSER, interpret_markdown from ocr_toolkit.context.dlp.presentation import has_unsafe_controls @@ -167,17 +168,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 +197,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/tests/test_dlp_arithmetic.py b/tests/test_dlp_arithmetic.py new file mode 100644 index 00000000..614381cd --- /dev/null +++ b/tests/test_dlp_arithmetic.py @@ -0,0 +1,123 @@ +"""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") + + +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_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_date_ranges.py b/tests/test_dlp_date_ranges.py new file mode 100644 index 00000000..4510beff --- /dev/null +++ b/tests/test_dlp_date_ranges.py @@ -0,0 +1,117 @@ +"""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", + ( + "[§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_review_runner.py b/tests/test_review_runner.py index c90bc04f..371219dd 100644 --- a/tests/test_review_runner.py +++ b/tests/test_review_runner.py @@ -19,6 +19,7 @@ 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 @@ -2324,6 +2325,132 @@ def test_publication_dlp_retains_only_safe_local_findings_without_provider_recei assert "ocr_toolkit_evidence" in rendered +def test_publication_preserves_technical_findings_and_omits_sensitive_neighbors( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """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": [*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(base, head), + "coverage": { + "selected": [{"item_id": "scan"}], + "completed": [{"item_id": "scan"}], + "reused": [], + "failed": [], + "waived": [], + }, + }, + } + ), + encoding="utf-8", + ) + composition = MCPComposition( + payload={}, + capabilities=(MCPCapability("ocr_toolkit_evidence", BUILTIN_EVIDENCE_TOOLS, True),), + 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: From d05c4266ca27686e0c03b6145d1893102fcf96de Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:24:24 +0100 Subject: [PATCH 15/25] Keep context admission and canonical contact labels protected --- docs/security.md | 8 ++++++-- src/ocr_toolkit/context/dlp/admission.py | 23 +++++++++++++++-------- src/ocr_toolkit/context/dlp/arithmetic.py | 8 ++++++-- src/ocr_toolkit/context/dlp/numeric.py | 8 ++++---- tests/test_dlp_arithmetic.py | 22 ++++++++++++++++++++++ tests/test_dlp_date_ranges.py | 19 +++++++++++++++++++ 6 files changed, 72 insertions(+), 16 deletions(-) diff --git a/docs/security.md b/docs/security.md index 0b1293a1..d79dddf5 100644 --- a/docs/security.md +++ b/docs/security.md @@ -469,10 +469,14 @@ 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. Publication recognizes a range when both ISO dates are calendar-valid and the entire phone candidate falls -inside the range. A dated local Markdown heading can retain Unicode letters in +inside the range. 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 dated local Markdown heading can retain Unicode letters in its destination. A complete assignment such as `size = 16 * 1024 * 1024` preserves its multiplication operators during phone checks, including when -quoted in a supported inline code span. Explicit contact context, adjacent +quoted in a supported inline code span. This form accepts two to four +power-of-two factors of up to five decimal digits, including at least two +factors of 1024 or greater, with spaces or tabs around `*` or `**`. +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; diff --git a/src/ocr_toolkit/context/dlp/admission.py b/src/ocr_toolkit/context/dlp/admission.py index c5b68501..9bdf4df7 100644 --- a/src/ocr_toolkit/context/dlp/admission.py +++ b/src/ocr_toolkit/context/dlp/admission.py @@ -241,18 +241,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. hidden = ( - markup.hidden - if literal - else (*markup.hidden_nonlinks, *(dated_anchor_phone_view(link) for link in markup.links)) + (*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))) or any( - _contains_phone(phone_markup_view(_literal_normalize(fragment))) for fragment in 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 ) @@ -446,7 +450,9 @@ def _check_material( phone_candidate = candidate if representation == "source" and not literal and arithmetic_phone != normalized: phone_candidate = _source_normalize(arithmetic_phone) - if _contains_phone(phone_candidate) or _markup_phone(phone_candidate, literal=literal): + 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. @@ -472,7 +478,8 @@ 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) diff --git a/src/ocr_toolkit/context/dlp/arithmetic.py b/src/ocr_toolkit/context/dlp/arithmetic.py index 2e893ee0..4bdf3dd8 100644 --- a/src/ocr_toolkit/context/dlp/arithmetic.py +++ b/src/ocr_toolkit/context/dlp/arithmetic.py @@ -5,6 +5,7 @@ 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}" @@ -41,8 +42,11 @@ def binary_size_phone_view(value: str, *, prose: bool) -> str: for opening, start, end in interpret_markdown(value).exact_code_bodies: if start < cursor or _explicit_context(value, opening): continue - prefix = strip_format_markers(value[max(0, opening - 256) : opening]) - if _explicit_context(prefix, len(prefix)): + # 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) diff --git a/src/ocr_toolkit/context/dlp/numeric.py b/src/ocr_toolkit/context/dlp/numeric.py index d7ba6cb5..e25cbc5a 100644 --- a/src/ocr_toolkit/context/dlp/numeric.py +++ b/src/ocr_toolkit/context/dlp/numeric.py @@ -123,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( @@ -133,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) ) @@ -221,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) @@ -233,7 +233,7 @@ def _technical_number(value: str, match: re.Match[str]) -> bool: return False if ( complete_datetime(value, *match.span()) - or complete_date_range(value, *match.span()) + or (publication and complete_date_range(value, *match.span())) or _complete_technical_block(value, *match.span()) ): return True diff --git a/tests/test_dlp_arithmetic.py b/tests/test_dlp_arithmetic.py index 614381cd..59a552c9 100644 --- a/tests/test_dlp_arithmetic.py +++ b/tests/test_dlp_arithmetic.py @@ -91,6 +91,28 @@ def test_inline_qualification_preserves_other_contacts_and_requires_exact_body(v 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" diff --git a/tests/test_dlp_date_ranges.py b/tests/test_dlp_date_ranges.py index 4510beff..704da4c2 100644 --- a/tests/test_dlp_date_ranges.py +++ b/tests/test_dlp_date_ranges.py @@ -66,6 +66,25 @@ 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", ( From 8679fdd12774acb900ffa597eed47b2fbd8cf3d9 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:29:27 +0100 Subject: [PATCH 16/25] Document the supported publication literal grammar --- docs/security.md | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/docs/security.md b/docs/security.md index d79dddf5..3546a208 100644 --- a/docs/security.md +++ b/docs/security.md @@ -470,14 +470,16 @@ formatted numbers retain conservative phone checks; arithmetic syntax alone 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 separator can be two or three periods, an ellipsis, or -an en dash, with up to 16 spaces or tabs on either side. A dated local Markdown heading can retain Unicode letters in -its destination. A complete assignment such as `size = 16 * 1024 * 1024` -preserves its multiplication operators during phone checks, including when -quoted in a supported inline code span. This form accepts two to four -power-of-two factors of up to five decimal digits, including at least two -factors of 1024 or greater, with spaces or tabs around `*` or `**`. -Explicit contact context, adjacent -phone numbers and credential checks still apply. Literal code +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. +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. +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. From dd8688cc5b0b5d3ae201a082b831d68342624ec5 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:34:20 +0100 Subject: [PATCH 17/25] Clarify remaining conservative publication cases --- changelog.d/358.bugfix.md | 2 +- docs/security.md | 9 +++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/changelog.d/358.bugfix.md b/changelog.d/358.bugfix.md index 5056b4f1..978cceb9 100644 --- a/changelog.d/358.bugfix.md +++ b/changelog.d/358.bugfix.md @@ -1 +1 @@ -Publication DLP keeps findings that quote supported ISO date ranges, dated local Markdown anchors and integer size calculations. Phone numbers and sensitive material elsewhere in the finding still prevent publication. +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/security.md b/docs/security.md index 3546a208..d66e6f66 100644 --- a/docs/security.md +++ b/docs/security.md @@ -469,16 +469,21 @@ 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. Publication recognizes a range when both ISO dates are calendar-valid and the entire phone candidate falls -inside the range. The separator can be two or three periods, an ellipsis, or +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. +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; From 6ca67d63c3cb6a94d40a684bbc19774d42521123 Mon Sep 17 00:00:00 2001 From: xeonvs <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:49:47 +0100 Subject: [PATCH 18/25] Exercise publication, context readback and review recovery without native OCR --- tests/test_context_store.py | 44 ++ tests/test_dlp_publication_edges.py | 121 ++++++ ...st_review_runner_publication_boundaries.py | 375 ++++++++++++++++++ tests/test_review_runtime_cleanup.py | 337 ++++++++++++++++ 4 files changed, 877 insertions(+) create mode 100644 tests/test_dlp_publication_edges.py create mode 100644 tests/test_review_runner_publication_boundaries.py create mode 100644 tests/test_review_runtime_cleanup.py diff --git a/tests/test_context_store.py b/tests/test_context_store.py index 7c9bcb67..5902e6c2 100644 --- a/tests/test_context_store.py +++ b/tests/test_context_store.py @@ -547,3 +547,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_dlp_publication_edges.py b/tests/test_dlp_publication_edges.py new file mode 100644 index 00000000..694d8f13 --- /dev/null +++ b/tests/test_dlp_publication_edges.py @@ -0,0 +1,121 @@ +"""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, check_text + +_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, + ) + + +def test_forbidden_comparison_budget_fails_closed_before_publication(): + candidate = "a" * 8000 + result = check_text( + candidate, budgets=_BUDGETS, publication=True, forbidden=("b" * 8000,), 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 " 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?} @@ -171,15 +173,16 @@ 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 @@ -197,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] @@ -222,7 +225,7 @@ 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,incremental_federation_fallback,review,diagram_snapshot,finalize,diagram_admit,diag,dlp,disabled,publishable,partial,receipt,diagram_post,transaction auxiliary; + 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; ``` @@ -245,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. @@ -264,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 @@ -283,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 @@ -339,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. @@ -364,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] @@ -389,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; @@ -420,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 a3844c3b..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,22 @@ 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. @@ -169,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 @@ -196,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, @@ -205,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 @@ -245,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. @@ -275,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. @@ -326,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 @@ -340,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. @@ -562,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 @@ -581,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. @@ -646,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/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/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 9bdf4df7..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 @@ -54,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"}) @@ -130,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: @@ -140,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: @@ -175,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 - ) - if comparison_cost > MAX_EXCERPT_SEARCH_COST: - 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 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()) ) - 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: + if work > MAX_FORBIDDEN_MATCH_WORK: 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: @@ -206,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.""" @@ -280,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, @@ -331,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), @@ -349,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: @@ -373,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( ( ( @@ -393,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)) @@ -419,6 +465,16 @@ 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 @@ -484,11 +540,10 @@ def _check_material( 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 @@ -496,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) ): @@ -527,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, @@ -535,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, @@ -549,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: @@ -566,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/projection.py b/src/ocr_toolkit/context/dlp/projection.py index a25bf0f9..35414d5e 100644 --- a/src/ocr_toolkit/context/dlp/projection.py +++ b/src/ocr_toolkit/context/dlp/projection.py @@ -11,9 +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.datetimes import dated_anchor_phone_view -from ocr_toolkit.context.dlp.decoding import RepresentationLimit, _html_decode +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 @@ -25,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: 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 a15bbf58..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,21 +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", - "gitignore", - "deleted", - "binary", - "too_large", - } -) @dataclass(frozen=True, slots=True) @@ -82,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, ...] @@ -97,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() @@ -376,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, ...]: @@ -436,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, @@ -464,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) @@ -484,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): @@ -518,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") @@ -525,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"} @@ -557,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 @@ -583,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, ...]: - """Verify native preview records against the independently proven Git 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", @@ -609,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 @@ -659,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 ( @@ -672,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 2f4e2694..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,6 +38,7 @@ 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$" ) @@ -114,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.""" @@ -204,15 +267,23 @@ def _run_at( return completed def _run( - self, args: list[str], *, timeout: int = 15, text: bool = True, local_only: bool = False + 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 or local_only or self._local_only: - return self._run_streamed( - args, timeout=self._timeout(timeout), text=text, local_only=local_only - ) - 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, @@ -222,6 +293,7 @@ def _run_streamed( 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.""" @@ -253,6 +325,8 @@ def _run_streamed( 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: @@ -480,42 +554,40 @@ def list_objects( """List bounded tree entries without following symlinks or submodules.""" sha = self.resolve_commit(ref, local_only=local_only) - result = self._run( - ["ls-tree", "-z", "-r", "--full-tree", sha], - timeout=30, - text=False, - local_only=local_only, - ) - 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: + 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: @@ -867,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/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/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/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 c799fdeb..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: 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/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 c5d4a281..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, @@ -225,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 @@ -383,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"" @@ -941,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", @@ -980,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 @@ -1016,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.""" @@ -1216,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 @@ -1255,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, ) @@ -1513,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, @@ -1543,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() @@ -1731,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) @@ -1744,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"), @@ -1825,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 @@ -1839,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( @@ -1863,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, @@ -1915,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: @@ -1943,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") @@ -2037,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: @@ -2046,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"]) @@ -2089,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: @@ -2112,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, ) @@ -2455,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() @@ -2588,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, ) @@ -2609,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 @@ -2640,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 @@ -3890,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: @@ -4068,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( @@ -4081,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", @@ -4109,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, @@ -4283,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, @@ -4310,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 {} @@ -4443,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 ab8af7e5..62e9c619 100644 --- a/tests/federation/test_ocr_qualification.py +++ b/tests/federation/test_ocr_qualification.py @@ -30,7 +30,9 @@ ) 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 @@ -57,7 +59,7 @@ def test_local_incremental_uses_normal_federation_and_reports_fallback( (repo / "ocr_toolkit.py").write_text("raise RuntimeError('repository shadow')\n") registry = { - "version": 2, + "version": REGISTRY_VERSION, "servers": { "tracker": { "transport": { @@ -65,7 +67,7 @@ def test_local_incremental_uses_normal_federation_and_reports_fallback( "command": sys.executable, "args": ["-I", str(Path(__file__).with_name("sdk_peer.py").resolve())], }, - "tools": {"echo": {"assurance": "review_read"}}, + "tools": {"echo": {**tool_policy("echo"), "assurance": "review_read"}}, } }, } @@ -200,7 +202,7 @@ def read_issue(key: str) -> str: encoding="utf-8", ) registry = { - "version": 2, + "version": REGISTRY_VERSION, "servers": { "tracker": { "transport": { @@ -208,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, + }, + } + }, } }, } @@ -422,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 5902e6c2..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} ), 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_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_publication_edges.py b/tests/test_dlp_publication_edges.py index 694d8f13..3e1f78e1 100644 --- a/tests/test_dlp_publication_edges.py +++ b/tests/test_dlp_publication_edges.py @@ -5,7 +5,8 @@ import pytest from ocr_toolkit.context.contracts import TextBudgets -from ocr_toolkit.context.dlp import ForbiddenValue, check_text +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) @@ -66,10 +67,114 @@ def test_percent_decoding_and_unicode_compatibility_cannot_hide_a_credential(): ) -def test_forbidden_comparison_budget_fails_closed_before_publication(): +@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=("b" * 8000,), enabled=True + candidate, budgets=_BUDGETS, publication=True, forbidden=forbidden, enabled=True ) assert (result.admitted, result.reason, result.detector, result.text) == ( False, diff --git a/tests/test_dlp_safe_markup.py b/tests/test_dlp_safe_markup.py index b1d50c11..3c24c605 100644 --- a/tests/test_dlp_safe_markup.py +++ b/tests/test_dlp_safe_markup.py @@ -51,8 +51,9 @@ def test_benign_markup_is_prepared_and_idempotent(value): "[guide]: javascript:hello\n\nordinary text", ), ) -def test_unsafe_destinations_are_rejected(value): - assert not check_text(value, budgets=BUDGETS, publication=True).admitted +@pytest.mark.parametrize("enabled", (True, False)) +def test_unsafe_destinations_are_rejected(value, enabled): + assert not check_text(value, budgets=BUDGETS, publication=True, enabled=enabled).admitted @pytest.mark.parametrize( @@ -94,12 +95,24 @@ def test_html_and_images_are_visible_but_inert(): assert check_text(checked.text, budgets=BUDGETS, publication=True).text == checked.text -def test_projection_expansion_has_an_independent_budget(): +@pytest.mark.parametrize("enabled", (True, False)) +def test_projection_expansion_has_an_independent_budget(enabled): value = "" * 8 - checked = check_text(value, budgets=TextBudgets(len(value), 1000, 10), publication=True) + checked = check_text( + value, budgets=TextBudgets(len(value), 1000, 10), publication=True, enabled=enabled + ) assert not checked.admitted and checked.reason == "limit" +def test_disabled_runner_rejects_presentation_expansion_with_controlled_error(): + value = "" * 8 + payload = {"comments": [{"path": "file.py", "content": value}]} + with pytest.raises(review_runner.ReviewRunnerError, match="mandatory safe presentation"): + review_runner._project_disabled_publication_prose( + payload, budgets=TextBudgets(len(value), 1000, 10) + ) + + def test_finalization_prepares_prose_without_filtering_or_mutating_input(): from html import unescape @@ -159,32 +172,47 @@ def test_html_literal_projection_cannot_activate_its_inner_markdown(value): 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_environment_contract.py b/tests/test_environment_contract.py index c14618d4..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", 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 b7be1c5e..8e668202 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, @@ -113,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 @@ -173,6 +201,120 @@ def test_projection_preserves_original_ordinary_diff(tmp_path: Path, kind: str) verify_gitlink_projection(reader, projection) +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] = { @@ -207,6 +349,142 @@ def test_projection_qualifies_exact_preview_and_zero_selection(tmp_path: Path) - 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( "mutate", [ @@ -231,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) @@ -517,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() @@ -672,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": [], @@ -709,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": []}] @@ -1001,7 +1329,20 @@ 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: @@ -1013,16 +1354,17 @@ def test_installed_ocr_projected_review_matches_native_manifest( 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) @@ -1042,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, @@ -1051,12 +1397,24 @@ 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) + 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-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, @@ -1075,7 +1433,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) 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 7ab4ad28..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 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_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 7b98c42c..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`", 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_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 371219dd..72a27263 100644 --- a/tests/test_review_runner.py +++ b/tests/test_review_runner.py @@ -22,13 +22,19 @@ 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 @@ -38,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, @@ -328,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.""" @@ -761,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), @@ -797,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), @@ -1295,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),), @@ -1308,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) @@ -1340,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": @@ -1349,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" @@ -1363,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") @@ -2017,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", @@ -2109,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"] == [] @@ -2456,31 +2528,17 @@ def test_background_preview_advisory_is_atomically_finalized_without_blocking_ap ) -> None: """Keep the accepted numeric advisory outside warnings, DLP, and approval inputs.""" - result = tmp_path / "result.json" - result.write_text( - json.dumps( - { - "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", - "input": native_range_input("c" * 40, "a" * 40), - "coverage": { - "selected": [{"item_id": "synthetic-item"}], - "completed": [{"item_id": "synthetic-item"}], - "reused": [], - "failed": [], - "waived": [], - }, - }, - } - ), - encoding="utf-8", + 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),), @@ -2492,12 +2550,13 @@ def test_background_preview_advisory_is_atomically_finalized_without_blocking_ap _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")) @@ -2964,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 ( @@ -3017,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")) @@ -4839,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]] = [] @@ -4851,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 @@ -4895,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" ) @@ -4939,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"), @@ -4949,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, @@ -4989,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") @@ -5008,9 +5080,9 @@ def bootstrap(*_args: object, **kwargs: object) -> str: tmp_path / "stderr.log", [ "--from", - "base", + base, "--to", - "head", + head, "--format", "json", "--max-tools", @@ -5032,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", }, ) @@ -5054,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" @@ -5065,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 index e0e54364..48bacbd6 100644 --- a/tests/test_review_runner_publication_boundaries.py +++ b/tests/test_review_runner_publication_boundaries.py @@ -11,22 +11,35 @@ 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 gitlink_selection_proof, make_gitlink_projection -from ocr_toolkit.evidence.gitlinks import plan_gitlink_input -from ocr_toolkit.evidence.repository import GitRepositoryReader +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.approval import toolkit_receipt_is_valid +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 tests.support import native_range_input +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( @@ -53,6 +66,7 @@ def _native_result(base: str, head: str) -> dict: "input": native_range_input(base, head), "coverage": { "selected": [item.copy()], + "excluded": [], "completed": [item.copy()], "failed": [], "reused": [], @@ -222,7 +236,7 @@ def finalize(): ) if damage_manifest: - with pytest.raises(review_runner.ReviewRunnerError, match="did not prove selected work"): + with pytest.raises(review_runner.ReviewRunnerError, match="did not prove the immutable"): finalize() assert not result.exists() and not reports return @@ -245,6 +259,256 @@ def finalize(): 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) 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 From 65ed3d0cc33378f8c00336a8d853fbf900d17d34 Mon Sep 17 00:00:00 2001 From: Max Irgiznov <11463419+xeonvs@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:41:21 +0100 Subject: [PATCH 23/25] Verify native OCR preview against the trusted base version (#362) Related to #355 and the 0.16.1 promotion in #361. The native integration test now checks the exact immutable input and the toolkit rejection when OCR 1.14.5 omits a tracked ignored file. With the new qualification, the test requires the selected path and the explicit gitignore exclusion, then verifies the production manifest. The workflow continues to select the binary from its protected base. All 78 gitlink tests passed locally with the qualified OCR executable. Ruff, the range and tree secret scans, and the dependency audit passed. Protected CI on dev exercises the updated binary. CI on the promotion to main exercises its older trusted binary. --- tests/test_gitlinks.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/tests/test_gitlinks.py b/tests/test_gitlinks.py index 8e668202..ceb8c1ef 100644 --- a/tests/test_gitlinks.py +++ b/tests/test_gitlinks.py @@ -1348,7 +1348,7 @@ def test_installed_ocr_projected_review_matches_native_manifest( ) -> 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 @@ -1397,12 +1397,24 @@ def test_installed_ocr_projected_review_matches_native_manifest( timeout=30, ) assert preview.returncode == 0 and preview.stderr == b"" + 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 + 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] == [ 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 24/25] 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. From 834c49514cd04e1baf59ec2c565575eaf9ba0e79 Mon Sep 17 00:00:00 2001 From: Max Irgiznov <11463419+xeonvs@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:18:05 +0100 Subject: [PATCH 25/25] Prepare 0.16.2: incremental review efficiency and CI deduplication (#369) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Target release: 0.16.2. Related issues: [#368 — incremental review reuse and measured OCR costs](https://github.com/xeonvs/open-code-review-toolkit/issues/368) and [#364 — CI deduplication and protected-check qualification](https://github.com/xeonvs/open-code-review-toolkit/issues/364). Qualify bounded native reads and searches, measure token use and evidence preparation, and validate CI event routing with protected check identities. The implementation and acceptance results will be reviewed before promotion. ## Verification The synthetic same-revision follow-up consumed 41,390 vs 83,606 total input/output tokens and retained the known finding. Default-filter reuse also passed. Evidence collection used two full tree walks instead of five. See the [measured OCR results](https://github.com/xeonvs/open-code-review-toolkit/issues/368#issuecomment-7339853269) and the [hosted CI scope](https://github.com/xeonvs/open-code-review-toolkit/issues/364#issuecomment-7339853850). Existing protected CI triggers are preserved. --- PLANS.md | 107 +++++++ changelog.d/368.bugfix.md | 1 + changelog.d/370.bugfix.md | 1 + docs/codex/ENGINEERING_WORKFLOW_STATE.yaml | 2 +- docs/development.md | 29 +- docs/gitlab.md | 17 +- docs/local.md | 20 +- docs/review-decision-flow.md | 2 +- docs/security.md | 22 ++ src/ocr_toolkit/evidence/collect.py | 32 +- .../evidence/collectors/orchestration.py | 4 +- .../evidence/gitlink_projection.py | 252 ++++++++++++++-- src/ocr_toolkit/evidence/repository.py | 12 +- .../local_incremental_dependencies.py | 161 +++++++--- src/ocr_toolkit/local_incremental_replay.py | 82 ++++- src/ocr_toolkit/local_incremental_state.py | 45 ++- src/ocr_toolkit/posting/workflow.py | 53 ++-- src/ocr_toolkit/reporting/incremental.py | 4 + src/ocr_toolkit/review_runner.py | 27 +- tests/test_evidence_collectors.py | 40 +++ tests/test_gitlinks.py | 125 +++++++- tests/test_local_incremental.py | 123 +++++++- tests/test_local_incremental_reads.py | 154 ++++++++++ tests/test_local_incremental_replay.py | 281 +++++++++++++++++- 24 files changed, 1403 insertions(+), 193 deletions(-) create mode 100644 changelog.d/368.bugfix.md create mode 100644 changelog.d/370.bugfix.md create mode 100644 tests/test_local_incremental_reads.py diff --git a/PLANS.md b/PLANS.md index ecc5b3e7..53d89b2c 100644 --- a/PLANS.md +++ b/PLANS.md @@ -1,5 +1,112 @@ # Execution Plans +## Active Plan: Toolkit 0.16.2 — incremental review efficiency, Runner compatibility and CI deduplication + +plan_schema_version: 2 +Status: active +Release classification: release-required +Target release: 0.16.2 +Next development marker: 0.17.0 +Last Updated: 2026-12-02 + +### Goal + +Reduce repeated native OCR model work with verifiable incremental reuse, measure preparation and MCP costs, and qualify CI deduplication on protected PRs. + +### Plan Origin + +plan_mode_approved + +### Requested Scope + +Deliver [#368](https://github.com/xeonvs/open-code-review-toolkit/issues/368), [#364](https://github.com/xeonvs/open-code-review-toolkit/issues/364) and [#370](https://github.com/xeonvs/open-code-review-toolkit/issues/370) through one implementation draft targeting dev, then prepare the signed release PR. + +### Requirement Traceability + +| Requirement | Outcome | Queue | Status | +| --- | --- | --- | --- | +| REQ-001 | One linked implementation draft and milestone | WQ-01 | done | +| REQ-002 | Exact immutable read/search replay and native token measurements | WQ-02 | done | +| REQ-003 | Separate preflight, preparation and MCP measurements | WQ-03 | done | +| REQ-004 | Hosted CI qualification and resource cleanup | WQ-04 | done | +| REQ-006 | Restore review and posting for ordinary GitLab Runner checkouts with externalized Git configuration | WQ-06 | done | +| REQ-005 | Verified promotion, TestPyPI preview and signed release candidate | WQ-05 | pending | + +### Explicit Non-Goals + +Stable publication requires separate authorization. Workflow credentials and private review material stay outside test fixtures. + +### Constraints + +Reuse evidence for identical inputs and environments. Publish only synthetic cases and anonymous aggregates. Preserve existing replay budgets, DLP, attestation, fork isolation and required check identities. + +### Inputs And Sources + +[#368](https://github.com/xeonvs/open-code-review-toolkit/issues/368), [#364](https://github.com/xeonvs/open-code-review-toolkit/issues/364), [#370](https://github.com/xeonvs/open-code-review-toolkit/issues/370), the native qualification manifest, development and release guides, existing telemetry, provider check rules and [#366](https://github.com/xeonvs/open-code-review-toolkit/pull/366). + +### User Decisions And Answers + +Patch release 0.16.2, one draft to dev, and final cleanup. The maintainer subsequently waived the disposable hosted repository and fork exercise. Preserve the current required triggers and track the outstanding hosted proof in #364. Use the existing native executable for local qualification. + +### Completed Baseline State + +Protected dev incorporates the preceding release workflow repair. The reported token count is an observation from one review. Milestone v0.16.2 tracks the original two issues and the urgent Runner compatibility report. + +### Current Work Queue + +| Item | Work and exit evidence | Requirements | Status | +| --- | --- | --- | --- | +| WQ-01 | Push signed plan and create the linked draft. | REQ-001 | done | +| WQ-02 | Qualify UTF-8/line/body truncation and 99/100/101 matches, PCRE and exclusions. Compare baseline, repeat and control for usage, groups and expected finding. | REQ-002 | done | +| WQ-03 | Measure cold/warm preflight, preparation through first request, evidence construction and repeated query. Attribute time, RSS, Git work and bytes; optimize only measured costs. | REQ-003 | done | +| WQ-04 | Verify existing route evidence for fork, draft and advisory intervals. The maintainer waived the new remote fixture. Keep unqualified trigger changes pending in #364. | REQ-004 | done | +| WQ-06 | Qualify ordinary Runner-managed config includes in GitLab review and posting while retaining immutable coverage, ignored-path and credential boundaries. | REQ-006 | done | +| WQ-05 | Review each logical change and aggregate diff. Merge ready dev PR, promote dev, verify development publication, prepare release PR and request permission. | REQ-005 | pending | + +### Locked Decisions + +Observed native bytes and immutable dependencies determine reuse. Unknown outputs or unavailable proof cause a fresh review of the affected group. Gate changes to protected check behavior on hosted proof. + +### Verification + +Compare equivalent synthetic reviews with one controlled change. Report measured input/output/cached tokens and tool activity when available. Compare first and repeated requests on the same revision and verify evidence identity after optimization. Verify hosted merge eligibility and clean up before handoff. + +### Latest Validation Results + +2026-12-02: #369 opened as a draft with both issue links. Synthetic follow-up against the same revisions and model with filtering disabled used 41,390 input plus output tokens compared with 83,606 on the previous release, and retained the known finding. Default-filter candidate baseline and follow-up qualified and carried the same finding. Installed-path measurements used a local development adapter; released executable binding remains unchanged. The collector reduced full tree listings from five to two with identical evidence and bootstrap bytes. The local preflight and MCP measurements are reported separately in #368. + +On the same synthetic MR range, review and post succeeded with and without a Runner include on 0.16.0. On 0.16.1 only the include case failed before OCR. With the correction, installed OCR reviewed the selected change and posting reported the tracked ignored file as incomplete coverage. The checkout config was unchanged. This used a local HTTPS forge fixture. + +Existing protected fork and draft runs corroborate distinct Actions and CodeQL app checks. After required checks passed, two prior merges took 17 s and 23 s, including cases with pending advisory runners. Required workflow triggers remain unchanged. No remote test infrastructure was created. + +### Risks And Recovery + +Keep broad checks for uncertain CI events. Continue independent work when hosted access is unavailable. Use existing data first, isolate new model runs to synthetic fixtures, and remove temporary materials after retaining sanitized results. + +### Resume Point + +WQ-05: finish aggregate verification and obtain passing protected dev checks, then promote, verify TestPyPI and prepare the signed release PR. Keep #364 open for the outstanding hosted proof. + +### Plan Fidelity Check + +REQ-001 through REQ-006 cover the three issues, native and hosted acceptance, measurements, cleanup, promotion and the authorization boundary. + +### Reconciliation Check + +Use dev and the issue milestone as the development baseline. Keep open issues tracked through the release receipt. + +### Closure Gate + +Require applicable protected checks, completed qualification, measured results, cleanup, verified TestPyPI development artifacts and the signed release candidate. + +### Post-Close Delivery + +Stable publishing, tag, immutable Release, registry verification and issue closure follow explicit owner authorization. + +### Handoff Notes + +Preserve the exact reviewed commits and report unverified scenarios explicitly. + ## 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). diff --git a/changelog.d/368.bugfix.md b/changelog.d/368.bugfix.md new file mode 100644 index 00000000..45fe7802 --- /dev/null +++ b/changelog.d/368.bugfix.md @@ -0,0 +1 @@ +Qualify bounded truncated reads, capped searches, PCRE and supported exclusion pathspecs for local incremental review. Reuse unchanged groups after verifying the native-visible result against immutable Git inputs. diff --git a/changelog.d/370.bugfix.md b/changelog.d/370.bugfix.md new file mode 100644 index 00000000..87980326 --- /dev/null +++ b/changelog.d/370.bugfix.md @@ -0,0 +1 @@ +Restore ordinary GitLab merge request reviews and posting on Runner checkouts with an external Git configuration include. Qualify the immutable diff using a private Git view that omits the external configuration and preserves tracked-file exclusion checks. 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/development.md b/docs/development.md index db082db4..1fbf0585 100644 --- a/docs/development.md +++ b/docs/development.md @@ -40,11 +40,19 @@ 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. +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 and retry only the affected job +when appropriate. + +When measuring CI latency, identify the required checks and their source apps +from the target branch ruleset. Measure the interval from the last required +success to the PR merge. Report that interval separately from runner time and +advisory queue time. A job that never received a runner contributes zero runner +time. An advisory cancellation can leave the workflow run marked failed even +when all required checks passed. + Bandit scans only the supported runtime package at medium-or-higher severity and confidence; tests and synthetic fixtures are outside that bounded gate. @@ -69,9 +77,14 @@ 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. +ready jobs required and confirm the successful checks for the current candidate +and target before merging. GitHub Actions reports `analyze-python` and the code +scanning app reports the separate required `CodeQL` result. Finalize the title +and body while the PR is a draft. GitHub sends title, body and base changes as +`edited` events, and the required workflows listen for them to validate +retargeting. Metadata edits after readiness can restart checks for the same +test merge. 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`. diff --git a/docs/gitlab.md b/docs/gitlab.md index a93f5a48..1c6045c0 100644 --- a/docs/gitlab.md +++ b/docs/gitlab.md @@ -171,11 +171,18 @@ publication: a missing receipt stays in the job and cannot publish findings or replace the previous review. A present v9-v13 receipt remains readable for historical diagnostics but blocks a new current MR publication. -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. +For ordinary merge requests, a direct GitLab Runner checkout can use an +unconditional `include.path` in `.git/config`. Review and posting each +construct a private Git view from the reviewed commit and local objects. +The generated config preserves the direct `core.ignoreCase` setting and +omits the external file, credential helpers and URL rewrites. Tracked ignored +files still require verifiable exclusion evidence before publication. + +Use a direct `.git` directory. Conditional includes, separate worktree +configuration and alternate object stores are unsupported on this isolated +route. A change to a submodule pointer uses the separate gitlink qualification +path. The ordinary projection accepts regular files; changed symlinks and +unsupported file-type transitions 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. diff --git a/docs/local.md b/docs/local.md index ea6ffefb..9229a506 100644 --- a/docs/local.md +++ b/docs/local.md @@ -187,13 +187,19 @@ 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 +an immutable file and the file remains unchanged. This covers reads past EOF +and native reads limited by line count, line length or rendered bytes. The +verification includes the visible UTF-8 text, range, line addresses and +omission notices. An edit in a hidden part of the read file requires fresh +review of the dependent group. + +The toolkit repeats bounded `code_search`, `file_find`, `file_read_diff` and +built-in evidence queries on the new inputs. For a capped native code search it +compares the first 100 matches, their order and the matching-file count. +Supported searches include literal and PCRE patterns and bounded +`:(exclude)` file patterns. A changed visible result, an unsupported pathspec, +a search that exceeds resource limits, or an incomplete evidence page calls +for fresh review of 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 diff --git a/docs/review-decision-flow.md b/docs/review-decision-flow.md index 4fccf5a0..6fd8564e 100644 --- a/docs/review-decision-flow.md +++ b/docs/review-decision-flow.md @@ -138,7 +138,7 @@ flowchart TD 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, local --> preview - gitlink_check -- No, GitLab --> ordinary_projection[Freeze immutable ordinary diff
and Git selection inputs] + gitlink_check -- No, GitLab --> ordinary_projection[Freeze immutable ordinary diff and Git inputs;
isolate unconditional Runner include] 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] diff --git a/docs/security.md b/docs/security.md index 21fcf930..9aef021d 100644 --- a/docs/security.md +++ b/docs/security.md @@ -199,6 +199,28 @@ 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. +GitLab Runner may externalize checkout credentials and Git settings through an +unconditional `include.path` in the direct checkout's local config. Runner +owns that configuration. Its settings grant no authority to select fewer files +for review, mark a partial review complete, or publish configuration values. +For an ordinary GitLab MR in this layout, preview and native review use a +private Git directory with HEAD and index derived from the reviewed commit. +The view uses local objects, disables Git transports and lazy fetches, and +imports only the direct case-sensitivity setting and bounded checkout metadata +for attributes, exclusions and shallow history. The external config is outside +this projection. This boundary governs Git selection; the Runner and the OS +account executing the job remain trusted. + +Review checks the projection again after OCR returns. Before a GitLab write, +posting independently reconstructs selection and checks coverage. Missing +proof stops publication; a proven exclusion blocks automatic approval. +Conditional includes and changed gitlinks retain their separate restrictions. +When hardening expands a check to another MR type, qualify both ordinary Runner +layouts (with and without an include) through review and posting. Include a +tracked, ignored change so the test observes partial coverage as well as a +successful review. This guards against denying routine reviews or silently +approving work that OCR skipped. + 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 diff --git a/src/ocr_toolkit/evidence/collect.py b/src/ocr_toolkit/evidence/collect.py index 76ddaffb..fd76b301 100644 --- a/src/ocr_toolkit/evidence/collect.py +++ b/src/ocr_toolkit/evidence/collect.py @@ -21,6 +21,7 @@ from ocr_toolkit.evidence.repository import ( GitRepositoryReader, RepositoryEvidenceError, + RepositoryObject, build_file_snapshot, file_deltas, ) @@ -116,8 +117,20 @@ def collect_repository_evidence( base_sha, head_sha = _commit_refs(reader, base_ref, head_ref) changed = reader.changed_paths(base_sha, head_sha) policy_sha = reader.resolve_commit(policy_ref) if policy_ref is not None else base_sha - base = build_file_snapshot(reader, base_sha, RefRole.BASE, paths=changed) - head = build_file_snapshot(reader, head_sha, RefRole.HEAD, paths=changed) + tree_entries: dict[str, tuple[RepositoryObject, ...]] = {} + + def entries_at(commit_sha: str) -> tuple[RepositoryObject, ...]: + """Share the immutable tree only within this collection call.""" + if commit_sha not in tree_entries: + tree_entries[commit_sha] = reader.list_objects(commit_sha) + return tree_entries[commit_sha] + + base = build_file_snapshot( + reader, base_sha, RefRole.BASE, paths=changed, entries=entries_at(base_sha) + ) + head = build_file_snapshot( + reader, head_sha, RefRole.HEAD, paths=changed, entries=entries_at(head_sha) + ) base_paths = {record.source_path for record in base.records} head_paths = {record.source_path for record in head.records} base_coverage = [] @@ -128,6 +141,7 @@ def collect_repository_evidence( RefRole.BASE, changed_paths=changed, coverage_sink=base_coverage, + entries=entries_at(base_sha), ) if include_policy_records: policy_facts, policy_diagnostics = collect_ref_facts( @@ -135,6 +149,7 @@ def collect_repository_evidence( policy_sha, RefRole.POLICY, changed_paths=changed, + entries=entries_at(policy_sha), ) policy_facts = [record for record in policy_facts if record.kind in POLICY_KINDS] else: @@ -151,6 +166,7 @@ def collect_repository_evidence( RefRole.HEAD, changed_paths=changed, coverage_sink=head_coverage, + entries=entries_at(head_sha), ) base = EvidenceSnapshot( base.ref, @@ -306,10 +322,18 @@ def collect_repository_evidence( else: try: target_files = build_file_snapshot( - reader, target_sha, RefRole.TARGET, paths=changed + reader, + target_sha, + RefRole.TARGET, + paths=changed, + entries=entries_at(target_sha), ) target_facts, target_fact_diagnostics = collect_ref_facts( - reader, target_sha, RefRole.TARGET, changed_paths=changed + reader, + target_sha, + RefRole.TARGET, + changed_paths=changed, + entries=entries_at(target_sha), ) except RepositoryEvidenceError as exc: if str(exc) != "repository tree exceeds the bounded entry limit": diff --git a/src/ocr_toolkit/evidence/collectors/orchestration.py b/src/ocr_toolkit/evidence/collectors/orchestration.py index d67a249b..a58d8a7c 100644 --- a/src/ocr_toolkit/evidence/collectors/orchestration.py +++ b/src/ocr_toolkit/evidence/collectors/orchestration.py @@ -72,6 +72,7 @@ def collect_ref_facts( *, changed_paths: Iterable[str] = (), coverage_sink: list[CoverageRecord] | None = None, + entries: tuple[RepositoryObject, ...] | None = None, ) -> tuple[list[EvidenceRecord], list[str]]: """Collect supported facts from one immutable tree with explicit diagnostics.""" @@ -84,7 +85,8 @@ def collect_ref_facts( ) changed_exact = tuple(sorted(set(changed_paths))) changed = {path.casefold() for path in changed_exact} - entries = reader.list_objects(commit_sha) + if entries is None: + entries = reader.list_objects(commit_sha) entries_by_path = {entry.path: entry for entry in entries} role_paths = selected_role_paths(tuple(entry.path for entry in entries)) topology_entries = tuple( diff --git a/src/ocr_toolkit/evidence/gitlink_projection.py b/src/ocr_toolkit/evidence/gitlink_projection.py index 1b388f75..6b1c151e 100644 --- a/src/ocr_toolkit/evidence/gitlink_projection.py +++ b/src/ocr_toolkit/evidence/gitlink_projection.py @@ -10,8 +10,10 @@ import stat import subprocess import time -from contextlib import ExitStack +from collections.abc import Iterator +from contextlib import ExitStack, contextmanager from dataclasses import dataclass +from dataclasses import field as dataclass_field from pathlib import Path from ocr_toolkit.common.filesystem import open_private_parent_directory, same_file_identity @@ -51,6 +53,14 @@ _REVIEW_SELECTION_SCHEMA = "ocr.review-selection/v1" _LOCAL_INPUTS = (".gitignore", ".gitmodules", ".gitattributes") _GIT_METADATA_INPUTS = ("config", "config.worktree", "info/attributes", "info/exclude") +_GIT_CONFIG_INCLUDE = re.compile(rb"(?im)^\s*\[\s*include(if)?(?:\s|\])") +_GIT_VIEW_NAME = "ordinary-git-view" +_GIT_VIEW_COPIED = ("info/attributes", "info/exclude", "shallow") +_GIT_VIEW_INPUTS = ("config", "HEAD", "index", *_GIT_VIEW_COPIED) + + +class GitProjectionConfigError(RepositoryEvidenceError): + """A fixed diagnostic about local Git config isolation.""" @dataclass(frozen=True, slots=True) @@ -95,6 +105,7 @@ class GitlinkProjection: line_counts: tuple[tuple[str, int, int], ...] environment: tuple[tuple[str, str], ...] input_digest: str + git_view_digest: str | None = None def child_environment(self) -> dict[str, str]: return dict(self.environment) @@ -116,7 +127,14 @@ class ReviewSelection: excluded: tuple[PreviewExclusion, ...] -def _read_input(root: int, path: Path) -> bytes | None: +@dataclass(frozen=True, slots=True) +class _GitInputSnapshot: + digest: str + view_config: bytes | None = dataclass_field(repr=False) + view_files: tuple[tuple[str, bytes], ...] = dataclass_field(repr=False) + + +def _read_input(root: int, path: Path, *, limit: int = _GIT_INPUT_LIMIT) -> bytes | None: parent = root try: for component in path.parts[:-1]: @@ -138,7 +156,7 @@ def _read_input(root: int, path: Path) -> bytes | None: 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: + if not stat.S_ISREG(metadata.st_mode) or metadata.st_size > 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: @@ -146,11 +164,19 @@ def _read_input(root: int, path: Path) -> bytes | None: if ( not stat.S_ISREG(opened.st_mode) or not same_file_identity(opened, metadata) - or opened.st_size > _GIT_INPUT_LIMIT + or opened.st_size > 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: + with os.fdopen(descriptor, "rb", closefd=False) as stream: + payload = stream.read(limit + 1) + after = os.fstat(descriptor) + named = os.stat(path.name, dir_fd=parent, follow_symlinks=False) + if ( + len(payload) != opened.st_size + or not same_file_identity(after, named) + or (opened.st_size, opened.st_mtime_ns, opened.st_ctime_ns) + != (after.st_size, after.st_mtime_ns, after.st_ctime_ns) + ): raise RepositoryEvidenceError("OCR local Git input changed or is too large") return payload finally: @@ -162,7 +188,51 @@ def _read_input(root: int, path: Path) -> bytes | None: os.close(parent) -def _input_digest(root: Path, plan: GitlinkInputPlan) -> str: +@contextmanager +def _direct_git_input(root: Path) -> Iterator[tuple[int, int]]: + with ExitStack() as stack: + try: + root_fd, git_name = open_private_parent_directory(root / ".git", 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: + raise GitProjectionConfigError( + "OCR Git projection requires a direct Git directory" + ) from exc + yield root_fd, git_fd + + +def _input_digest_frame(path: Path, payload: bytes | None) -> bytes: + data = b"M" if payload is None else b"P" + hashlib.sha256(payload).digest() + return str(path).encode("utf-8") + b"\0" + data + + +def _validate_direct_git_store(git_fd: int) -> os.stat_result: + try: + with ExitStack() as stack: + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + objects = os.open("objects", flags, dir_fd=git_fd) + stack.callback(os.close, objects) + try: + info = os.open("info", flags, dir_fd=objects) + except FileNotFoundError: + return os.fstat(objects) + stack.callback(os.close, info) + for name in ("alternates", "http-alternates"): + try: + os.stat(name, dir_fd=info, follow_symlinks=False) + except FileNotFoundError: + continue + raise GitProjectionConfigError("OCR Git config isolation requires local objects") + return os.fstat(objects) + except OSError as exc: + raise GitProjectionConfigError("OCR Git config isolation requires local objects") from exc + + +def _input_snapshot( + root: Path, plan: GitlinkInputPlan, *, allow_ordinary_include: bool +) -> _GitInputSnapshot: paths = {Path(path) for path in _LOCAL_INPUTS} git_dir = Path(".git") paths.update(git_dir / path for path in _GIT_METADATA_INPUTS) @@ -173,36 +243,130 @@ def _input_digest(root: Path, plan: GitlinkInputPlan) -> str: break paths.update((directory / ".gitignore", directory / ".gitattributes")) digest = hashlib.sha256() - 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 + view_config = None + metadata = {} + with _direct_git_input(root) as (root_fd, git_fd): 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()) + if payload is not None and path in configs: + includes = _GIT_CONFIG_INCLUDE.finditer(payload.removeprefix(b"\xef\xbb\xbf")) + for include in includes: + if not allow_ordinary_include or path.name != "config" or include[1]: + raise GitProjectionConfigError( + "OCR local Git config includes are unsupported for this review" + ) + view_config = payload + if path.is_relative_to(git_dir): + metadata[path.relative_to(git_dir).as_posix()] = payload + digest.update(_input_digest_frame(path, payload)) + if view_config is not None: + if ( + metadata["config.worktree"] is not None + or _read_input(git_fd, Path("commondir")) is not None + ): + raise GitProjectionConfigError( + "OCR Git config isolation does not support separate common or worktree config" + ) + objects = _validate_direct_git_store(git_fd) + digest.update(f"objects\0{objects.st_dev}:{objects.st_ino}\0".encode("ascii")) + metadata["shallow"] = _read_input(git_fd, Path("shallow")) + digest.update(_input_digest_frame(git_dir / "shallow", metadata["shallow"])) + view_files = tuple( + (name, payload) for name in _GIT_VIEW_COPIED if (payload := metadata.get(name)) is not None + ) + return _GitInputSnapshot(digest.hexdigest(), view_config, view_files) + + +def _private_git_view_digest(path: Path) -> str: + digest = hashlib.sha256() + try: + descriptor = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + for name in _GIT_VIEW_INPUTS: + item = Path(name) + limit = 2 * _DIFF_OUTPUT_LIMIT if name == "index" else _GIT_INPUT_LIMIT + digest.update(_input_digest_frame(item, _read_input(descriptor, item, limit=limit))) + finally: + os.close(descriptor) + except (OSError, ValueError) as exc: + raise GitProjectionConfigError("OCR isolated Git config could not be verified") from exc return digest.hexdigest() +def _direct_ignore_case(config: bytes, home: Path, environment: dict[str, str]) -> bytes: + # Ask Git to decode only one boolean in the pinned direct config. The + # external configuration is never opened, copied or passed to OCR. + completed = subprocess.run( + [ + *read_only_git_prefix(), + "config", + "--no-includes", + "--file", + "-", + "--type=bool", + "--get", + "core.ignoreCase", + ], + input=config, + capture_output=True, + cwd=home, + env=environment, + timeout=_GIT_TIMEOUT_SECONDS, + check=False, + ) + if completed.returncode == 1 and not completed.stdout and not completed.stderr: + return b"false" + if ( + completed.returncode == 0 + and not completed.stderr + and completed.stdout in (b"true\n", b"false\n") + ): + return completed.stdout.rstrip(b"\n") + raise GitProjectionConfigError("OCR could not read the direct Git config safely") + + +def _prepare_private_git_view( + root: Path, + home: Path, + head: str, + environment: dict[str, str], + snapshot: _GitInputSnapshot, +) -> Path: + view = home / _GIT_VIEW_NAME + assert snapshot.view_config is not None + try: + ignore_case = _direct_ignore_case(snapshot.view_config, home, environment) + view.mkdir(mode=0o700) + for name in ("info", "objects", "refs"): + (view / name).mkdir(mode=0o700) + for name, payload in snapshot.view_files: + (view / name).write_bytes(payload) + (view / "config").write_bytes( + b"[core]\n\trepositoryformatversion = 0\n\tbare = false\n" + b"\thooksPath = /dev/null\n\tignoreCase = " + ignore_case + b"\n" + ) + (view / "HEAD").write_text(f"{head}\n", encoding="ascii") + environment.update( + GIT_DIR=str(view), + GIT_WORK_TREE=str(root), + GIT_OBJECT_DIRECTORY=str(root / ".git" / "objects"), + GIT_ALLOW_PROTOCOL="", + GIT_NO_LAZY_FETCH="1", + ) + # Preserve attribute lookup for files absent in the checkout using only + # the reviewed tree. No checkout or filter execution is requested. + _git_output(root, ["read-tree", "--", head], environment) + except GitProjectionConfigError: + raise + except (OSError, ValueError, subprocess.TimeoutExpired) as exc: + raise GitProjectionConfigError("OCR could not isolate local Git configuration") from exc + return view + + def _projection_environment(plan: GitlinkInputPlan) -> dict[str, str]: # The same inherited environment is frozen once for preview and production. environment = { @@ -696,13 +860,24 @@ def _patch_fingerprints( def make_gitlink_projection( - reader: GitRepositoryReader, plan: GitlinkInputPlan + reader: GitRepositoryReader, + plan: GitlinkInputPlan, + *, + ordinary_config_home: Path | None = None, ) -> GitlinkProjection: """Qualify the original range and freeze exact OCR Git inputs.""" environment = _projection_environment(plan) root = reader.root - input_digest = _input_digest(root, plan) + allow_ordinary_include = ordinary_config_home is not None and not plan.changes + initial_inputs = _input_snapshot(root, plan, allow_ordinary_include=allow_ordinary_include) + view_digest = None + if initial_inputs.view_config is not None: + assert ordinary_config_home is not None + view = _prepare_private_git_view( + root, ordinary_config_home, plan.head_sha, environment, initial_inputs + ) + view_digest = _private_git_view_digest(view) merge_base = ( _git_output(root, ["merge-base", plan.base_sha, plan.head_sha], environment) .decode("ascii") @@ -726,7 +901,10 @@ def make_gitlink_projection( ): raise RepositoryEvidenceError("OCR non-regular ordinary change is unsupported") fingerprints, line_counts = _patch_fingerprints(root, plan, environment, projected) - if input_digest != _input_digest(root, plan): + if ( + initial_inputs.digest + != _input_snapshot(root, plan, allow_ordinary_include=allow_ordinary_include).digest + ): raise RepositoryEvidenceError("OCR local Git inputs changed during qualification") return GitlinkProjection( plan, @@ -736,7 +914,8 @@ def make_gitlink_projection( fingerprints, line_counts, tuple(sorted(environment.items())), - input_digest, + initial_inputs.digest, + view_digest, ) @@ -744,12 +923,19 @@ def verify_gitlink_projection(reader: GitRepositoryReader, projection: GitlinkPr """Recheck every original endpoint, consulted input and projected record.""" current = plan_review_input(reader, projection.plan.base_sha, projection.plan.head_sha) + isolate = projection.git_view_digest is not None if ( current != projection.plan - or _input_digest(reader.root, projection.plan) != projection.input_digest + or _input_snapshot(reader.root, projection.plan, allow_ordinary_include=isolate).digest + != projection.input_digest ): raise RepositoryEvidenceError("OCR gitlink review inputs drifted") environment = projection.child_environment() + if ( + isolate + and _private_git_view_digest(Path(environment["GIT_DIR"])) != projection.git_view_digest + ): + raise GitProjectionConfigError("OCR isolated Git config changed during review") if ( _raw_diff(reader.root, projection.plan, environment, reveal_gitlinks=True) != projection.original_diff diff --git a/src/ocr_toolkit/evidence/repository.py b/src/ocr_toolkit/evidence/repository.py index b32f9798..8a25b15d 100644 --- a/src/ocr_toolkit/evidence/repository.py +++ b/src/ocr_toolkit/evidence/repository.py @@ -348,6 +348,7 @@ def grep_tree( patterns: tuple[str, ...], *, case_sensitive: bool, + use_perl_regexp: bool = False, ) -> bytes: """Return bounded, NUL-addressed immutable tree matches, without text converters.""" @@ -366,7 +367,7 @@ def grep_tree( args.append("-i") args.extend( [ - "-F", + "-P" if use_perl_regexp else "-F", "-n", "-z", "--no-color", @@ -381,7 +382,7 @@ def grep_tree( ) result = self._run_streamed( args, - timeout=self._timeout(10), + timeout=min(self._timeout(10), 10), text=False, local_only=True, max_bytes=MAX_GIT_GREP_BYTES, @@ -959,8 +960,9 @@ def build_file_snapshot( role: RefRole, *, paths: tuple[str, ...] | None = None, + entries: tuple[RepositoryObject, ...] | None = None, ) -> EvidenceSnapshot: - """Build repository-file facts for a commit without reading file contents.""" + """Build file facts, optionally using entries already read for this commit.""" if role not in {RefRole.BASE, RefRole.HEAD, RefRole.TARGET}: raise RepositoryEvidenceError("file snapshot role must be base, head, or target") @@ -973,7 +975,9 @@ def build_file_snapshot( if role in {RefRole.BASE, RefRole.TARGET} else TrustClass.SOURCE_REPOSITORY ) - for entry in reader.list_objects(sha): + if entries is None: + entries = reader.list_objects(sha) + for entry in entries: if selected is not None and entry.path not in selected: continue if entry.is_symlink: diff --git a/src/ocr_toolkit/local_incremental_dependencies.py b/src/ocr_toolkit/local_incremental_dependencies.py index e7fc9bd2..04e1a544 100644 --- a/src/ocr_toolkit/local_incremental_dependencies.py +++ b/src/ocr_toolkit/local_incremental_dependencies.py @@ -30,6 +30,7 @@ RUN_ID, DependencyScope, IncrementalError, + IncrementalSearchError, ToolReplay, canonical_json, literal_path, @@ -39,7 +40,22 @@ from ocr_toolkit.review_range import ReviewRange from ocr_toolkit.review_trace import NativeTraceSource +_MAX_READ_LINES = 500 +_MAX_READ_LINE_BYTES = 2048 +_MAX_READ_BODY_BYTES = 256 * 1024 +_MAX_READ_METADATA_BYTES = 512 # Header and notes, excluding the file path. _READ_RANGE = re.compile(r"LINE_RANGE: ([0-9]{1,10})-([0-9]{1,10})\Z") +_READ_LINE_NOTE = ( + f"\nNote: Lines longer than {_MAX_READ_LINE_BYTES} bytes were cut mid-line and the omitted " + "bytes are not part of this result. Reason about the visible part only.\n" +).encode() +_READ_BODY_NOTE = ( + f"\nNote: Output truncated at {_MAX_READ_BODY_BYTES} bytes. " + "Re-read the remaining lines with a narrower start_line/end_line range.\n" +).encode() +_READ_RANGE_NOTE = ( + f"\nNote: Results truncated to {_MAX_READ_LINES} lines. Please narrow your line range.\n" +).encode() _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 @@ -84,9 +100,11 @@ class _ReadObservation: path: str revision: str start: int - end: int + requested_end: int | None total: int - content: bytes | None = field(repr=False) + result_digest: bytes | None = field(repr=False) + result_size: int = 0 + truncated: bool = False def _read_observation( @@ -127,50 +145,105 @@ def _read_observation( ) 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) + return _ReadObservation(path, revision, requested_start, requested_end, total, None) + header, truncation, source_range, _ = 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) - if total_match is None or range_match is None or truncated != "IS_TRUNCATED: false": - raise IncrementalError("native read has no complete matching file response") + if ( + total_match is None + or range_match is None + or truncation not in {"IS_TRUNCATED: true", "IS_TRUNCATED: false"} + ): + raise IncrementalError("native read has no matching file response") total = int(total_match[1]) - start, end = map(int, range_match.groups()) - if not 1 <= start == requested_start <= end == min( - total, requested_end or total - ) <= 1_000_000_000 or not body.endswith("\n"): + start, shown_end = map(int, range_match.groups()) + end = min(total, requested_end or total) + if not start == requested_start <= shown_end <= end <= 1_000_000_000: raise IncrementalError("native read response range does not match its inputs") - lines = body[:-1].split("\n") - if len(lines) != end - start + 1: - raise IncrementalError("native read response has incomplete source lines") - contents = [] - for number, line in enumerate(lines, start): - prefix = f"{number}|" - if not line.startswith(prefix): - raise IncrementalError("native read response has invalid line addresses") - contents.append(line.removeprefix(prefix)) - return _ReadObservation(path, revision, start, end, total, _digest(contents)) + raw = response.encode() + if len(raw) > _MAX_READ_BODY_BYTES + _MAX_READ_METADATA_BYTES + len(path): + raise IncrementalError("native read exceeds its result budget") + truncated = truncation == "IS_TRUNCATED: true" + if truncated and not raw.endswith((_READ_LINE_NOTE, _READ_BODY_NOTE, _READ_RANGE_NOTE)): + raise IncrementalError("native read has an unrecognized truncation notice") + return _ReadObservation( + path, + revision, + requested_start, + requested_end, + total, + hashlib.sha256(raw).digest(), + len(raw), + truncated, + ) + + +def _read_line(line: bytes) -> tuple[bytes, bool]: + size = len(line) - int(line.endswith(b"\r")) + if size <= _MAX_READ_LINE_BYTES: + return line[:size], False + cut = _MAX_READ_LINE_BYTES + # The source has already been validated as UTF-8. Back off over continuation bytes. + while (line[cut] & 0xC0) == 0x80: + cut -= 1 + return line[:cut] + f" …[line truncated, {size - cut} more bytes omitted]".encode(), True + + +def _matches_read(observation: _ReadObservation, lines: list[bytes]) -> bool: + if observation.total != len(lines): + return False + if observation.result_digest is None: + return observation.start > len(lines) + + start = observation.start + end = min(observation.requested_end or len(lines), len(lines)) + capped_end = min(end, start + _MAX_READ_LINES - 1) + line_cut = body_cut = False + body = bytearray() + shown_end = start - 1 + for number in range(start, capped_end + 1): + text, cut = _read_line(lines[number - 1]) + row = f"{number}|".encode() + text + b"\n" + size = len(body) + len(row) + if size > _MAX_READ_BODY_BYTES: + body_cut = True + break + # An impossible short trace result cannot drive reconstruction of a larger body. + if size > observation.result_size: + return False + body.extend(row) + shown_end = number + line_cut |= cut + + range_cut = capped_end < end + truncated = "true" if line_cut or body_cut or range_cut else "false" + header = ( + f"File: {observation.path} (Total lines: {observation.total})\n" + f"IS_TRUNCATED: {truncated}\nLINE_RANGE: {start}-{shown_end}\n" + ).encode() + response = bytearray(header) + response.extend(body) + if line_cut: + response.extend(_READ_LINE_NOTE) + if body_cut: + response.extend(_READ_BODY_NOTE) + if range_cut: + response.extend(_READ_RANGE_NOTE) + return ( + len(response) == observation.result_size + and hashlib.sha256(response).digest() == observation.result_digest + ) def _verified_windows(observations: set[_ReadObservation], blob: bytes) -> set[_ReadObservation]: if b"\0" in blob: return set() try: - lines = blob.decode("utf-8").split("\n") if blob else [] + blob.decode("utf-8") except UnicodeError: return set() - return { - observation - for observation in observations - if len(lines) == observation.total - 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 - ) - } + lines = blob.split(b"\n") if blob else [] + return {observation for observation in observations if _matches_read(observation, lines)} def _groups(value: object, selected: set[str]) -> dict[str, tuple[str, ...]]: @@ -297,14 +370,14 @@ def _group_record(self, record: dict[str, Any], kind: str) -> None: if kind == "llm_request": group.main_request |= task == "main_task" elif kind == "llm_response": - self._requested_tools(record.get("tool_calls"), group) + self._requested_tools(record.get("tool_calls"), group, task=task) elif kind == "llm_error": group.reasons.add("llm_error") else: self._tool(record, group) @staticmethod - def _requested_tools(value: object, group: _GroupObservation) -> None: + def _requested_tools(value: object, group: _GroupObservation, *, task: str) -> None: """Check model requests that native may reject before recording execution.""" if value is None: @@ -315,6 +388,10 @@ def _requested_tools(value: object, group: _GroupObservation) -> None: for item in value: if not isinstance(item, dict) or not isinstance(name := item.get("name"), str): group.reasons.add("invalid_arguments") + elif name == "approve_all_comments" and task == "review_filter_task": + # Native recognizes this response without dispatching a tool or removing a finding. + if item.get("arguments") != "{}": + group.reasons.add("invalid_arguments") elif name == "code_comment": group.requested_comments += 1 elif name not in _GROUP_CALLS: @@ -376,6 +453,8 @@ def _tool(self, record: dict[str, Any], group: _GroupObservation) -> None: group.reasons.add(reason) else: group.reasons.add("unsupported_tool") + except IncrementalSearchError as exc: + group.reasons.add(exc.reason) except (TypeError, ValueError, RecursionError): if tool == "code_comment" and ok: # An ambiguously authored finding can be filed against a different group. @@ -543,14 +622,18 @@ def all_unqualified(reason: str) -> DependencyAssessment: for key in sorted(candidates): group = candidates[key] rejected = set() - if not group.reads <= verified: - rejected.add("read_verification") + rejected.update( + "read_truncated" if item.truncated else "read_verification" + for item in group.reads - verified + ) 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)) + rejected.add( + replay_verifier.failure_reason(replay) or _replay_reason(replay.tool) + ) if rejected: reasons.update(rejected) continue diff --git a/src/ocr_toolkit/local_incremental_replay.py b/src/ocr_toolkit/local_incremental_replay.py index 66e593f0..53c4998a 100644 --- a/src/ocr_toolkit/local_incremental_replay.py +++ b/src/ocr_toolkit/local_incremental_replay.py @@ -16,10 +16,15 @@ TOOL_NAME, call_named_tool, ) -from ocr_toolkit.evidence.repository import GitRepositoryReader, RepositoryObject +from ocr_toolkit.evidence.repository import ( + GitRepositoryReader, + RepositoryEvidenceError, + RepositoryObject, +) from ocr_toolkit.evidence.store import EvidenceStore from ocr_toolkit.local_incremental_state import ( IncrementalError, + IncrementalSearchError, ToolReplay, canonical_json, literal_path, @@ -42,6 +47,7 @@ _MAX_MATCHES = 100 _MAX_RESULT_BYTES = 256 * 1024 _MAX_REPLAY_CALLS = 64 +_SEARCH_CAP_PREFIX = f"Note: Showing the first {_MAX_MATCHES} matches across " def _complete_evidence_result(tool: str, args: dict[str, Any], payload: dict[str, Any]) -> bool: @@ -79,6 +85,8 @@ def _complete_evidence_result(tool: str, args: dict[str, Any], payload: dict[str def _result_digest(tool: str, args: dict[str, Any], result: str) -> str: raw = result.encode() if not raw or len(raw) > _MAX_RESULT_BYTES: + if tool == "code_search" and _capped_search(args, result): + raise IncrementalSearchError("search_capped", "native capped search exceeds its budget") raise IncrementalError("incremental tool result exceeds its replay budget") if tool in _EVIDENCE_TOOLS: payload = unique_json(raw) @@ -91,7 +99,12 @@ def _result_digest(tool: str, args: dict[str, Any], result: str) -> str: 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)) + return ToolReplay( + tool, + raw.decode(), + _result_digest(tool, args, result), + capped_search=tool == "code_search" and _capped_search(args, result), + ) def _arg_texts(args: dict[str, Any]) -> Iterator[str]: @@ -102,19 +115,25 @@ def _arg_texts(args: dict[str, Any]) -> Iterator[str]: yield from value +def _capped_search(args: dict[str, Any], result: str) -> bool: + if args.get("side") == "old": + return result.startswith("SIDE: old\nREVISION: ") and result.split("\n", 2)[-1].startswith( + _SEARCH_CAP_PREFIX + ) + return result.startswith(_SEARCH_CAP_PREFIX) + + 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") + if not raw.endswith(b"\n"): + raise IncrementalError("native search output is incomplete") 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") + rows = raw[:-1].split(b"\n") matches: dict[str, list[str]] = {} - for row in rows: + for index, row in enumerate(rows): name, number, value = row.split(b"\0", 2) - path, text = name.removeprefix(prefix).decode(), value.decode() + path = name.removeprefix(prefix).decode() if ( not name.startswith(prefix) or not literal_path(path) @@ -122,10 +141,19 @@ def _render_search(raw: bytes, revision: str) -> str: or b"\0" in value ): raise IncrementalError("native search match is ambiguous") - matches.setdefault(path, []).append(f"{int(number)}|{text}\n") - return "".join( + lines = matches.setdefault(path, []) + if index < _MAX_MATCHES: + lines.append(f"{int(number)}|{value.decode()}\n") + note = "" + if len(rows) > _MAX_MATCHES: + note = ( + f"{_SEARCH_CAP_PREFIX}{len(matches)} matching files. Some files are partially shown " + "or omitted entirely. Narrow file_patterns to see the rest.\n" + ) + return note + "".join( f"File: {path}\nMatch lines: {len(lines)}\n{''.join(lines)}\n" for path, lines in matches.items() + if lines ) @@ -181,6 +209,7 @@ class ReplayVerifier: 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) + _failures: dict[tuple[str, str], str | None] = field(default_factory=dict) _diffs: dict[str, str] | None = None def verifies(self, replay: ToolReplay) -> bool: @@ -192,13 +221,27 @@ def verifies(self, replay: ToolReplay) -> bool: try: args = validated_replay_arguments(replay.tool, replay.arguments.encode()) if all(self.authorize_text(value) for value in _arg_texts(args)): + self._failures[key] = None self._observed[key] = _result_digest( replay.tool, args, self._execute(replay.tool, args) ) + except IncrementalSearchError as exc: + self._failures[key] = exc.reason except (ValueError, OSError, TimeoutExpired, RecursionError): pass return self._observed[key] == replay.result + def failure_reason(self, replay: ToolReplay) -> str | None: + """Explain a failed search comparison without including its inputs or output.""" + + key = (replay.tool, replay.arguments) + if self._observed.get(key) == replay.result: + return None + reason = self._failures.get(key) + if reason is None and replay.capped_search and key in self._failures: + return "search_capped" + return reason + def _tree(self, revision: str) -> tuple[RepositoryObject, ...]: if revision not in self.trees: self.trees[revision] = self.reader.list_objects(revision, local_only=True) @@ -245,13 +288,20 @@ def _execute(self, tool: str, args: dict[str, Any]) -> str: 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( + regex = args.get("use_perl_regexp", False) + try: + raw_matches = self.reader.grep_tree( revision, args["search_text"], tuple(args.get("file_patterns", ())), case_sensitive=args.get("case_sensitive", False), - ), - revision, - ) + use_perl_regexp=regex, + ) + except (RepositoryEvidenceError, TimeoutExpired) as exc: + if regex: + raise IncrementalSearchError( + "search_regex", "native search regex could not be replayed completely" + ) from exc + raise + result = _render_search(raw_matches, 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 d2285b87..6d9649b8 100644 --- a/src/ocr_toolkit/local_incremental_state.py +++ b/src/ocr_toolkit/local_incremental_state.py @@ -90,6 +90,14 @@ class IncrementalError(ValueError): """Incremental review inputs or coverage could not be proved.""" +class IncrementalSearchError(IncrementalError): + """Carry a bounded diagnostic for an unverified native search.""" + + def __init__(self, reason: str, message: str) -> None: + super().__init__(message) + self.reason = reason + + @dataclass(frozen=True, slots=True) class ToolReplay: """Hold bounded admitted arguments and the digest of the witnessed result.""" @@ -97,6 +105,7 @@ class ToolReplay: tool: str arguments: str = field(repr=False) result: str + capped_search: bool = field(default=False, compare=False, repr=False) def payload(self) -> dict[str, str]: return {"tool": self.tool, "arguments": self.arguments, "result": self.result} @@ -173,6 +182,17 @@ def _query_text(value: object) -> bool: ) +def _search_pathspec(value: object) -> bool: + if not isinstance(value, str) or len(value) > 256: + return False + pattern = value.removeprefix(":(exclude)") + return ( + _SEARCH_PATTERN.fullmatch(pattern) is not None + and not pattern.startswith("/") + and ".." not in pattern.split("/") + ) + + def validated_replay_arguments(tool: str, raw: bytes) -> dict[str, Any]: """Revalidate the closed argument families before any repository or MCP read.""" @@ -197,24 +217,27 @@ def validated_replay_arguments(tool: str, raw: bytes) -> dict[str, Any]: 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 - ) ) + if valid and search: + patterns = args.get("file_patterns", []) + if not ( + isinstance(patterns, list) + and len(patterns) <= 16 + and all(_search_pathspec(pattern) for pattern in patterns) + ): + raise IncrementalSearchError( + "search_pathspec", "incremental search pathspec is unsupported" + ) + if type(args.get("use_perl_regexp", False)) is not bool: + raise IncrementalSearchError( + "search_regex", "incremental search regex mode must be a boolean" + ) else: valid = ( args.keys() <= _EVIDENCE_REPLAY_FIELDS[tool] diff --git a/src/ocr_toolkit/posting/workflow.py b/src/ocr_toolkit/posting/workflow.py index 237dfd75..6e9ac8da 100644 --- a/src/ocr_toolkit/posting/workflow.py +++ b/src/ocr_toolkit/posting/workflow.py @@ -12,6 +12,7 @@ from collections.abc import Callable from dataclasses import replace from pathlib import Path +from tempfile import TemporaryDirectory from typing import Any from ocr_toolkit import review_analysis @@ -1011,33 +1012,39 @@ def verified_review_coverage( if identity.diff_base_sha is None: raise RepositoryEvidenceError("ordinary review has no original diff identity") - reader = GitRepositoryReader(Path.cwd()) + reader = GitRepositoryReader(Path.cwd(), local_only=True) 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 + with TemporaryDirectory(prefix="ocr-post-git-view-") as home: + projection = make_gitlink_projection(reader, plan, ordinary_config_home=Path(home)) + 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 + except OSError as exc: + raise RepositoryEvidenceError("OCR ordinary Git review inputs are unavailable") from exc def verified_no_model_repository_coverage(status: PreExecutionStatus) -> RepositoryCoverage: diff --git a/src/ocr_toolkit/reporting/incremental.py b/src/ocr_toolkit/reporting/incremental.py index f44c6ba4..bff09eb1 100644 --- a/src/ocr_toolkit/reporting/incremental.py +++ b/src/ocr_toolkit/reporting/incremental.py @@ -23,7 +23,11 @@ "native_counters", "native_trace", "no_evidence_summary", + "read_truncated", "read_verification", + "search_capped", + "search_pathspec", + "search_regex", "search_tool", "unsupported_tool", } diff --git a/src/ocr_toolkit/review_runner.py b/src/ocr_toolkit/review_runner.py index a29fd32e..8dbe712d 100644 --- a/src/ocr_toolkit/review_runner.py +++ b/src/ocr_toolkit/review_runner.py @@ -99,6 +99,7 @@ from ocr_toolkit.evidence.collect import collect_repository_evidence from ocr_toolkit.evidence.gitlink_projection import ( GitlinkProjection, + GitProjectionConfigError, PreviewExclusion, RawDiffEntry, ReviewSelection, @@ -1945,7 +1946,7 @@ def _verify_projection_after_execution(result_path: Path, projection: GitlinkPro """Reject review-input drift before any publication DLP work.""" try: - verify_gitlink_projection(GitRepositoryReader(Path.cwd()), projection) + verify_gitlink_projection(GitRepositoryReader(Path.cwd(), local_only=True), projection) except (RepositoryEvidenceError, OSError, subprocess.TimeoutExpired) as exc: _discard_unadmitted_result(result_path) raise ReviewRunnerError("OCR review inputs drifted during model execution") from exc @@ -2786,7 +2787,7 @@ def _run_background_qualified_review( ) return 2, qualification try: - verify_gitlink_projection(GitRepositoryReader(Path.cwd()), projection) + verify_gitlink_projection(GitRepositoryReader(Path.cwd(), local_only=True), projection) except (RepositoryEvidenceError, OSError, subprocess.TimeoutExpired) as exc: raise ReviewRunnerError("OCR review inputs drifted before model execution") from exc if state is not None: @@ -4218,7 +4219,7 @@ def _run_evidence_review( gitlink_detected = False review_plan = None try: - reader = GitRepositoryReader(Path.cwd()) + reader = GitRepositoryReader(Path.cwd(), local_only=True) 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: @@ -4234,7 +4235,11 @@ def _run_evidence_review( else: gitlink_detected = True elif review_plan is not None: - projection = make_gitlink_projection(reader, review_plan) + projection = make_gitlink_projection( + reader, + review_plan, + ordinary_config_home=session_home if not state.local else None, + ) except RepositoryEvidenceError as exc: if review_plan is not None and review_plan.changes: gitlink_detected = True @@ -4244,7 +4249,10 @@ def _run_evidence_review( except RepositoryEvidenceError: pass if not gitlink_detected: - raise ReviewRunnerError("immutable review coverage could not be qualified") from exc + reason = "immutable review coverage could not be qualified" + if isinstance(exc, GitProjectionConfigError): + reason += f": {exc}" + raise ReviewRunnerError(reason) from exc print( "OCR gitlink qualification: immutable changed pointer is outside the " "qualified subset; model review did not run", @@ -4408,6 +4416,13 @@ def _run_evidence_review( state.debug.capture("diagram.json", artifacts.diagram) if not state.analysis.enabled: state.debug.capture_native_trace() + if ( + (exit_code == 0 or partial) + and projection is not None + and projection.git_view_digest is not None + ): + # Check the model's isolated Git inputs before removing their private home. + _verify_projection_after_execution(result_path, projection) finally: try: try: @@ -4437,7 +4452,7 @@ def _run_evidence_review( forbidden += enrichment.forbidden_sources or tuple( ForbiddenValue(v, "other") for v in enrichment.forbidden_publication ) - if projection is not None: + if projection is not None and projection.git_view_digest is None: _verify_projection_after_execution(result_path, projection) usage, publication_filtered, publication = _finalize_ocr_result( result_path, diff --git a/tests/test_evidence_collectors.py b/tests/test_evidence_collectors.py index b0c1bdb6..8cb81e87 100644 --- a/tests/test_evidence_collectors.py +++ b/tests/test_evidence_collectors.py @@ -1133,6 +1133,46 @@ def test_changed_head_guidance_cannot_self_authorize_policy(tmp_path: Path) -> N assert not head_records +def test_collection_reads_each_immutable_tree_once( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _git(tmp_path, "init", "-q") + _git(tmp_path, "config", "user.email", "agent@example.invalid") + _git(tmp_path, "config", "user.name", "Synthetic Agent") + manifest = tmp_path / "package.json" + (tmp_path / "AGENTS.md").write_text("Review security carefully.\n", encoding="utf-8") + manifest.write_text('{"dependencies": {"example": "1.0.0"}}\n', encoding="utf-8") + _git(tmp_path, "add", ".") + _git(tmp_path, "commit", "-qm", "base") + base = _git(tmp_path, "rev-parse", "HEAD") + manifest.write_text('{"dependencies": {"example": "2.0.0"}}\n', encoding="utf-8") + _git(tmp_path, "commit", "-qam", "head") + head = _git(tmp_path, "rev-parse", "HEAD") + _git(tmp_path, "checkout", "-q", "--detach", base) + manifest.write_text('{"dependencies": {"example": "3.0.0"}}\n', encoding="utf-8") + _git(tmp_path, "commit", "-qam", "actual target") + target = _git(tmp_path, "rev-parse", "HEAD") + + list_objects = GitRepositoryReader.list_objects + scans = [] + + def count_tree(reader: GitRepositoryReader, ref: str) -> tuple[RepositoryObject, ...]: + scans.append(ref) + return list_objects(reader, ref) + + monkeypatch.setattr(GitRepositoryReader, "list_objects", count_tree) + store = collect_repository_evidence( + tmp_path, base_ref=base, head_ref=head, policy_ref=base, target_ref=target + ) + + assert scans == [base, head, target] + assert store.policy is not None + assert any(record.source_path == "AGENTS.md" for record in store.policy.records) + assert store.target is not None + assert store.target.commit_sha == target + assert any(record.kind == "dependency.declared" for record in store.target.records) + + def test_source_guidance_content_is_not_read(tmp_path: Path) -> None: """Never include source guidance in the bounded blob read queue.""" diff --git a/tests/test_gitlinks.py b/tests/test_gitlinks.py index ceb8c1ef..75094b6c 100644 --- a/tests/test_gitlinks.py +++ b/tests/test_gitlinks.py @@ -30,13 +30,20 @@ ) 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.ocr_result import ( + TOOLKIT_RESULT_KEY, + TOOLKIT_RESULT_SCHEMA_VERSION, + TOOLKIT_REVIEW_SELECTION_KEY, +) +from ocr_toolkit.posting.workflow import verified_review_coverage from ocr_toolkit.pre_execution import ( GITLINK_PROJECTION_UNQUALIFIED, GITLINK_STATUS_SCHEMA, read_pre_execution_status, ) from ocr_toolkit.preflight import RECOMMENDED_OCR_VERSION, SUPPORTED_OCR_VERSIONS +from ocr_toolkit.review_coverage import coverage_from_selection +from ocr_toolkit.review_receipt import ReceiptReviewIdentity OLD_OID = "1" * 40 NEW_OID = "2" * 40 @@ -141,6 +148,21 @@ def _ordinary_exclusion_fixture(root: Path) -> tuple[str, str]: return base, _git(root, "rev-parse", "HEAD") +def _include_runner_config(root: Path) -> Path: + directory = root.with_name(root.name + ".tmp") + directory.mkdir() + runner_config = directory / ".gitlab-runner.ext.conf" + runner_config.write_text( + '[credential "https://gitlab.example.invalid"]\n' + "\thelper = store\n" + '[url "https://job-token@example.invalid/"]\n' + "\tinsteadOf = https://gitlab.example.invalid/\n", + encoding="utf-8", + ) + _git(root, "config", "include.path", str(runner_config)) + return runner_config + + @pytest.mark.parametrize("kind", ["added", "updated", "deleted"]) def test_changed_gitlinks_use_immutable_tree_modes_with_ordinary_file( tmp_path: Path, kind: str @@ -907,8 +929,66 @@ def test_projection_rejects_local_git_config_include(tmp_path: Path) -> None: plan = plan_gitlink_input(reader, base, head) assert plan is not None _git(tmp_path, "config", "include.path", "/tmp/unused-config") + home = tmp_path / "private" + home.mkdir(mode=0o700) with pytest.raises(RepositoryEvidenceError, match="includes"): + make_gitlink_projection(reader, plan, ordinary_config_home=home) + assert not list(home.iterdir()) + + +def test_ordinary_gitlab_projection_isolates_runner_include(tmp_path: Path) -> None: + root = tmp_path / "repo" + root.mkdir() + base, head = _ordinary_exclusion_fixture(root) + _git(root, "config", "core.ignoreCase", "true") + reader = GitRepositoryReader(root, local_only=True) + plan = plan_review_input(reader, base, head) + original = make_gitlink_projection(reader, plan) + runner_config = _include_runner_config(root) + home = tmp_path / "private" + home.mkdir(mode=0o700) + directory = root / ".git" + config = (directory / "config").read_bytes() + index = (directory / "index").read_bytes() + + with pytest.raises(RepositoryEvidenceError, match="includes are unsupported"): make_gitlink_projection(reader, plan) + projection = make_gitlink_projection(reader, plan, ordinary_config_home=home) + + assert projection.original_diff == original.original_diff + assert projection.fingerprints == original.fingerprints + assert projection.line_counts == original.line_counts + env = projection.child_environment() + assert env["GIT_OBJECT_DIRECTORY"] == str(directory / "objects") + assert env["GIT_WORK_TREE"] == str(root) + sanitized = Path(env["GIT_DIR"]) / "config" + assert b"ignoreCase = true" in sanitized.read_bytes() + assert b"credential" not in sanitized.read_bytes() and b"include" not in sanitized.read_bytes() + assert b"job-token" not in sanitized.read_bytes() + assert (directory / "config").read_bytes() == config + assert (directory / "index").read_bytes() == index + + # Runner may remove the external include after checkout. The file is not + # a Git input to the isolated projection. + runner_config.unlink() + verify_gitlink_projection(reader, projection) + sanitized.write_text("[core]\n\tbare = false\n", encoding="utf-8") + with pytest.raises(RepositoryEvidenceError, match="isolated Git config changed"): + verify_gitlink_projection(reader, projection) + + +def test_ordinary_gitlab_projection_rejects_conditional_include(tmp_path: Path) -> None: + root = tmp_path / "repo" + root.mkdir() + base, head = _ordinary_exclusion_fixture(root) + reader = GitRepositoryReader(root, local_only=True) + plan = plan_review_input(reader, base, head) + home = tmp_path / "private" + home.mkdir(mode=0o700) + _git(root, "config", "includeIf.onbranch:*.path", "/unused/synthetic-config") + with pytest.raises(RepositoryEvidenceError, match="includes are unsupported"): + make_gitlink_projection(reader, plan, ordinary_config_home=home) + assert not list(home.iterdir()) def test_projection_rejects_bom_prefixed_local_git_config_include(tmp_path: Path) -> None: @@ -1339,6 +1419,7 @@ def test_installed_ocr_gitlink_preview_qualification( "excluded-rename", "move", "ordinary", + "ordinary-runner", "ordinary-quoted", "ordinary-non-utf8", ], @@ -1359,15 +1440,20 @@ def test_installed_ocr_projected_review_matches_native_manifest( "excluded-rename": _mixed_fixture, "move": _move_fixture, "ordinary": _ordinary_exclusion_fixture, + "ordinary-runner": _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_review_input(reader, base, head) - projection = make_gitlink_projection(reader, plan) home = tmp_path / "ocr-home" home.mkdir(mode=0o700) + if kind == "ordinary-runner": + _include_runner_config(repo) + reader = GitRepositoryReader(repo) + plan = plan_review_input(reader, base, head) + projection = make_gitlink_projection( + reader, plan, ordinary_config_home=home if kind == "ordinary-runner" else None + ) env = projection.child_environment() env["HOME"] = str(home) args = [ @@ -1397,7 +1483,8 @@ def test_installed_ocr_projected_review_matches_native_manifest( timeout=30, ) assert preview.returncode == 0 and preview.stderr == b"" - if kind == "ordinary" and version == "1.14.5": + has_gitignore = kind in {"ordinary", "ordinary-runner"} + if has_gitignore 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"] @@ -1410,7 +1497,7 @@ def test_installed_ocr_projected_review_matches_native_manifest( assert all(entry.status != "D" for entry in selected) if kind in {"added", "updated", "deleted"}: assert selected == projection.ordinary_diff - elif kind == "ordinary": + elif has_gitignore: assert [entry.path for entry in selected] == ["selected.py"] assert [(item.entry.path, item.reason) for item in selection.excluded] == [ ("hidden.py", "gitignore") @@ -1446,9 +1533,31 @@ def finish_review(_request): ) assert production.returncode == 0 and production.stderr == b"" payload = json.loads(production.stdout) - qualify_review_manifest( - projection, selection, payload, require_fresh_complete=kind != "ordinary" + uses_proof = qualify_review_manifest( + projection, selection, payload, require_fresh_complete=not has_gitignore ) + if kind == "ordinary-runner": + assert uses_proof + expected = coverage_from_selection(projection, selection) + payload[TOOLKIT_RESULT_KEY] = { + "review_coverage": expected.payload(), + "publication": {"state": "passed"}, + } + payload[TOOLKIT_REVIEW_SELECTION_KEY] = review_selection_proof(projection, selection) + identity = ReceiptReviewIdentity( + source_sha=head, + target_sha=base, + target_protection="protected", + mr_author_id=42, + schema_version=TOOLKIT_RESULT_SCHEMA_VERSION, + policy_sha=base, + diff_base_sha=base, + ) + monkeypatch.chdir(repo) + assert verified_review_coverage(payload, identity) == expected + del payload[TOOLKIT_REVIEW_SELECTION_KEY] + with pytest.raises(RepositoryEvidenceError, match="omitted"): + verified_review_coverage(payload, identity) if kind == "excluded-rename": (renamed,) = ( record diff --git a/tests/test_local_incremental.py b/tests/test_local_incremental.py index 99cf5166..4fc5d3f8 100644 --- a/tests/test_local_incremental.py +++ b/tests/test_local_incremental.py @@ -62,7 +62,7 @@ def _fixture(tmp_path, environment): return root, base, head, paths, changed -def _mixed_fixture(tmp_path, environment): +def _mixed_fixture(tmp_path, environment, *, bounded_tools=False): compat = load_script() paths = [f"file_{index:02}.{'md' if index % 2 else 'json'}" for index in range(23)] texts = { @@ -75,7 +75,14 @@ def _mixed_fixture(tmp_path, environment): } texts[paths[7]] += f"See [configuration]({paths[6]}).\n" texts[paths[9]] += f"The setting is `{Path(paths[6]).stem}_state`.\n" + if bounded_tools: + appendix = "\n## Appendix\n" + "x" * 2045 + "🧪beyond\n" + appendix += "Example marker\n" * 128 + "\n" * 400 + "End of appendix.\n" + texts[paths[1]] += appendix + texts[paths[3]] += appendix initial = {path: text.replace("ready", "waiting") for path, text in texts.items()} + if bounded_tools: + initial[paths[1]] = initial[paths[1]].replace("End of appendix.", "End of examples.") first, *others = paths root, base, _ = compat.execution._synthetic_repo( tmp_path, @@ -968,6 +975,21 @@ def test_native_incremental_reuses_21_markdown_and_json_files_after_unchanged_se ) +def test_native_incremental_reuses_bounded_markdown_results_and_rechecks_invalidated_groups( + tmp_path, monkeypatch, qualified_native_ocr, capsys +): + _native_incremental_case( + tmp_path, + monkeypatch, + qualified_native_ocr, + capsys, + "flag", + False, + mixed=True, + bounded_tools=True, + ) + + @pytest.mark.parametrize( ("tool", "arguments", "result"), ( @@ -1057,6 +1079,7 @@ def _native_incremental_case( mixed=False, diagnostics_only=False, advanced=False, + bounded_tools=False, ): qualifying_candidate = bool(os.environ.get("OCR_QUALIFY_CANDIDATE")) binary, _ = qualified_native_ocr( @@ -1077,7 +1100,9 @@ def _native_incremental_case( monkeypatch.setenv("GIT_NO_LAZY_FETCH", "1") if mixed: - root, base, first, paths, texts = _mixed_fixture(tmp_path, environment) + root, base, first, paths, texts = _mixed_fixture( + tmp_path, environment, bounded_tools=bounded_tools + ) rule = root / ".opencodereview" / "rule.json" rule.parent.mkdir(exist_ok=True) rule.write_text('{"include":["*.md"]}') @@ -1095,6 +1120,9 @@ def _native_incremental_case( confirmed_search: set[str] = set() search_text = "Release notes" if mixed else "missing_synthetic_symbol" operator_token = "roverJune" + unqualified_reasons = ( + "Unqualified groups by reason: search_pathspec 15, search_tool 1, unsupported_tool 1." + ) evidence_path = paths[10] advanced_calls = { paths[6]: ("file_find", {"query_name": paths[10]}), @@ -1106,6 +1134,40 @@ def _native_incremental_case( {"action": "list", "kind": "repository.file", "ref": "base", "page_size": 50}, ), } + bounded_read, bounded_search, changed_read, changed_search = ( + paths[3], + paths[5], + paths[11], + paths[13], + ) + bounded_calls = { + bounded_read: ( + ("file_read", {"file_path": bounded_read, "start_line": 4, "end_line": 540}), + ), + bounded_search: ( + ("code_search", {"search_text": "Example marker", "file_patterns": [bounded_read]}), + ( + "code_search", + { + "search_text": "Example (marker|sample)", + "use_perl_regexp": True, + "file_patterns": ["*.md", f":(exclude){paths[1]}"], + }, + ), + ), + changed_read: (("file_read", {"file_path": paths[1], "start_line": 4, "end_line": 540}),), + changed_search: ( + ( + "code_search", + { + "search_text": "Example state is (ready|active)", + "use_perl_regexp": True, + "file_patterns": [paths[1]], + }, + ), + ), + } + bounded_responses: dict[str, tuple[str, ...]] = {} diagram_on = False diagram_owner = paths[0] confirmed_diagram: set[str] = set() @@ -1118,6 +1180,10 @@ def _native_incremental_case( updated_anchors = { path: text.replace("ready", "active") for path, text in comment_anchors.items() } + if bounded_tools: + edited_texts[paths[1]] = edited_texts[paths[1]].replace( + "End of appendix.", "End of material." + ) else: edited_texts = { path: text.replace("return 2 +", "return 3 +") for path, text in texts.items() @@ -1221,10 +1287,15 @@ def tool_script(request): "ocr_toolkit_evidence", {"action": "get", "id": page["records"][0]["id"]}, ) + elif bounded_tools and path in bounded_calls and len(names) <= len(bounded_calls[path]): + name, arguments = bounded_calls[path][len(names) - 1] elif "code_comment" not in names: rendered = [ message.get("content", "") for message in messages if message.get("role") == "tool" ] + if bounded_tools and path in bounded_calls: + with lock: + bounded_responses[path] = tuple(rendered[1:]) if DIAGRAM_TOOL_NAME in names and any( '"received"' in response for response in rendered ): @@ -1292,6 +1363,7 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): ) seen.clear() switches = ["--incremental"] if incremental else [] + native_flags = [] if bounded_tools else ["--no-filter"] if analysis: switches += ["--analysis-max-tokens-budget", "2"] if analysis_input == "flag": @@ -1319,7 +1391,7 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): head, "--concurrency", "2", - "--no-filter", + *native_flags, ] ) captured = capsys.readouterr() @@ -1334,10 +1406,7 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): 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 unqualified_reasons in captured.err assert all( value not in captured.err for value in ( @@ -1372,10 +1441,7 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): == 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 - ) + assert unqualified_reasons in baseline_report private_state = baseline_path.read_text() assert all( value not in private_state + baseline_report @@ -1410,6 +1476,28 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): else: assert {item.tool for item in scope.replays} == {tool} assert len(scope.replays) == (2 if path == evidence_path else 1) + if bounded_tools: + assert cache.baseline_groups is not None + assert not cache.baseline_groups.reasons, (cache.baseline_groups, baseline_report) + assert compat.peer._StubHandler.request_stages.count("filter") == len(paths) + assert "approve_all_comments" not in baseline["tool_calls"]["by_tool"] + assert set(bounded_responses) == set(bounded_calls) + for path, target in ((bounded_read, bounded_read), (changed_read, paths[1])): + (output,) = bounded_responses[path] + assert "IS_TRUNCATED: true\nLINE_RANGE: 4-503" in output + assert "10 more bytes omitted" in output and "🧪" not in output + scope = cache.files[path].scope + assert scope is not None and scope.head_paths == (dependency_path(target),) + for output in bounded_responses[bounded_search]: + assert "Showing the first 100 matches across 1 matching files" in output + for path, replays in ((bounded_search, 2), (changed_search, 1)): + scope = cache.files[path].scope + assert scope is not None and len(scope.replays) == replays + prior_read, prior_search = ( + bounded_responses[changed_read], + bounded_responses[changed_search], + ) + bounded_responses.clear() old_run = baseline["manifest"]["run_id"] changed_now.update(paths[1:3] if diagram else paths[:2]) corrupted_path = paths[-1] @@ -1439,6 +1527,16 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): ) if diagram: expected_fresh.add(diagram_owner) + if bounded_tools: + expected_fresh.update({changed_read, changed_search}) + assert compat.peer._StubHandler.request_stages.count("filter") == ( + len(paths) + len(expected_fresh) + ) + assert set(bounded_responses) == {changed_read, changed_search}, narrowed[ + "toolkit_incremental" + ] + assert bounded_responses[changed_read] == prior_read + assert bounded_responses[changed_search] != prior_search if ( qualifying_candidate and narrowed["status"] == "complete" @@ -1479,6 +1577,9 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): if diagram: assert "```mermaid" not in markdown return + if bounded_tools: + assert {bounded_read, bounded_search} <= {item["path"] for item in carry["reused"]} + return if mixed: assert carry["reused_count"] == 21 groups = {cache.files[item["path"]].scope.members for item in carry["reused"]} diff --git a/tests/test_local_incremental_reads.py b/tests/test_local_incremental_reads.py new file mode 100644 index 00000000..952fa614 --- /dev/null +++ b/tests/test_local_incremental_reads.py @@ -0,0 +1,154 @@ +"""Verify exact native read observations against bounded immutable Git content.""" + +import json +from time import monotonic + +from ocr_toolkit.evidence.repository import GitRepositoryReader +from ocr_toolkit.evidence.text_contracts import MAX_SOURCE_BYTES +from ocr_toolkit.local_incremental_dependencies import ( + NativeDependencies, + _read_observation, + _verified_windows, +) +from ocr_toolkit.review_range import ReviewRange +from tests.test_ocr_compat import load_script + +_UTF8_NOTICE = ( + "\nNote: Lines longer than 2048 bytes were cut mid-line and the omitted bytes are not part " + "of this result. Reason about the visible part only.\n" +) + + +def test_truncated_read_requires_exact_visible_source_and_omission_count(): + review_range = ReviewRange("1" * 40, "2" * 40) + args = {"file_path": "example.txt"} + content = "x" * 2045 + source = (content + "🧪beyond\r\n").encode() + result = ( + "File: example.txt (Total lines: 2)\nIS_TRUNCATED: true\nLINE_RANGE: 1-2\n" + f"1|{content} …[line truncated, 10 more bytes omitted]\n2|\n{_UTF8_NOTICE}" + ) + valid = _read_observation(args, result, review_range, ok=True) + wrong_count = _read_observation( + args, result.replace("10 more", "11 more"), review_range, ok=True + ) + wrong_visible_source = _read_observation( + args, result.replace("1|x", "1|y"), review_range, ok=True + ) + wrong_range = _read_observation( + args, result.replace("LINE_RANGE: 1-2", "LINE_RANGE: 1-1"), review_range, ok=True + ) + assert valid.truncated and valid.revision == review_range.head + assert _verified_windows({valid, wrong_count, wrong_visible_source, wrong_range}, source) == { + valid + } + assert not _verified_windows({valid}, source.replace(b"beyond", b"beyon\0")) + assert not _verified_windows({valid}, source.replace(b"beyond", b"beyon\xff")) + + +def _read_body_at_size(total): + rows = ["a" * 2040] * 128 + current = sum(len(f"{number}|{line}\n") for number, line in enumerate(rows, 1)) + return "\n".join([*rows, "b" * (total - current - len("129|\n"))]) + + +def test_qualified_native_read_limits_match_immutable_git(tmp_path, qualified_native_ocr): + binary, _ = qualified_native_ocr( + "OCR_FEDERATION_QUALIFY_BINARY", handoff="local_review_incremental" + ) + compat = load_script() + home = tmp_path / "home" + environment = compat.execution._isolated_probe_environment(home) + tail = "x" * 2040 + "🧪beyond\r\n" + root, base, head = compat.execution._synthetic_repo( + tmp_path, + environment, + baseline="BASE " + tail, + changed="HEAD " + tail, + context_files={ + "lines.txt": "\n".join(f"line{number}" for number in range(1, 502)), + "exact.txt": _read_body_at_size(262_144), + "over.txt": _read_body_at_size(262_145), + "combined.txt": "a" * 10 + _read_body_at_size(262_145) + "\n" * 400, + }, + ) + cases = [ + ({"file_path": "lines.txt"}, "true", "1-500", "Results truncated to 500 lines."), + ( + {"file_path": "lines.txt", "start_line": 2, "end_line": 501}, + "false", + "2-501", + "501|line501\n", + ), + ( + {"file_path": "example.py", "start_line": 1, "end_line": 1, "side": "old"}, + "true", + "1-1", + "1|BASE ", + ), + ({"file_path": "example.py", "end_line": 1, "side": "new"}, "true", "1-1", "1|HEAD "), + ({"file_path": "exact.txt"}, "false", "1-129", "129|b"), + ({"file_path": "over.txt"}, "true", "1-128", "Output truncated at 262144 bytes."), + ({"file_path": "combined.txt"}, "true", "1-128", "Results truncated to 500 lines."), + ] + results = {} + + def tool_script(request): + for message in request["messages"]: + identity = message.get("tool_call_id", "") + if message["role"] == "tool" and identity.startswith("read-"): + results[int(identity.removeprefix("read-"))] = message["content"] + index = len(results) + if index < len(cases): + return {"name": "file_read", "arguments": json.dumps(cases[index][0])}, f"read-{index}" + return {"name": "task_done", "arguments": "{}"}, "done" + + with compat.peer._stub_gateway(tool_script=tool_script) as url: + environment.update( + OCR_LLM_URL=url, + OCR_LLM_TOKEN="synthetic-token", + OCR_LLM_MODEL="synthetic-model", + OCR_LLM_PROTOCOL="openai", + OCR_TELEMETRY_ENABLED="false", + ) + output = compat.execution._run( + [ + binary, + "review", + "--from", + base, + "--to", + head, + "--effort", + "low", + "--concurrency", + "1", + "--format", + "json", + "--audience", + "agent", + ], + cwd=root, + env=environment, + ) + assert json.loads(output)["tool_calls"]["by_tool"]["file_read"] == len(cases) + assert len(results) == len(cases) + review_range = ReviewRange(base, head) + observations = set() + for index, (args, truncated, expected_range, marker) in enumerate(cases): + result = results[index] + assert f"IS_TRUNCATED: {truncated}\nLINE_RANGE: {expected_range}\n" in result + assert marker in result + if args["file_path"] == "example.py": + assert "🧪" not in result and "10 more bytes omitted" in result + observations.add(_read_observation(args, result, review_range, ok=True)) + assert results[2].startswith(f"SIDE: old\nREVISION: {base}\n") + assert len(results[4].split("\n", 3)[-1].encode()) == 262_144 + assert results[6].index(_UTF8_NOTICE) < results[6].index("Output truncated at 262144 bytes.") + dependencies = NativeDependencies.inspect(home, root, review_range) + assert dependencies is not None + assert dependencies.groups["example.py"].reads == observations + reader = GitRepositoryReader( + root, max_file_bytes=MAX_SOURCE_BYTES, deadline=monotonic() + 10, local_only=True + ) + assert dependencies._verify_reads(reader, observations) == observations diff --git a/tests/test_local_incremental_replay.py b/tests/test_local_incremental_replay.py index ad61701a..50e2b392 100644 --- a/tests/test_local_incremental_replay.py +++ b/tests/test_local_incremental_replay.py @@ -2,11 +2,12 @@ import json from collections import Counter +from pathlib import Path import pytest from ocr_toolkit import local_incremental_replay -from ocr_toolkit.evidence import CoverageRecord, CoverageState, EvidenceStore, RefRole +from ocr_toolkit.evidence import CoverageRecord, CoverageState, EvidenceStore, RefRole, repository from ocr_toolkit.evidence.actions import ACTION_RECEIPT_BUCKETS, EVIDENCE_ACTIONS from ocr_toolkit.evidence.mcp import ( COVERAGE_TOOL_NAME, @@ -18,9 +19,11 @@ 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.local_incremental_state import IncrementalError, IncrementalSearchError, ToolReplay +from ocr_toolkit.result_contract import parse_result_outcome from ocr_toolkit.review_range import ReviewRange from tests.test_evidence_repository import git +from tests.test_ocr_compat import load_script @pytest.fixture(scope="module") @@ -104,27 +107,241 @@ def test_replay_reproduces_immutable_native_output_and_detects_changes( assert current.verifies(observed) is remains_valid -def test_excess_search_matches_do_not_confirm_a_partial_observation(tmp_path): +def _search_block(path, lines): + return ( + f"File: {path}\nMatch lines: {len(lines)}\n" + + "".join(f"{number}|{line}\n" for number, line in enumerate(lines, start=1)) + + "\n" + ) + + +def _search_note(files): + return ( + f"Note: Showing the first 100 matches across {files} matching files. " + "Some files are partially shown or omitted entirely. Narrow file_patterns to see the rest.\n" + ) + + +def test_capped_search_binds_visible_matches_and_omitted_file_count(tmp_path, monkeypatch): git(tmp_path, "init", "-q") - (tmp_path / "status.md").write_text("ordinary text\n") + first = tmp_path / "first.md" + middle = tmp_path / "middle.md" + last = tmp_path / "z-last.md" + first.write_text("searchable line\n" * 99) + middle.write_text("searchable middle\n") + git(tmp_path, "add", ".") + git(tmp_path, "commit", "-qm", "base") + base = git(tmp_path, "rev-parse", "HEAD") + last.write_text("searchable initially omitted\n") + git(tmp_path, "add", last.name) + git(tmp_path, "commit", "-qm", "first cap") + capped_head = git(tmp_path, "rev-parse", "HEAD") + arguments = {"search_text": "searchable"} + first_block = _search_block(first.name, ["searchable line"] * 99) + full_prefix = first_block + _search_block(middle.name, ["searchable middle"]) + capped = observed_replay("code_search", arguments, _search_note(3) + full_prefix) + uncapped = observed_replay("code_search", arguments, full_prefix) + reader = GitRepositoryReader(tmp_path) + + def verifier(head): + return ReplayVerifier(reader, ReviewRange(base, head), None, lambda _: True) + + assert verifier(capped_head).verifies(capped) + assert not verifier(capped_head).verifies(uncapped) + with monkeypatch.context() as global_limits: + global_limits.setattr(repository, "MAX_GIT_GREP_BYTES", 60) + limited = verifier(capped_head) + assert not limited.verifies(capped) + assert limited.failure_reason(capped) == "search_capped" + + old_arguments = {**arguments, "side": "old"} + assert verifier(capped_head).verifies( + observed_replay("code_search", old_arguments, f"SIDE: old\nREVISION: {base}\n{full_prefix}") + ) + + last.write_text("searchable changed but omitted\n" * 2) + git(tmp_path, "commit", "-qam", "edit invisible matches") + assert verifier(git(tmp_path, "rev-parse", "HEAD")).verifies(capped) + + last.write_text("no hits remain\n") + git(tmp_path, "commit", "-qam", "remove the cap") + current = verifier(git(tmp_path, "rev-parse", "HEAD")) + assert not current.verifies(capped) + assert current.failure_reason(capped) == "search_capped" + assert current.verifies(uncapped) + + (tmp_path / "z-extra.md").write_text("searchable extra\n") + last.write_text("searchable last\n") git(tmp_path, "add", ".") + git(tmp_path, "commit", "-qm", "add another matching file") + count_change = verifier(git(tmp_path, "rev-parse", "HEAD")) + assert not count_change.verifies(capped) + assert count_change.verifies( + observed_replay("code_search", arguments, _search_note(4) + full_prefix) + ) + + +def test_capped_search_rejects_unrepresentable_rows_even_after_the_prefix(tmp_path): + git(tmp_path, "init", "-q") + (tmp_path / "first.md").write_text("searchable line\n" * 100) + (tmp_path / "z:7:ambiguous.md").write_text("searchable ambiguous line\n") + git(tmp_path, "add", "first.md") 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") + git(tmp_path, "add", ".") + git(tmp_path, "commit", "-qm", "ambiguous matching path") 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" + witnessed = _search_note(2) + _search_block("first.md", ["searchable line"] * 100) + assert not verifier.verifies( + observed_replay("code_search", {"search_text": "searchable"}, witnessed) ) - 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_search_unsupported_regex_and_pathspec_keep_a_private_reason(review_revisions): + root, base, _, head = review_revisions + verifier = ReplayVerifier( + GitRepositoryReader(root), ReviewRange(base, head), None, lambda _: True + ) + invalid = observed_replay( + "code_search", {"search_text": "(", "use_perl_regexp": True}, "No matches found" + ) + assert not verifier.verifies(invalid) + assert verifier.failure_reason(invalid) == "search_regex" + with pytest.raises(IncrementalSearchError) as error: + observed_replay( + "code_search", + {"search_text": "example", "file_patterns": [":(attr:worktree)*"]}, + "No matches found", + ) + assert error.value.reason == "search_pathspec" + + +def test_search_pcre_match_limit_fails_closed(tmp_path): + git(tmp_path, "init", "-q") + source = tmp_path / "sample.md" + source.write_text("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!\n") + git(tmp_path, "add", source.name) + git(tmp_path, "commit", "-qm", "base") + base = git(tmp_path, "rev-parse", "HEAD") + git(tmp_path, "commit", "--allow-empty", "-qm", "head") + head = git(tmp_path, "rev-parse", "HEAD") + reader = GitRepositoryReader(tmp_path) + query = r"(*LIMIT_MATCH=1)(*NO_JIT)^(a+)+$" + failed = reader._run(["grep", "-P", "-e", query, head, "--", source.name]) + if "not compiled with USE_LIBPCRE" in failed.stderr: + pytest.skip("installed Git does not provide PCRE search") + assert failed.returncode == 128 and "match limit" in failed.stderr.casefold() + + verifier = ReplayVerifier(reader, ReviewRange(base, head), None, lambda _: True) + observed = observed_replay( + "code_search", + {"search_text": query, "use_perl_regexp": True, "file_patterns": [source.name]}, + "No matches found", + ) + assert not verifier.verifies(observed) + assert verifier.failure_reason(observed) == "search_regex" + + +def test_native_search_boundaries_match_saved_replay(tmp_path, qualified_native_ocr): + binary, version = qualified_native_ocr("OCR_FEDERATION_QUALIFY_BINARY") + compat = load_script() + if compat.core._version(version) < (1, 14, 6): + pytest.skip("search replay uses the OCR 1.14.6 boundary") + from ocr_qualification.comparison import ComparisonConversation, ToolCase + + git_env = compat.execution._isolated_probe_environment(tmp_path / "git-home") + review_env = compat.execution._isolated_probe_environment(tmp_path / "review-home") + lines = ["release-note7: Résumé\r"] + ["release-note7"] * 98 + contents = { + "docs/a.md": "".join(f"{line}\n" for line in lines), + "docs/b.md": "release-note8\n", + "docs/c.md": "release-note9\n", + "docs/excluded/manual.md": "release-note10\n", + } + root, base, head = compat.execution._synthetic_repo(tmp_path, git_env, context_files=contents) + (root / "docs/a.md").write_text("worktree only release-note11\n", encoding="utf-8") + (root / "docs/untracked.md").write_text("untracked release-note12\n", encoding="utf-8") + a_block = _search_block("docs/a.md", lines) + b_block = _search_block("docs/b.md", ["release-note8"]) + literal = {"search_text": "release-note"} + cases = ( + ({**literal, "file_patterns": ["docs/a.md"]}, a_block), + ({**literal, "file_patterns": ["docs/a.md", "docs/b.md"]}, a_block + b_block), + ( + { + "search_text": r"(?<=release-)note[0-9]+", + "use_perl_regexp": True, + "file_patterns": ["docs/", ":(exclude)docs/excluded/"], + }, + _search_note(3) + a_block + b_block, + ), + ( + { + "search_text": r"(?<=return )1$", + "use_perl_regexp": True, + "file_patterns": [":(exclude)docs/"], + "side": "old", + }, + f"SIDE: old\nREVISION: {base}\nFile: example.py\nMatch lines: 1\n2| return 1\n\n", + ), + ) + conversation = ComparisonConversation( + [ToolCase("code_search", arguments, ()) for arguments, _ in cases] + ) + witnessed = {} + + def script(request): + response = conversation(request) + for message in request["messages"]: + if message.get("role") == "tool": + witnessed[message["tool_call_id"]] = message["content"] + return response + + with compat.peer._stub_gateway(tool_script=script) as url: + review_env.update( + OCR_LLM_URL=url, + OCR_LLM_TOKEN="synthetic-token", + OCR_LLM_MODEL="synthetic-model", + OCR_LLM_PROTOCOL="openai", + OCR_TELEMETRY_ENABLED="false", + ) + output = compat.execution._run( + [ + str(Path(binary).resolve()), + "review", + "--from", + base, + "--to", + head, + "--effort", + "low", + "--concurrency", + "1", + "--no-filter", + "--format", + "json", + "--audience", + "agent", + ], + cwd=root, + env=review_env, + ) + + assert conversation.complete + result = parse_result_outcome(json.loads(output)) + assert result.kind == "clean" and result.completed_count == 1 + assert (root / "docs/a.md").read_text(encoding="utf-8") == "worktree only release-note11\n" + assert (root / "docs/untracked.md").read_text(encoding="utf-8") == "untracked release-note12\n" + verifier = ReplayVerifier( + GitRepositoryReader(root), ReviewRange(base, head), None, lambda _: True + ) + for index, (arguments, expected) in enumerate(cases): + actual = witnessed[f"comparison-{index}"] + assert actual == expected + assert verifier.verifies(observed_replay("code_search", arguments, actual)) def test_duplicate_diff_paths_are_counted_against_the_aggregate_budget( @@ -184,9 +401,13 @@ def test_replay_budget_counts_distinct_queries_and_keeps_verified_results(review ( ("tracker__echo", '{"text":"external"}'), ("future_native_tool", "{}"), - ("code_search", '{"search_text":"[a-z]","use_perl_regexp":true}'), + ("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","file_patterns":[":(exclude)../outside"]}'), + ("code_search", '{"search_text":"text","file_patterns":[":(exclude)/absolute"]}'), + ("code_search", '{"search_text":"text","file_patterns":[":(attr:worktree)*"]}'), + ("code_search", '{"search_text":"text","file_patterns":[":(exclude,attr:worktree)*"]}'), ("code_search", '{"search_text":"text","search_text":"other"}'), ("file_find", '{"query_name":"private word"}'), ("file_read_diff", '{"path_array":["notes/release.md","status.md"]}'), @@ -296,6 +517,11 @@ def test_incomplete_or_unbound_observation_cannot_create_replay(tool, arguments, ("changed_search", "search_tool"), ("unexecuted_call", "unsupported_tool"), ("unknown_call", "unsupported_tool"), + ("filter_keep_all", None), + ("filter_wrong_task", "unsupported_tool"), + ("filter_wrong_arguments", "invalid_arguments"), + ("filter_remove", "unsupported_tool"), + ("filter_dispatched", "unsupported_tool"), ("failed_tool", "failed_tool_call"), ("model_failure", "llm_error"), ("invalid_args", "invalid_arguments"), @@ -366,6 +592,31 @@ def tool_call(tool, args, result, *, ok=True): observe("llm_response", tool_calls=[{"name": "future_native_tool"}]) case "unknown_call": tool_call("future_native_tool", {}, "Native returned an observation") + case "filter_keep_all" | "filter_wrong_task" | "filter_wrong_arguments" | "filter_remove": + calls = [ + { + "id": "filter-approve", + "name": "approve_all_comments", + "arguments": "[]" if observation == "filter_wrong_arguments" else "{}", + } + ] + if observation == "filter_remove": + calls.append( + { + "id": "filter-remove", + "name": "report_incorrect_comments", + "arguments": '{"analysis":"Synthetic contradiction","comment_ids":["c-0"]}', + } + ) + observe( + "llm_response", + taskType="main_task" + if observation == "filter_wrong_task" + else "review_filter_task", + tool_calls=calls, + ) + case "filter_dispatched": + tool_call("approve_all_comments", {}, "Unexpected executable tool observation") case "failed_tool": tool_call("file_find", {"query_name": "readme"}, "Tool failed", ok=False) case "invalid_args":