Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(ci): one GitHub Action, a GitLab template and one guide for the three CI gates (#2641)
Raghav Chamadiya386ccae78760
diff --git a/action.yml b/action.ymlnew file mode 100644index 000000000..24cbce266--- /dev/null+++ b/action.yml@@ -0,0 +1,106 @@+name: Repowise CI gates+description: >-+ Gate a pull request on patch coverage, documentation drift and new security+ findings. Needs git and nothing else: no index, no API key.+author: repowise-dev+branding:+ icon: check-circle+ color: blue++inputs:+ checks:+ description: >-+ Comma-separated gates to run: coverage, doc-drift, security. Coverage+ needs a report, so it is not on by default. Doc drift checks the whole+ tree; on a repository that already has drift, commit a baseline first.+ default: doc-drift,security+ version:+ description: Repowise version to install from PyPI. Empty installs the latest.+ default: ""+ python-version:+ description: Python used to install and run Repowise (3.11 or newer).+ default: "3.12"+ working-directory:+ description: Path inside the repository to run from.+ default: "."+ base:+ description: >-+ Revision range for coverage and security, e.g. origin/main...HEAD. Empty+ reads the pull request's target branch, else the default branch.+ default: ""+ coverage-report:+ description: >-+ Coverage report paths, one per line. Empty uses coverage.paths from+ .repowise/config.yaml, else discovery.+ default: ""+ coverage-fail-under:+ description: >-+ Minimum patch coverage percent. Empty uses coverage.fail_under from+ .repowise/config.yaml, else reports without gating.+ default: ""+ doc-drift-baseline:+ description: Committed doc-drift baseline file; only findings it does not list fail.+ default: ""+ security-fail-on:+ description: Lowest severity that fails the security gate (high, med or low).+ default: high+ security-baseline:+ description: Committed security baseline file; only findings it does not list fail.+ default: ""+ upload-sarif:+ description: >-+ "true" uploads doc-drift and security findings to GitHub code scanning.+ The workflow needs the security-events write permission.+ default: "false"++outputs:+ coverage:+ description: Exit code of the coverage gate (0 passed, 1 failed, 2 could not evaluate), empty when not run.+ value: ${{ steps.gates.outputs.coverage }}+ doc-drift:+ description: Exit code of the doc-drift gate, empty when not run.+ value: ${{ steps.gates.outputs.doc-drift }}+ security:+ description: Exit code of the security gate, empty when not run.+ value: ${{ steps.gates.outputs.security }}+ sarif-dir:+ description: Directory holding the SARIF files, when upload-sarif is on.+ value: ${{ steps.gates.outputs.sarif-dir }}++runs:+ using: composite+ steps:+ - uses: actions/setup-python@v5+ with:+ python-version: ${{ inputs.python-version }}++ - name: Install Repowise+ shell: bash+ env:+ REPOWISE_VERSION: ${{ inputs.version }}+ run: python -m pip install --quiet "repowise${REPOWISE_VERSION:+==$REPOWISE_VERSION}"++ - name: Run gates+ id: gates+ shell: bash+ working-directory: ${{ inputs.working-directory }}+ env:+ CHECKS: ${{ inputs.checks }}+ BASE: ${{ inputs.base }}+ COVERAGE_REPORT: ${{ inputs.coverage-report }}+ COVERAGE_FAIL_UNDER: ${{ inputs.coverage-fail-under }}+ DOC_DRIFT_BASELINE: ${{ inputs.doc-drift-baseline }}+ SECURITY_FAIL_ON: ${{ inputs.security-fail-on }}+ SECURITY_BASELINE: ${{ inputs.security-baseline }}+ SARIF: ${{ inputs.upload-sarif }}+ SARIF_DIR: ${{ runner.temp }}/repowise-sarif+ PYTHONUTF8: "1"+ run: bash "$GITHUB_ACTION_PATH/ci/github/run-gates.sh"++ - name: Upload SARIF+ if: always() && inputs.upload-sarif == 'true' && steps.gates.outputs.sarif-dir != ''+ # A fork's pull request has a read-only token; the gates decide the check.+ continue-on-error: true+ uses: github/codeql-action/upload-sarif@v3+ with:+ sarif_file: ${{ steps.gates.outputs.sarif-dir }}diff --git a/ci/github/run-gates.sh b/ci/github/run-gates.shnew file mode 100644index 000000000..4bc4cbe9d--- /dev/null+++ b/ci/github/run-gates.sh@@ -0,0 +1,95 @@+#!/usr/bin/env bash+# Runs the Repowise CI gates for the composite action in action.yml.+#+# Every selected gate runs even when an earlier one fails, so one job reports+# all of them. Exit codes follow the gates: 1 when any gate failed, 2 when any+# could not evaluate (and none failed), 0 otherwise. Inputs arrive as+# environment variables set by action.yml; nothing is interpolated into code.++set -u++# Commas, spaces and newlines all separate names, so a YAML block list works.+names=$(tr -s ', \t\r\n' ' ' <<<"$CHECKS")+checks=" $names "+wants() { [[ "$checks" == *" $1 "* ]]; }++if [[ -z "${names// /}" ]]; then+ echo "::error::No check selected; set checks to coverage, doc-drift or security."+ exit 2+fi+for name in $names; do+ case "$name" in+ coverage | doc-drift | security) ;;+ *) echo "::error::Unknown check '$name'; use coverage, doc-drift or security." ; exit 2 ;;+ esac+done++# Coverage and security diff the change, so they need its history and the+# target branch. A shallow clone has neither; fetch them rather than exit 2.+if wants coverage || wants security; then+ if [[ "$(git rev-parse --is-shallow-repository)" == "true" ]]; then+ git fetch --quiet --no-tags --unshallow origin || true+ fi+ if [[ -n "${GITHUB_BASE_REF:-}" ]] && ! git rev-parse --verify --quiet "refs/remotes/origin/$GITHUB_BASE_REF" >/dev/null; then+ git fetch --quiet --no-tags origin "+refs/heads/$GITHUB_BASE_REF:refs/remotes/origin/$GITHUB_BASE_REF" || true+ fi+fi++failed=0+broken=0++# run NAME COMMAND...: one gate in a log group, its exit code recorded.+run() {+ local name=$1+ shift+ echo "::group::repowise $name"+ "$@"+ local code=$?+ echo "::endgroup::"+ echo "$name=$code" >>"$GITHUB_OUTPUT"+ case "$code" in+ 0) ;;+ 1) failed=1 ;;+ *) broken=1 ;;+ esac+}++base=()+[[ -n "$BASE" ]] && base=("$BASE")++if wants coverage; then+ args=(coverage check ${base[@]+"${base[@]}"} --format github)+ while IFS= read -r report; do+ [[ -n "$report" ]] && args+=(--report "$report")+ done <<<"$COVERAGE_REPORT"+ [[ -n "$COVERAGE_FAIL_UNDER" ]] && args+=(--fail-under "$COVERAGE_FAIL_UNDER")+ run coverage repowise "${args[@]}"+fi++drift=(doc-drift --check)+[[ -n "$DOC_DRIFT_BASELINE" ]] && drift+=(--baseline "$DOC_DRIFT_BASELINE")+security=(security check ${base[@]+"${base[@]}"} --fail-on "$SECURITY_FAIL_ON")+[[ -n "$SECURITY_BASELINE" ]] && security+=(--baseline "$SECURITY_BASELINE")++wants doc-drift && run doc-drift repowise "${drift[@]}" --format github+wants security && run security repowise "${security[@]}" --format github++# SARIF is a second run in its own format. A gate that could not evaluate+# writes an empty file, which code scanning would reject, so it is dropped.+if [[ "$SARIF" == "true" ]] && { wants doc-drift || wants security; }; then+ mkdir -p "$SARIF_DIR"+ wants doc-drift && repowise "${drift[@]}" --format sarif >"$SARIF_DIR/doc-drift.sarif"+ wants security && repowise "${security[@]}" --format sarif >"$SARIF_DIR/security.sarif"+ find "$SARIF_DIR" -name '*.sarif' -empty -delete+ if [[ -n "$(ls -A "$SARIF_DIR")" ]]; then+ echo "sarif-dir=$SARIF_DIR" >>"$GITHUB_OUTPUT"+ fi+fi++if ((failed)); then+ exit 1+fi+if ((broken)); then+ exit 2+fi+exit 0diff --git a/ci/gitlab/repowise.gitlab-ci.yml b/ci/gitlab/repowise.gitlab-ci.ymlnew file mode 100644index 000000000..fcf1f8426--- /dev/null+++ b/ci/gitlab/repowise.gitlab-ci.yml@@ -0,0 +1,74 @@+# Repowise CI gates for GitLab merge requests.+#+# Include it from your .gitlab-ci.yml:+#+# include:+# - remote: https://raw.githubusercontent.com/repowise-dev/repowise/main/ci/gitlab/repowise.gitlab-ci.yml+#+# Each gate is its own job, so one failing does not hide the others. The+# markdown report is printed to the job log and kept as an artifact. Exit codes+# are the gates': 1 failed, 2 could not evaluate; both fail the job.+#+# Variables (set them in your .gitlab-ci.yml or the project's CI settings):+# REPOWISE_VERSION Version to install; empty installs the latest.+# REPOWISE_COVERAGE_REPORT Coverage report paths, space separated. The coverage+# job runs only when it is set; add `needs:` on your+# test job.+# REPOWISE_COVERAGE_FAIL_UNDER Minimum patch coverage percent.+# REPOWISE_DOC_DRIFT_BASELINE Committed doc-drift baseline file.+# REPOWISE_SECURITY_BASELINE Committed security baseline file.+# REPOWISE_SECURITY_FAIL_ON Lowest severity that fails: high (default), med, low.++.repowise:+ image: python:3.12+ variables:+ GIT_DEPTH: "0"+ before_script:+ - python -m pip install --quiet "repowise${REPOWISE_VERSION:+==$REPOWISE_VERSION}"+ # The gates diff against the target branch, which a merge request clone lacks.+ - git fetch --quiet --no-tags origin "+refs/heads/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME:refs/remotes/origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"+ rules:+ - if: $CI_PIPELINE_SOURCE == "merge_request_event"++repowise-coverage:+ extends: .repowise+ script:+ - >+ repowise coverage check "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME...HEAD"+ $(printf -- '--report %s ' $REPOWISE_COVERAGE_REPORT)+ ${REPOWISE_COVERAGE_FAIL_UNDER:+--fail-under "$REPOWISE_COVERAGE_FAIL_UNDER"}+ --format markdown > repowise-coverage.md+ after_script:+ - cat repowise-coverage.md+ artifacts:+ when: always+ paths: [repowise-coverage.md]+ rules:+ - if: $CI_PIPELINE_SOURCE == "merge_request_event" && $REPOWISE_COVERAGE_REPORT++repowise-doc-drift:+ extends: .repowise+ script:+ - >+ repowise doc-drift --check+ ${REPOWISE_DOC_DRIFT_BASELINE:+--baseline "$REPOWISE_DOC_DRIFT_BASELINE"}+ --format markdown > repowise-doc-drift.md+ after_script:+ - cat repowise-doc-drift.md+ artifacts:+ when: always+ paths: [repowise-doc-drift.md]++repowise-security:+ extends: .repowise+ script:+ - >+ repowise security check "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME...HEAD"+ --fail-on "${REPOWISE_SECURITY_FAIL_ON:-high}"+ ${REPOWISE_SECURITY_BASELINE:+--baseline "$REPOWISE_SECURITY_BASELINE"}+ --format markdown > repowise-security.md+ after_script:+ - cat repowise-security.md+ artifacts:+ when: always+ paths: [repowise-security.md]diff --git a/docs/README.md b/docs/README.mdindex d6070ff53..78bd4e382 100644--- a/docs/README.md+++ b/docs/README.md@@ -32,6 +32,7 @@ your agent in under five minutes, with no API key.| [start/QUICKSTART.md](start/QUICKSTART.md) | Install, index your repo, and connect your agent in under 5 minutes || [start/USER_GUIDE.md](start/USER_GUIDE.md) | The everyday guide: how the pieces fit and the workflows they support || [start/DASHBOARD.md](start/DASHBOARD.md) | Every view in the local web dashboard, and what each one answers |+| [start/CI.md](start/CI.md) | Gate pull requests on patch coverage, documentation drift and new security findings, with the GitHub Action and GitLab template |## Connect your AI agentdiff --git a/docs/layers/DOC_DRIFT.md b/docs/layers/DOC_DRIFT.mdindex 4fcbf77af..75b3312bb 100644--- a/docs/layers/DOC_DRIFT.md+++ b/docs/layers/DOC_DRIFT.md@@ -92,18 +92,16 @@ index, no model, a few seconds on a large repository. It exits `1` when afinding at or above `--fail-on-confidence` (default 0.7) is present, and `2`when it cannot evaluate.-```yaml-# .github/workflows/docs.yml-- uses: actions/checkout@v4- with:- fetch-depth: 0 # lets the rename suggestion read history-- run: pip install repowise-- run: repowise doc-drift --check --format github+```bash+repowise doc-drift --check --format github````--format github` annotates each finding on the document line and writes asummary to the job page. `--format sarif` produces a file for GitHub code-scanning; `--format markdown` is for posting a comment yourself.+scanning; `--format markdown` is for posting a comment yourself. Full history+(`fetch-depth: 0`) is optional and only improves the rename suggestions. The+GitHub Action and GitLab template that run it beside the other gates are in+[Repowise in CI](../start/CI.md).To adopt the gate on a repository that already has drift, record what is thereand fail only on new findings:diff --git a/docs/layers/SECURITY.md b/docs/layers/SECURITY.mdindex d6fa8c5cc..fc5b5a652 100644--- a/docs/layers/SECURITY.md+++ b/docs/layers/SECURITY.md@@ -276,43 +276,11 @@ baseline adds to its entries (and to those of `--baseline`, when given)instead of replacing them; remove an entry by deleting it from the file.`--format sarif` marks accepted findings as suppressed.-GitHub Actions, with the SARIF uploaded from your own workflow:--```yaml-on: pull_request-permissions:- contents: read- actions: read # upload-sarif needs it in a private repository- security-events: write-jobs:- security:- runs-on: ubuntu-latest- steps:- - uses: actions/checkout@v4- with:- fetch-depth: 0 # the gate reads every commit of the change- - run: pip install repowise- - run: repowise security check --format github --baseline .security-baseline.json- - if: always()- run: |- repowise security check --format sarif --baseline .security-baseline.json > security.sarif || true- [ -s security.sarif ] || rm security.sarif- - if: always() && hashFiles('security.sarif') != ''- uses: github/codeql-action/upload-sarif@v3- with:- sarif_file: security.sarif-```--A pull request from a fork runs with a read-only token, so the upload step-fails there; the gate step itself still runs and still fails the check. When-the gate cannot evaluate (exit 2) the SARIF file is empty, so it is removed-and the upload is skipped.--Without a REVSPEC the base comes from the CI's pull-request variables-(`GITHUB_BASE_REF`, GitLab's `CI_MERGE_REQUEST_TARGET_BRANCH_NAME`, Jenkins'-`CHANGE_TARGET`, Bitbucket's `BITBUCKET_PR_DESTINATION_BRANCH`), else the-remote's default branch. A shallow checkout cannot be read commit by commit,-so fetch the full history; the gate exits 2 rather than guess.+Without a REVSPEC the base comes from the CI's pull-request variables, else+the remote's default branch. A shallow checkout cannot be read commit by+commit, so fetch the full history; the gate exits 2 rather than guess. The+GitHub Action, the GitLab template and the SARIF upload are in+[Repowise in CI](../start/CI.md).## Line verificationdiff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.mdindex b26ce8293..d1f2cac81 100644--- a/docs/layers/TEST_INTELLIGENCE.md+++ b/docs/layers/TEST_INTELLIGENCE.md@@ -260,21 +260,10 @@ text report: export it with `coverage lcov` or `coverage xml` first.CI checkouts are often shallow, which leaves no merge-base to diff from. Fetchfull history (`fetch-depth: 0` on GitHub Actions, `GIT_DEPTH: 0` on GitLab).-Workflow snippets for GitHub Actions, GitLab and Jenkins are in the-[CLI reference](../reference/CLI_REFERENCE.md#repowise-coverage-check-revspec).--A new file no test loads must still appear in the report, or it reads "not in-report" and is not counted. Per language:--- **Python:** `pytest --cov=<src> --cov-report=lcov` (prefer lcov: its paths are- relative to the working directory).-- **JavaScript / TypeScript:** `c8 --all --reporter=lcov`, or jest with- `collectCoverageFrom` set.-- **Go:** `go test -coverprofile=coverage.out ./...`; add `-coverpkg=./...` to- include packages that have no tests.-- **Java:** Maven `jacoco:report` (`report-aggregate` for multi-module), or Gradle- `jacocoTestReport`.-- **Rust:** `cargo llvm-cov --lcov --output-path lcov.info`.+The GitHub Action, the GitLab template and the report command for each language+are in [Repowise in CI](../start/CI.md). A new file no test loads must still+appear in the report, or it reads "not in report" and is not counted; the+per-language commands there make sure it does.## Untested hotspotsdiff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex bdd06d82c..9995fee9e 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1344,7 +1344,7 @@ A coverage.py `.coverage` database is not a text report: export it first with`coverage lcov` or `coverage xml`. A new file no test loads must still appearin the report, or it is "not in report" and not counted; the per-languagecommands are in-[Patch coverage in CI](../layers/TEST_INTELLIGENCE.md#patch-coverage-in-ci).+[Coverage reports per language](../start/CI.md#coverage-reports-per-language).```bashrepowise coverage check origin/main...HEAD --report coverage/lcov.info --fail-under 80@@ -1353,49 +1353,8 @@ repowise coverage check origin/main...HEAD --report coverage.out --report-format```CI clones are often shallow, so the merge-base is missing and the check exits 2.-Fetch full history.--GitHub Actions (`pull_request` only: `github.base_ref` is empty on `push`, where-`"${{ github.event.before }}..${{ github.sha }}"` is the range instead):--```yaml-- uses: actions/checkout@v4- with:- fetch-depth: 0-- run: pytest --cov=src --cov-report=lcov:coverage/lcov.info-- run: pip install repowise-- run: >- repowise coverage check "origin/${{ github.base_ref }}...HEAD"- --report coverage/lcov.info --fail-under 80 --format github-```--A cheaper checkout: `fetch-depth: 2` and `HEAD^1..HEAD`, which on a-`pull_request` run diffs the merge commit GitHub builds against the base.--GitLab merge request (`markdown` goes to the job log; redirect it to a file to-post it as a note or keep it as an artifact):--```yaml-coverage-gate:- variables:- GIT_DEPTH: 0- script:- - git fetch --no-tags origin "$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"- - pytest --cov=src --cov-report=lcov:coverage/lcov.info- - pip install repowise- - >- repowise coverage check "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME...HEAD"- --report coverage/lcov.info --fail-under 80 --format markdown- rules:- - if: $CI_PIPELINE_SOURCE == "merge_request_event"-```--Jenkins multibranch pull request:--```bash-git fetch --no-tags origin "+refs/heads/$CHANGE_TARGET:refs/remotes/origin/$CHANGE_TARGET"-repowise coverage check "origin/$CHANGE_TARGET...HEAD" --report coverage/lcov.info --fail-under 80-```+Fetch full history. The GitHub Action, the GitLab template and recipes for+other CI systems are in [Repowise in CI](../start/CI.md).---diff --git a/docs/start/CI.md b/docs/start/CI.mdnew file mode 100644index 000000000..1f837387b--- /dev/null+++ b/docs/start/CI.md@@ -0,0 +1,216 @@+# Repowise in CI++Three gates judge a pull request, each on what the change adds rather than on+the whole repository's past:++| Gate | Question | Needs | History |+|------|----------|-------|---------|+| `repowise coverage check` | Did the tests run the lines this change touched? | git and a coverage report | the merge-base with the target branch |+| `repowise doc-drift --check` | Does the documentation still describe files, links and commands that exist? | git | none (full history only improves rename suggestions) |+| `repowise security check` | Did this change add a secret or a risky call? | git | every commit of the change |++None of them needs an index, a database, a model or an API key, and none+stores anything. They share one set of exit codes, output formats and base+resolution, described once below. Each layer's own page has the detail:+[test intelligence](../layers/TEST_INTELLIGENCE.md#patch-coverage-in-ci),+[documentation drift](../layers/DOC_DRIFT.md#in-ci),+[security](../layers/SECURITY.md#in-ci-repowise-security-check).++## What every gate does the same way++**Exit codes.** `0` passed, or had nothing to judge. `1` the change failed the+gate. `2` the gate could not evaluate: not a git repository, an unknown+revision, no merge-base in a shallow clone, an unreadable report or baseline.+A setup problem never reads as a pass.++**Formats.** `--format table` (the default) for a terminal, `json` for a+script, `markdown` for a comment or a job artifact, and `github` for GitHub+Actions: up to ten annotations on the changed lines, a notice counting the+rest, and the markdown report appended to the job summary. Doc drift and+security also write `sarif` for code scanning.++**The change being judged.** Coverage and security take a revision range:+`origin/main...HEAD` (three dots: what the branch did since it forked, the+pull request's view), `base..head`, or one commit. Without one they read the+target branch from the CI's own variables (`GITHUB_BASE_REF`,+`CI_MERGE_REQUEST_TARGET_BRANCH_NAME`, `CHANGE_TARGET`,+`BITBUCKET_PR_DESTINATION_BRANCH`), else the remote's default branch. Doc+drift has no range: it checks the whole working tree, and a baseline limits+it to new findings.++**History.** CI checkouts are usually shallow, which leaves no merge-base.+Fetch full history (`fetch-depth: 0` on GitHub Actions, `GIT_DEPTH: 0` on+GitLab) and make sure the target branch exists as `origin/<branch>`. The+gates exit `2` rather than guess.++## Adopting the gates on an existing repository++Coverage and security judge only what a change adds, so an old untested file+or an old finding never fails a new pull request. Doc drift checks the whole+tree, so on a repository whose documentation has already drifted it fails from+the first run. Record what is there once and fail only on new drift:++```bash+repowise doc-drift --check --write-baseline .doc-drift-baseline.json+git add .doc-drift-baseline.json+```++Then pass `--baseline .doc-drift-baseline.json` (or the action's+`doc-drift-baseline` input). Entries are keyed on the document, the reference+and its target, so an edit above a finding does not turn it back into a new+one.++Security has a baseline too, for accepting a finding a change adds on purpose+(a documented test key, say): `repowise security check --write-baseline+.security-baseline.json` on that change records it, and `--baseline` accepts it+from then on.++## GitHub Actions++The repository is itself an action. It installs Repowise, runs the gates you+pick, keeps going when one fails so the job reports all of them, and fails the+step at the end:++```yaml+on: pull_request+permissions:+ contents: read+jobs:+ repowise:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ with:+ fetch-depth: 0+ - run: pytest --cov=src --cov-report=lcov:coverage/lcov.info+ - uses: repowise-dev/repowise@main # pin a release tag in production+ with:+ checks: coverage,doc-drift,security+ coverage-report: coverage/lcov.info+ coverage-fail-under: 80+```++Pin a release tag rather than `main`, and set `version:` to pin the Repowise+release the action installs.++| Input | Default | Meaning |+|-------|---------|---------|+| `checks` | `doc-drift,security` | Gates to run. Coverage needs a report, so it is opt-in. |+| `version` | latest | Repowise version to install. |+| `python-version` | `3.12` | Python to run it with (3.11 or newer). |+| `working-directory` | `.` | Where to run from. |+| `base` | from the pull request | Revision range for coverage and security. |+| `coverage-report` | config, else discovery | Report paths, one per line. |+| `coverage-fail-under` | `coverage.fail_under` | Minimum patch coverage percent. |+| `doc-drift-baseline` | none | Committed baseline file. |+| `security-fail-on` | `high` | Lowest severity that fails: `high`, `med`, `low`. |+| `security-baseline` | none | Committed baseline file. |+| `upload-sarif` | `false` | Upload doc drift and security findings to code scanning. |++Outputs: `coverage`, `doc-drift` and `security` hold each gate's exit code+(empty when not run), and `sarif-dir` the SARIF directory.++A shallow checkout still works when coverage or security runs: the action+fetches the missing history and the target branch first. Checking out with+`fetch-depth: 0` skips that step.++**Code scanning.** With `upload-sarif: true` the findings appear in the+repository's Security tab and on the pull request's diff. The job then needs+`security-events: write` (and `actions: read` in a private repository). A pull+request from a fork runs with a read-only token, so the upload is skipped+there with a warning; the gates still run and still decide the check.++**Without the action,** each gate is one step:++```yaml+- run: pip install repowise+- run: repowise coverage check --report coverage/lcov.info --fail-under 80 --format github+- run: repowise doc-drift --check --format github+- run: repowise security check --format github+```++On a pull request the gates read the target branch from `GITHUB_BASE_REF`+themselves. On a `push` event there is none; pass the range explicitly, for+example `"$BEFORE..$GITHUB_SHA"` with `BEFORE: ${{ github.event.before }}` set+under `env:`.++## GitLab++Include the template and set variables for what you use:++```yaml+include:+ - remote: https://raw.githubusercontent.com/repowise-dev/repowise/main/ci/gitlab/repowise.gitlab-ci.yml++variables:+ REPOWISE_COVERAGE_REPORT: coverage/lcov.info+ REPOWISE_COVERAGE_FAIL_UNDER: "80"++repowise-coverage:+ needs: [test] # the job that writes the report as an artifact+```++It adds one job per gate on merge request pipelines: `repowise-coverage` (only+when `REPOWISE_COVERAGE_REPORT` is set), `repowise-doc-drift` and+`repowise-security`. Each prints its markdown report to the log and keeps it as+an artifact. Other variables: `REPOWISE_VERSION`, `REPOWISE_DOC_DRIFT_BASELINE`,+`REPOWISE_SECURITY_BASELINE`, `REPOWISE_SECURITY_FAIL_ON`. Override any job's+`image`, `rules` or `needs` in your own file as usual.++## Other CI systems++The gates are plain commands. Fetch the target branch, run them, and let the+exit code fail the build. Jenkins multibranch:++```bash+git fetch --no-tags origin "+refs/heads/$CHANGE_TARGET:refs/remotes/origin/$CHANGE_TARGET"+pip install repowise+repowise coverage check "origin/$CHANGE_TARGET...HEAD" --report coverage/lcov.info --fail-under 80+repowise doc-drift --check+repowise security check "origin/$CHANGE_TARGET...HEAD"+```++Bitbucket Pipelines and others work the same way with their own branch+variable; `--format markdown` or `json` gives you something to post.++## Coverage reports per language++The coverage gate needs the lines each file could have run, not only the lines+it did, and a new file no test loads must still appear in the report or it is+listed as "not in report" and left out of the figure. These commands do both:++| Stack | Produce the report | Pass |+|-------|--------------------|------|+| Python (pytest) | `pytest --cov=src --cov-report=lcov:coverage/lcov.info` (lcov paths are relative to the working directory) | `coverage/lcov.info` |+| Python (coverage.py) | `coverage lcov` or `coverage xml` after the run | `coverage.lcov`, `coverage.xml` |+| Go | `go test -coverprofile=coverage.out -coverpkg=./... ./...` (`-coverpkg` includes packages with no tests) | `coverage.out` |+| Java or Kotlin (Gradle) | `gradle test jacocoTestReport` with the XML report on | `build/reports/jacoco/test/jacocoTestReport.xml` |+| Java (Maven) | `mvn test jacoco:report` (`report-aggregate` for a multi-module build) | `target/site/jacoco/jacoco.xml` |+| JavaScript or TypeScript | `c8 --all --reporter=lcov`, or a test runner's `lcov` reporter with every source file included | `coverage/lcov.info` |+| Rust | `cargo llvm-cov --lcov --output-path coverage/lcov.info` | `coverage/lcov.info` |++Several reports merge: a line any of them ran counts as run. A coverage.py+`.coverage` database is not a text report; export it first. When report paths+do not line up with the repository (a build directory, a container path), set+`coverage.strip_prefix` or `coverage.path_prefix` in `.repowise/config.yaml`.+The gate reports how many report paths matched the repository, and exits `2`+when none did, so a wrong prefix never passes as zero.++The threshold can live in config instead of the workflow:++```yaml+# .repowise/config.yaml+coverage:+ paths: [coverage/lcov.info]+ fail_under: 80+```++## When a gate exits 2++| Message | Fix |+|---------|-----|+| no merge-base, or a commit cut off by a shallow clone | fetch full history |+| unknown revision `origin/<branch>` | fetch the target branch |+| no coverage report found | pass `--report`, or set `coverage.paths` |+| report paths match no file in the repository | set `coverage.strip_prefix` or `coverage.path_prefix` |+| baseline unreadable | commit the file, or drop `--baseline` |diff --git a/packages/ui/__tests__/shared/ci-hint.test.tsx b/packages/ui/__tests__/shared/ci-hint.test.tsxnew file mode 100644index 000000000..c0d6b2420--- /dev/null+++ b/packages/ui/__tests__/shared/ci-hint.test.tsx@@ -0,0 +1,17 @@+import { describe, it, expect } from "vitest";+import { render, screen } from "@testing-library/react";+import { CiHint, CI_GUIDE_URL } from "../../src/shared/ci-hint.js";+import { SecurityFindingsTable } from "../../src/security/findings-table.js";++describe("CiHint", () => {+ it("names the gate and links the CI guide", () => {+ render(<CiHint command="repowise doc-drift --check" checks="the documentation" />);+ expect(screen.getByText("repowise doc-drift --check")).toBeInTheDocument();+ expect(screen.getByRole("link", { name: "Set it up" })).toHaveAttribute("href", CI_GUIDE_URL);+ });++ it("is offered when a repository has no security findings", () => {+ render(<SecurityFindingsTable findings={[]} />);+ expect(screen.getByText("repowise security check")).toBeInTheDocument();+ });+});diff --git a/packages/ui/src/doc-drift/doc-drift-view.tsx b/packages/ui/src/doc-drift/doc-drift-view.tsxindex 538c0a599..a1c2382e9 100644--- a/packages/ui/src/doc-drift/doc-drift-view.tsx+++ b/packages/ui/src/doc-drift/doc-drift-view.tsx@@ -36,6 +36,7 @@ import {import { Skeleton } from "../ui/skeleton";import { ApiError } from "../shared/api-error";import { EmptyState } from "../shared/empty-state";+import { CiHint } from "../shared/ci-hint";import { OverviewSection } from "../overview/section";import { toFriendlyMessage } from "../lib/errors";@@ -174,11 +175,14 @@ export function DocDriftView({/>{summary.findings_total === 0 && !filtered ? (- <EmptyState- icon={<FileCheck2 className="h-6 w-6" />}- title="No documentation drift found"- description="Every reference this detector could resolve still resolves. It re-checks on each update, so this is worth a second look after a rename or a move."- />+ <div className="flex flex-col items-center gap-2">+ <EmptyState+ icon={<FileCheck2 className="h-6 w-6" />}+ title="No documentation drift found"+ description="Every reference this detector could resolve still resolves. It re-checks on each update, so this is worth a second look after a rename or a move."+ />+ <CiHint command="repowise doc-drift --check" checks="that every reference in the docs still resolves" />+ </div>) : (<OverviewSectiontitle="Drifted assertions"diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsxindex 27bbb0ae6..7013f279c 100644--- a/packages/ui/src/health/coverage-view.tsx+++ b/packages/ui/src/health/coverage-view.tsx@@ -52,6 +52,7 @@ import {} from "./ai-prompt-builder";import { scoreBadgeClass } from "./tokens";import { COVERAGE_REPORT_FORMATS_LABEL } from "./coverage-formats";+import { CiHint } from "../shared/ci-hint";import type { CodeHealthAdapter } from "./code-health-adapter";export function CoverageView({ adapter }: { adapter: CodeHealthAdapter }) {@@ -633,6 +634,7 @@ function NoCoverageState() {<p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">{COVERAGE_REPORT_FORMATS_LABEL}</p>+ <CiHint command="repowise coverage check" checks="the lines each change touched" /></div>);}diff --git a/packages/ui/src/health/inferred-tests-view.tsx b/packages/ui/src/health/inferred-tests-view.tsxindex 62d0e9765..facc0e56a 100644--- a/packages/ui/src/health/inferred-tests-view.tsx+++ b/packages/ui/src/health/inferred-tests-view.tsx@@ -45,6 +45,7 @@ import { formatNumber } from "../lib/format";import { RiskCoverageScatter } from "./risk-coverage-scatter";import { scoreBadgeClass } from "./tokens";import { COVERAGE_REPORT_FORMATS_LABEL } from "./coverage-formats";+import { CiHint } from "../shared/ci-hint";/** Below this, a file nothing reaches is worth leading with. */const AT_RISK_SCORE = 6;@@ -260,6 +261,7 @@ function AddResolutionSection() {<p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">{COVERAGE_REPORT_FORMATS_LABEL}</p>+ <CiHint command="repowise coverage check" checks="the lines each change touched" /></div></OverviewSection>);diff --git a/packages/ui/src/security/findings-table.tsx b/packages/ui/src/security/findings-table.tsxindex 867bb256f..17147121c 100644--- a/packages/ui/src/security/findings-table.tsx+++ b/packages/ui/src/security/findings-table.tsx@@ -5,6 +5,7 @@ import { Search } from "lucide-react";import { Badge } from "../ui/badge";import { Input } from "../ui/input";import { EmptyState } from "../shared/empty-state";+import { CiHint } from "../shared/ci-hint";import { ResponsiveTable, type ResponsiveColumn } from "../shared/responsive-table";import { AiPromptButton } from "../health/ai-prompt-button";import { formatDate, formatDateTime, formatRelativeTimeOrNull } from "../lib/format";@@ -186,10 +187,13 @@ export function SecurityFindingsTable({ findings, onSelect, onGeneratePrompt }:if (findings.length === 0) {return (- <EmptyState- title="No findings"- description="No security findings detected on this repo. Re-run analysis to refresh."- />+ <div className="flex flex-col items-center gap-2">+ <EmptyState+ title="No findings"+ description="No security findings detected on this repo. Re-run analysis to refresh."+ />+ <CiHint command="repowise security check" checks="what each change adds" />+ </div>);}diff --git a/packages/ui/src/shared/ci-hint.tsx b/packages/ui/src/shared/ci-hint.tsxnew file mode 100644index 000000000..654098227--- /dev/null+++ b/packages/ui/src/shared/ci-hint.tsx@@ -0,0 +1,31 @@+/**+ * One line pointing an empty or quiet view at the CI gate that keeps it+ * current. Coverage, documentation drift and security each have a gate that+ * judges every pull request, and the guide covers all three.+ */++export const CI_GUIDE_URL = "https://github.com/repowise-dev/repowise/blob/main/docs/start/CI.md";++export interface CiHintProps {+ /** The gate command, e.g. `repowise coverage check`. */+ command: string;+ /** What the gate judges on each pull request, completing "checks ...". */+ checks: string;+}++export function CiHint({ command, checks }: CiHintProps) {+ return (+ <p className="text-xs leading-relaxed text-[var(--color-text-tertiary)] [text-wrap:pretty]">+ In CI, <code className="font-mono text-[var(--color-text-secondary)]">{command}</code>{" "}+ checks {checks} on every pull request.{" "}+ <a+ href={CI_GUIDE_URL}+ target="_blank"+ rel="noreferrer"+ className="underline underline-offset-2 hover:text-[var(--color-text-primary)]"+ >+ Set it up+ </a>+ </p>+ );+}diff --git a/packages/ui/src/shared/index.ts b/packages/ui/src/shared/index.tsindex 8b2674d2f..4055b3fcc 100644--- a/packages/ui/src/shared/index.ts+++ b/packages/ui/src/shared/index.ts@@ -25,6 +25,7 @@ export {export { Toaster, toast, type ToasterProps } from "./toast";export * from "./breadcrumb";export * from "./empty-state";+export * from "./ci-hint";export {DismissibleNotice,type DismissibleNoticeProps,diff --git a/tests/unit/test_ci_action.py b/tests/unit/test_ci_action.pynew file mode 100644index 000000000..2ce93a1ea--- /dev/null+++ b/tests/unit/test_ci_action.py@@ -0,0 +1,169 @@+"""The GitHub Action, its runner script and the CI guide stay in step.++``action.yml`` passes inputs to ``ci/github/run-gates.sh`` as environment+variables and the guide documents every input, so a renamed input that one of+the three misses would fail silently in a user's workflow. The runner is also+run here against a stand-in ``repowise`` to pin its exit-code rules.+"""++from __future__ import annotations++import os+import re+import shutil+import stat+import subprocess+from pathlib import Path++import pytest+import yaml++ROOT = Path(__file__).resolve().parents[2]+ACTION = ROOT / "action.yml"+RUNNER = ROOT / "ci" / "github" / "run-gates.sh"+GUIDE = ROOT / "docs" / "start" / "CI.md"+GITLAB = ROOT / "ci" / "gitlab" / "repowise.gitlab-ci.yml"+++def _action() -> dict:+ return yaml.safe_load(ACTION.read_text(encoding="utf-8"))+++def test_every_input_is_documented_in_the_guide() -> None:+ guide = GUIDE.read_text(encoding="utf-8")+ missing = [name for name in _action()["inputs"] if f"| `{name}` |" not in guide]+ assert not missing+++def test_every_variable_the_runner_reads_is_passed_by_the_action() -> None:+ step = next(s for s in _action()["runs"]["steps"] if s.get("id") == "gates")+ passed = set(step["env"])+ script = RUNNER.read_text(encoding="utf-8")+ read = set(re.findall(r"\$\{?([A-Z][A-Z_]+)", script))+ runner_env = {"GITHUB_OUTPUT", "GITHUB_BASE_REF"}+ for_python = {"PYTHONUTF8"}+ assert read - runner_env <= passed+ assert passed - for_python <= read+++def test_the_gitlab_template_parses() -> None:+ jobs = yaml.safe_load(GITLAB.read_text(encoding="utf-8"))+ assert {"repowise-coverage", "repowise-doc-drift", "repowise-security"} <= set(jobs)+++def fake_repowise(tmp_path: Path) -> Path:+ """A ``repowise`` that logs its arguments and exits with ``$FAKE_<GATE>``."""+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir()+ fake = bin_dir / "repowise"+ fake.write_text(+ "#!/usr/bin/env bash\n"+ 'echo "$*" >> "$FAKE_LOG"\n'+ 'case "$1" in\n'+ ' coverage) exit "${FAKE_COVERAGE:-0}" ;;\n'+ ' doc-drift) exit "${FAKE_DOC_DRIFT:-0}" ;;\n'+ ' security) exit "${FAKE_SECURITY:-0}" ;;\n'+ "esac\n",+ encoding="utf-8",+ newline="\n",+ )+ fake.chmod(fake.stat().st_mode | stat.S_IEXEC)+ return bin_dir+++def _bash() -> str | None:+ """A real bash; on Windows the System32 one is the WSL launcher, which cannot run this."""+ git_bash = Path(os.environ.get("PROGRAMFILES", r"C:\Program Files"), "Git", "bin", "bash.exe")+ if os.name == "nt" and git_bash.exists():+ return str(git_bash)+ found = shutil.which("bash")+ if found and "system32" in found.lower():+ return None+ return found+++def _run(tmp_path: Path, bin_dir: Path, **env: str) -> tuple[int, str, str]:+ bash = _bash()+ if bash is None:+ pytest.skip("bash is not available")+ repo = tmp_path / "repo"+ repo.mkdir(exist_ok=True)+ subprocess.run(["git", "init", "-q"], cwd=repo, check=True)+ out = tmp_path / "out"+ log = tmp_path / "log"+ full = {+ **os.environ,+ "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}",+ "GITHUB_OUTPUT": str(out),+ "GITHUB_BASE_REF": "",+ "FAKE_LOG": str(log),+ "CHECKS": "coverage,doc-drift,security",+ "BASE": "",+ "COVERAGE_REPORT": "",+ "COVERAGE_FAIL_UNDER": "",+ "DOC_DRIFT_BASELINE": "",+ "SECURITY_FAIL_ON": "high",+ "SECURITY_BASELINE": "",+ "SARIF": "false",+ "SARIF_DIR": str(tmp_path / "sarif"),+ **env,+ }+ proc = subprocess.run([bash, str(RUNNER)], cwd=repo, env=full, capture_output=True, text=True)+ return (+ proc.returncode,+ out.read_text(encoding="utf-8") if out.exists() else "",+ log.read_text(encoding="utf-8") if log.exists() else "",+ )+++def test_every_gate_runs_and_a_failure_outranks_a_setup_error(tmp_path, fake_repowise) -> None:+ code, outputs, calls = _run(tmp_path, fake_repowise, FAKE_COVERAGE="2", FAKE_SECURITY="1")+ assert code == 1+ assert outputs.split() == ["coverage=2", "doc-drift=0", "security=1"]+ assert len(calls.splitlines()) == 3+++def test_a_setup_error_alone_exits_two(tmp_path, fake_repowise) -> None:+ code, _, _ = _run(tmp_path, fake_repowise, CHECKS="doc-drift", FAKE_DOC_DRIFT="2")+ assert code == 2+++def test_inputs_reach_the_commands(tmp_path, fake_repowise) -> None:+ code, _, calls = _run(+ tmp_path,+ fake_repowise,+ CHECKS="coverage, security",+ BASE="origin/main...HEAD",+ COVERAGE_REPORT="a.info\nb.xml",+ COVERAGE_FAIL_UNDER="80",+ SECURITY_BASELINE=".security-baseline.json",+ )+ assert code == 0+ coverage, security = calls.splitlines()+ assert coverage == (+ "coverage check origin/main...HEAD --format github "+ "--report a.info --report b.xml --fail-under 80"+ )+ assert security == (+ "security check origin/main...HEAD --fail-on high "+ "--baseline .security-baseline.json --format github"+ )+++def test_an_unknown_check_is_refused(tmp_path, fake_repowise) -> None:+ code, _, calls = _run(tmp_path, fake_repowise, CHECKS="coverage,lint")+ assert code == 2+ assert calls == ""+++def test_a_yaml_block_list_of_checks_runs_each_gate(tmp_path, fake_repowise) -> None:+ code, outputs, _ = _run(tmp_path, fake_repowise, CHECKS="doc-drift\nsecurity\n")+ assert code == 0+ assert outputs.split() == ["doc-drift=0", "security=0"]+++def test_no_check_selected_is_refused(tmp_path, fake_repowise) -> None:+ code, _, calls = _run(tmp_path, fake_repowise, CHECKS=" ")+ assert code == 2+ assert calls == ""