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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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/13] 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