Developers
Read pull requests, filter tagged code, post review comments, and trigger GitHub syncs from scripts, your terminal, AI assistants, or your own code. The command-line tool, MCP server, and SDKs all call the same versioned REST API, so one API key works with all of them.
Organization owners and admins create keys on the Team page. The full key, which starts with gtap_, is shown only once, so store it in a secret manager or environment variable.
Each key has one or more scopes:
read to list pull requests, diffs, chunks, comments, guidance, and evidence.comments:write to post review comments.sync:write to trigger a GitHub sync.audit:read to read the audit trail.evidence:read to list evidence variables and read their history (a secret's value is never returned).evidence:write to create, change, rotate, and delete evidence variables; it includes evidence:read. Only these two scopes reach /evidence/env-vars.A key belongs to the person who created it. Removing that person from the GitHub organization revokes their keys.
To post a comment, also send a GitHub token for the same person in the X-GitHub-Token header. GitHub shows that account as the comment author. GitApprove rejects bot tokens and tokens that belong to anyone else.
The examples below read the key from an environment variable:
export GITAPPROVE_API_KEY="gtap_..."
export GITAPPROVE_GITHUB_TOKEN="ghp_..." # only needed to post commentsSend the key as a bearer token. All endpoints live under https://gitapprove.com/api/v1 and return JSON.
curl https://gitapprove.com/api/v1/prs \
-H "Authorization: Bearer $GITAPPROVE_API_KEY"GET /prs lists pull requests, newest first. Pass the returned nextCursor as cursor to read the next page.GET /prs/{id} returns a pull request and its changed files.GET /prs/{id}/chunks returns tagged code chunks. Filter with tag.GET and POST /prs/{id}/comments read and post review comments.GET /prs/{id}/guidance returns rule-based reviewer guidance derived from diff scoring, CI checks, and diff stats.GET /prs/{id}/evidence returns the evidence run for a pull request (what the repository's own tests did on the base and head revisions), and GET /prs/{id}/evidence/captures returns the captures for a file range (file, start, end). Evidence is a beta feature; both answer enabled: false or 404 when your organization does not have it. Each capture carries a performance object when timing was measured: base and head medians per metric, or for a new state only the head's, marked headOnly: true. It is null when nothing was measured. The response also lists items: what GitApprove's authoring agent was asked to show for the chunks in the range (kind, description, route), each with the ids of the captures that show it and the test behind them, or the reason it is not shown.POST /sync syncs pull requests from GitHub.GET /billing/status returns your subscription state.GET /audit returns the organization's audit trail. It needs a key with the audit:read scope and the High, BYOK or Passthrough plan; on Standard it answers 403.GET|POST /evidence/env-vars, PATCH|DELETE /evidence/env-vars/{varId}, POST /evidence/env-vars/{varId}/rotate, GET /evidence/env-vars/{varId}/history and POST /evidence/env-vars/bulk-rotate manage the environment variables evidence gives your tests (see Evidence variables below). Reads need evidence:read (or evidence:write), changes evidence:write. A secret's value is never returned, only its version and fingerprint.Every endpoint works on every plan and during the trial, except GET /audit (High, BYOK and Passthrough) and the evidence endpoints (the evidence beta). POST /sync and POST /prs/{id}/comments need an active subscription or trial and answer 402 without one. The API reference marks plan-limited operations with x-gitapprove-plans.
The API reference documents every field and lets you try requests with your key. The OpenAPI spec is at /openapi.json.
The gitapprove command works like GitHub's gh. It needs Node.js 24 or later.
npm install -g gitapprove-cli
gitapprove auth loginauth login checks your key and saves it to ~/.config/gitapprove/config.json. You can skip it by setting GITAPPROVE_API_KEY instead. To use another host, pass --base-url or set GITAPPROVE_BASE_URL. The MCP server reads the same variable and accepts --base-url too.
gitapprove pr list --state open
gitapprove pr view 142
gitapprove chunks 142 --tag security-sensitive
gitapprove comment add 142 --file src/auth.ts --line 12 -m "Consider failing closed here."
gitapprove syncEvery command accepts --json for scripts. The CLI exits with 0 on success, 1 on an API or network error, and 2 on a usage or authentication error.
The MCP server lets AI assistants such as Claude list pull requests, read diffs and tagged chunks, get reviewer guidance and evidence, post comments, and trigger syncs. It runs locally over stdio and needs Node.js 24 or later.
Add it to your client's MCP configuration. For Claude Code, use .mcp.json in your project. For Claude Desktop, use claude_desktop_config.json and restart the app.
{
"mcpServers": {
"gitapprove": {
"command": "npx",
"args": ["-y", "@gitapprove/mcp-server"],
"env": {
"GITAPPROVE_API_KEY": "gtap_..."
}
}
}
}Add GITAPPROVE_GITHUB_TOKEN to env to let the assistant post comments as you. The server provides these tools: list_prs, get_pr, get_diff_chunks, add_comment, get_review_guidance, and trigger_sync.
npm install gitapprove-sdkimport { GitApproveClient } from "gitapprove-sdk";
const client = new GitApproveClient({ TOKEN: process.env.GITAPPROVE_API_KEY });
const page = await client.pRs.listPRs(20);
for (const pr of page.items) console.log(`#${pr.number} ${pr.title}`);
await client.comments.createPrComment(page.items[0].id, {
filename: "src/auth.ts",
line: 42,
body: "Rate limit key should include the tenant id.",
});The client defaults to https://gitapprove.com. Failed requests throw ApiError with the HTTP status and response body.
The Python SDK needs Python 3.11 or later.
pip install gitapprove-sdkimport os
from gitapprove_sdk import AuthenticatedClient
from gitapprove_sdk.api.p_rs import list_p_rs
client = AuthenticatedClient(
base_url="https://gitapprove.com",
token=os.environ["GITAPPROVE_API_KEY"],
)
with client:
page = list_p_rs.sync(client=client, limit=20)
for pr in page.items:
print(f"#{pr.number} {pr.title}")Each endpoint is a module with sync, sync_detailed, asyncio, and asyncio_detailed functions. To post comments, pass headers={"X-GitHub-Token": ...} when you create the client.
Put a .gitapprove.yaml file at the root of a repository to tune how GitApprove treats it. Every section is optional, and a missing file means the defaults. Unknown top-level keys are ignored.
Anyone who can open a pull request can change the file in their branch, so the settings that decide what GitApprove does for you or what it spends are read from the pull request's base branch, never its head: auto-approval's file categories, precompute, and evidence. Changing those in a pull request takes effect only after it merges, and results can lag a base-branch change by up to ten minutes. The review screen itself shows file groups using the pull request's own fileCategories, so an edit there is visible immediately but does not change any decision. release is read at the commit each release names. Auto-approval never approves a pull request that changes a .gitapprove.yaml.
fileCategories:
tests: ["cypress/**/*", "**/*.cy.ts"]
docs: ["website/**/*"]
generated: ["src/gen/**/*"]
code: ["scripts/testdata/**/*"]
precompute:
skip:
- authors: ["dependabot[bot]", "renovate[bot]"]
- draft: true
- labels: ["wip", "no-review"]
- branches: ["release/*"]
- only_paths: ["docs/**", "**/*.md"]
release:
dependsOn: ["my-org/billing-service"]
evidence:
enabled: true
sites:
- label: app
previewUrlTemplate: "https://pr-{pr}.app.example.com"
projects: ["chromium"]
paths: ["apps/web"]
maxStatesPerChunk: 5
maxTestsPerRun: 100
containerTimeoutMinutes: 15
runOnDrafts: false
runOnBotAuthors: false
installCommand: pnpm install --frozen-lockfile
installScripts: true
testCommand: pnpm exec playwright test
performance: trueGitApprove sorts changed files into code, tests, docs, and generated files, and uses that to order the review, hide generated noise, and judge auto-approval rules. Built-in heuristics handle most repositories. Use fileCategories to override them. The keys are tests, docs, generated, and code, each a list of globs. code is the escape hatch for files the heuristics mistake for something else. An override wins over the heuristics, and when several match, the one that comes first in the file wins.
Globs support * (anything except /), ** (anything, including /), and ? (one character), and are case-sensitive. A pattern with no / matches the file name in any directory, so *.cy.ts matches a/b/login.cy.ts. A pattern with a / matches the whole path from the repository root. At most 200 globs are read, each up to 256 characters. Entries that are not strings are ignored.
GitApprove prepares a pull request's review in the background when it is opened or updated: the nested summary of the change, the importance of each changed line, and the check of linked tickets' acceptance criteria. Every pull request from the repository itself is prepared unless a rule here skips it. It is not prepared in the background for pull requests from forks, when the organization has no active paid plan (trials are prepared when a member opens the pull request), when AI is not set up or its budget is used up, or for more than 120 pull requests an hour. Acceptance criteria are checked for up to five linked tickets, and only when a ticket provider is connected. Anything not prepared in the background is prepared the first time someone opens the pull request. Preparing is billed like any other review of that pull request, once per commit.
precompute.skip is a list of up to 50 rules. A pull request is skipped when any rule matches, and a rule matches when all of its keys match. A key that takes a list matches when any entry matches. A rule with no keys is rejected, because it would skip everything.
authors: the pull request author's GitHub login, such as dependabot[bot].labels: a label on the pull request as reported when GitHub sent the event that queued preparation. A label added later, or a pull request first prepared when someone opens it, is not seen.branches: the head branch (the branch with the changes).base_branches: the base branch (the branch being merged into).titles: the pull request title.draft: true or false.only_paths: globs, with the syntax above. Matches when every changed file matches at least one glob, so docs/** skips documentation-only pull requests. A pull request with no files never matches.For authors, labels, branches, base_branches, and titles, * matches any run of characters, ? matches one character, and case is ignored. Each list holds 1 to 50 entries of up to 200 characters. An unknown key or a wrongly shaped value makes GitApprove ignore the whole section and prepare every pull request, so a typo cannot silently skip reviews.
release.dependsOn is a list of other repositories, written owner/name, that this service depends on. When release planning covers a release that includes both, it suggests shipping the dependencies first. It also infers dependencies from package manifests, but never from shared names alone. A repository cannot depend on itself, and an entry that is not in owner/name form is an error.
Evidence runs the repository's tests before and after a change and attaches screenshots and recordings to the matching parts of the review. It is in beta and runs only for organizations that have been approved. It is off until evidence.enabled is true, and it runs only for pull requests into the repository's default branch. An unknown key or a wrongly typed value disables evidence for the pull request and reports the problem; it never falls back to defaults.
enabled: true or false. Default false.sites: up to 12 web apps the repository serves. Each has a label (lowercase letters, digits, and hyphens, up to 32 characters, unique), and optionally previewUrlTemplate, projects (test runner project names), and paths (directory prefixes that belong to the site). Evidence is grouped by site. A repository with one site can omit the list.previewUrlTemplate: an https link to the pull request's preview, where {pr} is the pull request number. It must name a public host (no IP addresses, localhost, or credentials) and may use only the {pr} placeholder. GitApprove only shows it as a link for the reviewer to click and never requests it.maxStatesPerChunk: most states or scenarios kept per piece of code. Default and maximum 5.maxTestsPerRun: most tests selected per run. Default and maximum 100.containerTimeoutMinutes: time limit for each of the two test environments (base and head), in minutes. Default 15, maximum 30. A value above a limit is lowered to it.runOnDrafts and runOnBotAuthors: whether evidence starts by itself on draft pull requests and on pull requests opened by bots. Default false for both. An organization owner or admin can still start a run by hand. Evidence never starts by itself for pull requests from forks, and an organization must also have evidence switched on for it.installCommand and testCommand: commands to install dependencies and run tests, up to 500 characters on one line. When absent, GitApprove detects them from your manifests.installScripts: set to false to stop dependency install scripts (such as postinstall) from running. Default true, as in a normal install. It applies to the detected npm, pnpm, and yarn installs; an installCommand runs exactly as written.performance: true or false. Default true. Set to false to turn off the three extra timing-only repetitions and the performance rows. It is read from the base branch, and the organization setting for performance evidence must also be on.Tests that need configuration (a staging URL, a sandbox API key) can get it from evidence variables, which owners and admins set on the Team page or with the API. They are not in .gitapprove.yaml. Each variable applies to every repository or to the ones you list; one for a repository wins over one for all. Names are upper case with digits and underscores, and cannot be one evidence sets itself or one that changes how a test process starts (PATH, HOME, NODE_OPTIONS, LD_PRELOAD, JAVA_TOOL_OPTIONS, DOTNET_*, EVIDENCE_* and similar).
*** in test output, failure messages, and recorded requests and responses. A secret shorter than 6 characters is replaced only where it stands alone (not inside a longer word or number); an empty value is never replaced. Screenshots cannot be redacted, so do not render secrets on a page.POST /evidence/env-vars/{varId}/rotate (or several with bulk-rotate). Set expiresAt or rotateAfterDays to get reminders before a value expires or is due. Once a value is past expiresAt, runs no longer get it (the run summary lists it as withheld, expired) until it is rotated.Each run installs the repository's dependencies from its manifests before the source is added, with network access only to the package registries of the languages it finds. Composer's GitHub downloads are fetched from codeload.github.com first; when GitHub rate-limits those, or answers 401, 403 or 404 (a private repository), GitApprove retries through api.github.com with your organization's GitHub App installation, using a token that can read the contents of the repositories the installation covers, so your private GitHub dependencies install. Runs of pull requests from forks get a token that reads public repositories only, so an outside contributor's pull request cannot pull your private repositories into output they can see. The token is added by GitApprove to the archive download only and is never visible to the install. Those requests are spread over the rest of the hour once fewer than 1,000 are left, and Composer runs at most six downloads at a time.
Evidence installs can use private dependencies without your repository holding a credential. GitApprove adds the credential to the install's requests from outside the container, so neither the install nor your tests ever see it. Private sources are used only for pull requests from the same repository; runs of pull requests from forks get none of them. Keep naming the registry in your repository as you do today; tokens in repository files are removed before the install starts.
PUT /api/v1/evidence/private-dependencies, evidence:write), picking from the GitHub App installation's repositories, or chooses All repositories in the installation. By default the install reads the pull request's own repository only. git fetches from github.com (read only; pushes are refused) and GitHub archives of private repositories use an installation token minted for the pull request's repository and the listed ones only, so a pull request's code, which runs in the install, can read exactly those repositories and no other private one. This covers Go modules (GOPRIVATE names those repositories, so they are fetched with git and never sent to the public Go proxy), npm, pnpm and Yarn github: and git+https:// dependencies (including git+ssh:// lockfile entries, fetched over HTTPS), pip git+https:// requirements, Bundler git: and github: sources, and Composer vcs repositories..npmrc, settings.xml, NuGet.config or Gemfile at npm.pkg.github.com (or the Maven, NuGet or RubyGems host) without a token.POST /api/v1/evidence/registries, evidence:write): the exact host, a path prefix that names the repository on that host (required, for example /artifactory/api/npm/npm-private/, not /: only requests under it are allowed and get the credential), the ecosystem, and a bearer token, a user and password, or a custom header. A request whose path has an encoded / or \, a ;, .. or // gets no credential (npm's @scope%2Fname aside), and a response that repeats the credential is refused. Widening the prefix later needs the credential entered again. The credential is write-only, shown by version and fingerprint, and can be rotated. pip reads a pip.conf at the repository root; Maven reads .mvn/settings.xml when .mvn/maven.config passes -s; a Go registry is asked before proxy.golang.org, and the module paths you list skip the public checksum database.registry.npmjs.org as a registry with ecosystem npm, your scopes (@acme) and an npm read-only token; it is sent with those scopes' packages only.With the package cache's private opt-in, immutable downloads from these sources are cached for your organization only; git fetches are not cached.
By default the tests in GitApprove's sandbox have no network at all. An owner or admin can turn on Package registries and allowed hosts in the Team page under Evidence, Test network (or with PUT /api/v1/evidence/test-network, evidence:write): the tests' requests then go through GitApprove's gateway and may reach the public package registries the install uses and the hosts you list. A host is api.example.com, *.example.com (any subdomain at any depth, not example.com itself), http://legacy.example.com (plain HTTP for that host; everything else is HTTPS only), or a public IP address. GitApprove adds no credential to these requests (registry and GitHub credentials stay with the install), refuses private, loopback, link-local and cloud metadata addresses (also when a name resolves to one, checked at every request and redirect), and records every request as evidence. Secret evidence variables still reach pull requests from the same repository only.
* allows every public host. A pull request's code runs in the tests, so with the network on it can send what it reads (the repository, plain evidence variables, secret ones for same-repository pull requests) to any host you allow; with *, anywhere. List the hosts your tests need instead. Evidence from your own GitHub Actions is not affected: your runner already has its network.
With the package cache add-on (organization settings, owners and admins), published archives come from a cache: npm tarballs, PyPI files, Go module versions, Maven Central release artifacts, NuGet packages, RubyGems gems, and GitHub archives at a full commit SHA. Indexes and metadata, branches and tags, and snapshots are always fetched from the registry. An archive is shared with other organizations only after its bytes match the digest its registry publishes (npm integrity, the PyPI URL digest, the Go checksum database, Maven Central's checksum files, the NuGet catalog, the RubyGems index); GitHub archives, which have none, only after two independent downloads match. Until then only the organization that downloaded it reads it, and an archive that does not match is fetched from the registry instead. With the private opt-in, archives of your private GitHub repositories and archives a registry marks private are cached too, readable only by your organization (and not by runs of pull requests from forks) and deleted when you switch the opt-in off; without it they are not cached. Every cached archive is re-checked as it is served, and anything unused for 7 days is deleted.
Alongside behavior, evidence reports a measured timing for each state, taken from your tests in the evidence container, not from a user device. For an API state it records the request latency and, where the server is instrumented, the number of database queries. Query counts are available for Node servers (pg, mysql2, better-sqlite3, node:sqlite, sqlite3, postgres.js, tedious/mssql and MongoDB) and Python servers built on http.server, wsgiref, or uvicorn or hypercorn in ASGI mode (sqlite3, psycopg, psycopg2, PyMySQL and asyncpg); ORMs such as Drizzle, Prisma driver adapters, SQLAlchemy and the Django ORM are counted through their driver (under Jest, only better-sqlite3, sqlite3, node:sqlite and postgres.js 4). A request whose queries cannot be counted shows "no query data", never a zero. Latency works for a server in any language. Tests run under Playwright, node:test, Jest, Vitest, pytest, Go (go test), JUnit (Maven or Gradle), .NET (dotnet test, and MSTest, NUnit, xUnit v3 and TUnit on Microsoft.Testing.Platform), RSpec, Minitest, PHPUnit and Pest; requests from Go, JVM, .NET, Ruby and PHP tests to a local server are recorded too (in-memory test clients such as MockMvc, TestServer, Rack::Test and Laravel's test requests make no request and are not), and servers in those languages report their query counts with the headers or log described below. For a browser state it records render time and long tasks. Each number is the median of three repetitions that run only for timing.
A state that exists on both revisions shows base against head, and a change is highlighted only when it passes both an absolute and a relative threshold and either the samples are not noisy or the two sides do not overlap at all. A new state (one that only the head produces) shows the head's numbers as "New", with no comparison and never highlighted. A timing is a measurement for the reviewer, not a verdict: it never changes which states differ, how they are ordered, or any approval.
For a server in a language or database driver the evidence runner does not hook (Go, Java and other JVM languages, .NET, Ruby, PHP, or a Node or Python driver outside the list above), the application can report its own query counts. Both ways below are active only in the timing repetitions, so check EVIDENCE_PERF_RUN and do nothing when it is not set; the first test run, which produces the captures, never reads them.
X-Evidence-Query-Count (a plain non-negative integer of at most nine digits) and, optionally, X-Evidence-Query-Time-Ms (non-negative, up to three decimals) on each response. The test client the runner loads (Node http, https and fetch; Python requests and httpx; Go's net/http client; JVM clients that use the default proxy selector, such as HttpURLConnection, java.net.http.HttpClient and OkHttp; .NET's HttpClient; Ruby's Net::HTTP; PHP's curl and http streams) reads them, so the tests must use one of those. Anything that is not a plain number (a sign, an exponent, a list from a repeated header) is ignored, and a time without a valid count is ignored. Headers must be set before the response starts, so queries made after that point cannot be counted this way (use the log).EVIDENCE_QUERY_LOG to a file path in every repetition. Append one JSON line per request: method, target (path and query as requested), start and end (epoch milliseconds), queryCount and queryTimeMs. Use this for streaming responses or queries after the headers are sent. The log is joined to the requests a recorded test client made, so it needs one of those clients too. A line is matched to the test's request with the same method and target when its start falls inside the request's (a 5 ms tolerance; end must not be before start), and each line is used once. Malformed lines and lines over 4,096 characters are skipped, and only the first 8 MiB or 50,000 lines of the file are read.For each measured request the first of these that has a count is used: the runner's own driver hook, then the header, then the log. A line reported by the application is marked "(reported by the app)", or "(partly reported by the app)" when only some of the counts were. These numbers come from the pull request's own code, like everything else in evidence: they are a measurement for the reviewer, not a control, and nothing about them gates, scores or approves.
# config/initializers/evidence.rb
class EvidenceQueryCount
def initialize(app)
@app = app
end
def call(env)
n = 0
me = Thread.current
sub = ActiveSupport::Notifications.subscribe("sql.active_record") do |*, payload|
n += 1 if Thread.current == me && !payload[:cached] && !%w[SCHEMA CACHE].include?(payload[:name])
end
status, headers, body = @app.call(env)
headers["x-evidence-query-count"] = n.to_s
[status, headers, body]
ensure
ActiveSupport::Notifications.unsubscribe(sub) if sub
end
end
Rails.application.config.middleware.insert(0, EvidenceQueryCount) if ENV["EVIDENCE_PERF_RUN"]type counter struct {
http.ResponseWriter
n atomic.Int64
sent bool
}
type counterKey struct{}
func (c *counter) WriteHeader(code int) {
if !c.sent {
c.sent = true
c.Header().Set("X-Evidence-Query-Count", strconv.FormatInt(c.n.Load(), 10))
}
c.ResponseWriter.WriteHeader(code)
}
// Unwrap lets http.ResponseController (Flush, Hijack) reach the real writer.
func (c *counter) Unwrap() http.ResponseWriter { return c.ResponseWriter }
func (c *counter) Write(b []byte) (int, error) {
if !c.sent {
c.WriteHeader(http.StatusOK)
}
return c.ResponseWriter.Write(b)
}
func Evidence(next http.Handler) http.Handler {
if os.Getenv("EVIDENCE_PERF_RUN") == "" {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c := &counter{ResponseWriter: w}
next.ServeHTTP(c, r.WithContext(context.WithValue(r.Context(), counterKey{}, c)))
})
}
// Call this instead of db.QueryContext (and likewise for ExecContext, QueryRowContext).
func queryContext(ctx context.Context, db *sql.DB, q string, args ...any) (*sql.Rows, error) {
if c, ok := ctx.Value(counterKey{}).(*counter); ok {
c.n.Add(1)
}
return db.QueryContext(ctx, q, args...)
}// Spring Boot 3 (jakarta.servlet); on Boot 2 use javax.servlet.
// The body is buffered so the header can still be set after the handler runs.
@Component
public class EvidenceQueryFilter extends OncePerRequestFilter {
static final ThreadLocal<int[]> COUNT = new ThreadLocal<>();
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
if (System.getenv("EVIDENCE_PERF_RUN") == null) { chain.doFilter(req, res); return; }
var wrapped = new ContentCachingResponseWrapper(res);
COUNT.set(new int[1]);
try {
chain.doFilter(req, wrapped);
wrapped.setHeader("X-Evidence-Query-Count", String.valueOf(COUNT.get()[0]));
wrapped.copyBodyToResponse();
} finally { COUNT.remove(); }
}
}
public class CountingInspector implements StatementInspector {
@Override
public String inspect(String sql) {
int[] c = EvidenceQueryFilter.COUNT.get();
if (c != null) c[0]++;
return sql;
}
}
// application.properties:
// spring.jpa.properties.hibernate.session_factory.statement_inspector=com.example.CountingInspector// Program.cs (using System.Data.Common; using Microsoft.EntityFrameworkCore.Diagnostics;)
// Put this before the endpoints are mapped.
if (Environment.GetEnvironmentVariable("EVIDENCE_PERF_RUN") is not null)
{
app.Use(async (ctx, next) =>
{
var count = new int[1];
CountingInterceptor.Current.Value = count;
ctx.Response.OnStarting(() =>
{
ctx.Response.Headers["X-Evidence-Query-Count"] = count[0].ToString();
return Task.CompletedTask;
});
await next();
});
}
public sealed class CountingInterceptor : DbCommandInterceptor
{
public static readonly AsyncLocal<int[]?> Current = new();
// One call per command EF creates, which is one round trip.
public override DbCommand CommandCreated(CommandEndEventData eventData, DbCommand result)
{
if (Current.Value is { } c) Interlocked.Increment(ref c[0]);
return result;
}
}
// options.AddInterceptors(new CountingInterceptor()) in AddDbContext// app/Http/Middleware/EvidenceQueryCount.php (add it to the global middleware)
use Closure;
use Illuminate\Support\Facades\DB;
class EvidenceQueryCount
{
public function handle($request, Closure $next)
{
if (!getenv('EVIDENCE_PERF_RUN')) {
return $next($request);
}
$n = 0;
// Listeners live as long as the process: not for Octane or other long-lived workers.
DB::listen(function () use (&$n) { $n++; });
$response = $next($request);
$response->headers->set('X-Evidence-Query-Count', (string) $n);
return $response;
}
}Outside a framework, call ob_start() at the top of the script when EVIDENCE_PERF_RUN is set, and send the header from a shutdown function with header(), before the buffer is flushed. PHP-FPM clears the environment by default, so set clear_env = no or run the tests against php -S. These examples are starting points: adapt the counting to the database layer you use, and count only queries the request itself makes.
Some test suites need more than a sandbox can give them: a database with seed data, service containers, a build that takes your caches. Add the GitApprove/evidence step to your own workflow, after your own setup steps, and GitApprove's evidence runner runs the selected tests in that job, on the environment you prepared, then sends the results to the review. The review uses them exactly like sandbox evidence and labels them "Ran in your GitHub Actions".
# .github/workflows/evidence.yml
on: pull_request
permissions:
contents: read
id-token: write # the OIDC token GitApprove verifies; no API key
jobs:
evidence:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
# Your own setup: services, databases, seeds, builds.
- run: docker compose up -d && npm ci && npm run db:seed
- uses: GitApprove/evidence@v1
env:
DATABASE_URL: postgres://app:app@localhost:5432/app
with:
secret-env: DATABASE_URL # removed from everything uploadedpermissions: id-token: write. The action asks GitHub for an OIDC token with the GitApprove URL as its audience; GitApprove checks GitHub's signature, the issuer, the audience and the time, and that the token's repository and pull request belong to your organization. There is no API key or secret to store.base-setup), and uploads the results. Your checkout is left as it was.gitapprove-evidence names, runs the tests it asks for on head or base, posts the results to POST /api/v1/evidence/action/author and does what the answer asks next, until the agent has a capture for each item or a reason. Then it runs the tests the agent kept with the planned ones on head and base. They are deleted before the step ends and never committed; the review shows each item with its capture and the test's source, labelled "Written by GitApprove".run-id, status, review-url, summary.| Input | Default | Meaning |
|---|---|---|
url | https://gitapprove.com | The GitApprove URL. |
audience | the url | The OIDC token audience. Change it only if GitApprove asks you to. |
working-directory | . | The project whose tests run, for monorepos. |
timeout-minutes | 30 | Most time for one revision's tests; your evidence configuration's container timeout (15 minutes by default) caps it. |
base-setup | auto | Prepares the base revision's worktree: auto runs the install command detected from your lockfiles, none runs nothing, anything else is a shell command. |
base-setup-timeout-minutes | 10 | Most time for the base setup. |
secret-env | (none) | Names of variables whose values are removed from everything uploaded. Names containing TOKEN, SECRET, PASSWORD, KEY, CREDENTIAL, PRIVATE or AUTH always are. |
fail-on-error | false | Fail the step when GitApprove is unreachable or refuses the upload. By default the step only warns, so GitApprove never fails your job. |
The tests get the job's environment (the step's env, service ports, what earlier steps exported) and your organization's plain evidence variables, with the job's values winning. They never get GitHub's own credentials (ACTIONS_*, GITHUB_TOKEN) or names the runner sets itself (PATH, HOME, NODE_OPTIONS, ...). Secret evidence variables stay in GitApprove: map your own Actions secrets into the step's env instead. Values of secret-looking variables, and of those named in secret-env, are replaced with *** before upload, and GitApprove removes your secret evidence variables' values again before storing. Screenshots cannot be redacted.
GitHub gives pull_request runs from forks no OIDC token, so fork pull requests get no evidence from the action: with the source set to both, GitApprove's sandbox covers them when an owner or admin starts a run; with GitHub Actions only, they have none. Never use the action in a pull_request_target workflow: that event runs with your repository's secrets and a write token, so running a pull request's tests there hands both to its author. The action refuses to run under it, and GitApprove refuses its tokens.
In GitApprove's sandbox the tests run in an isolated container with no network, after an automated safety check. In your workflow they run on your runner with whatever the job can reach, and the safety check does not run: it is your CI, as it already is for these tests. The review labels each run "Ran in your GitHub Actions" or "Ran in GitApprove's sandbox". In both cases the results come from the pull request's own code: GitApprove validates and bounds them (file names and sizes, the manifest, every image) and shows them as evidence, not as a verdict.
In GitHub Actions mode, the tests GitApprove's agent writes run in your workflow's job, on your runner, with that job's environment. That environment is filtered first: ACTIONS_*, GITHUB_TOKEN, GH_TOKEN, INPUT_*, the runner's command files and the names the evidence runner reserves are removed for every test. While any GitApprove-written test is in the checkout, every test the step runs (your own too) also gets no variable whose name looks secret (TOKEN, SECRET, PASSWORD, PRIVATE, CREDENTIAL, API_KEY, ACCESS_KEY, AUTH, or a name in the secret-env input): a test process loads more than one file (a Go package, a JVM or .NET build, conftest.py, autoloaders), so an authored file could read them from your test's process otherwise. They use reserved gitapprove-evidence file names, are screened like sandbox tests, and are deleted before the step ends.
What they can reach: your runner's network, and the job's variables whose names do not look secret (for example DATABASE_URL, including a password inside it: list such names in secret-env). The content checks on authored tests (no processes, no hosts but loopback, the safety screen) read a test's text; in your CI they are not a security boundary, as the sandbox's isolated container with no network is in GitApprove. To turn authored tests off for a workflow, set authored-tests: false on the step: GitApprove then uses your own tests only, and the review shows what only a new test could show as "not produced: authored tests disabled in this workflow".
Artifacts are streamed to GitApprove's storage one by one with single-use upload tickets (10 minutes, bound to each file's size and SHA-256), never in an API request body: at most 100 MiB an artifact and 300 MiB a run. Playwright tests are recorded; a recording over the limit is re-encoded smaller with ffmpeg when the runner has it, or left out with a note.
The tests use your GitHub Actions minutes, not GitApprove's compute. Each uploaded run counts as one evidence minute per started block of 40 screenshots, at least one, in the evidence add-on's monthly allowance (750 included; $0.05 each beyond it when overage is on). A plan that has nothing to run, or whose upload never arrives, costs nothing. Tests GitApprove writes add one evidence minute per started 2 cents of model cost when GitApprove pays for the model; none when your organization uses its own AI key.
id-token: write to the job's permissions (forks never get one).actions/checkout's default credentials, or use fetch-depth: 0) or base-setup failed. The run is then partial: every capture reads as new.actions/checkout checks out by default); anything else is refused. Use one evidence step per workflow run: a second job with the same step finds the run already finished.fail-on-error: true.