Acceptance Contracts for AI-Authored Pull Requests
Turn AI-written pull requests into reviewable changes with requirement-linked evidence, trusted CI checks, commit-bound decisions, and risk-aware human approval.
On this page
A coding assistant can produce a patch that compiles, passes a test suite, and still leaves the team unable to answer a basic question: what evidence shows that this change meets the actual product requirement?
I would treat an AI-authored pull request as a proposed implementation, not as an outcome already verified. The missing component is an *acceptance contract*: a small, maintainer-owned description of the behaviors that must be preserved, the checks that can provide evidence, and the people who must approve the remaining risks.
This is not a new benchmark for model intelligence. It is an engineering interface between a requested change, an untrusted patch, and a merge decision. It works for human-authored code too, but becomes especially valuable when agents can produce many convincing patches faster than maintainers can inspect them.
Start with a behavior the code must not violate
Imagine a multi-tenant analytics application with a new endpoint for daily workspace usage. A coding agent implements the controller, returns the right JSON shape, and adds tests for the requested date range. Everything passes in its local harness.
The essential requirement, however, is that usage must be scoped to the authenticated tenant. If a request-supplied tenant identifier controls the SQL filter, the endpoint can be structurally correct while exposing another workspace's data.
This example is hypothetical; it is not an account of an incident or a measured agent failure. It illustrates why a ticket such as “add daily usage reporting” is an insufficient test oracle.
Before assigning the change, I would record the acceptance behavior:
| Requirement | Acceptance evidence | Failure behavior |
|---|---|---|
| Only authenticated tenants receive data | Integration tests with two independently seeded tenants | Deny access, not an empty success that hides an authorization bug |
| Start is inclusive and end is exclusive in UTC | Boundary fixtures covering adjacent timestamps | Reject malformed ranges |
| The endpoint uses bounded database work | Query-plan review and a configured maximum range | Reject oversized requests |
| A successful response has the agreed contract | API-schema validation and consumer-facing tests | Fail CI on incompatible response changes |
| A security-sensitive change has an accountable owner | Review enforced by protected repository settings | Block merge until an authorized reviewer approves |
These are *claims we want to establish*, not claims that a CI suite has already established. Some evidence can be generated mechanically; query plans, authorization design, and operational load may still need judgment.
A practical distinction matters: an acceptance contract describes the system's desired behavior outside the agent's own implementation. If an agent is free to rewrite both the code and the only tests that define success, a green run is weak evidence.
Separate the requested change from its proof
I would keep the review decision across four boundaries rather than collapse it into one “agent finished” signal.
~~~text Maintainer-owned requirements / risk policy | v Proposed change at commit SHA | v Isolated build + independently selected checks | v Verified evidence bound to that exact SHA | +-----------+-----------+ | | Missing/failed Evidence complete | | Revise or stop Code-owner judgment | Merge under ruleset ~~~
The critical distinction is between an assertion and evidence. The agent can assert “tenant isolation is covered.” The trusted CI job must actually exercise the isolation case and report which revision it tested. A reviewer still decides whether the chosen tests capture the underlying requirement.
GitHub's repository rulesets can require status checks, specific review conditions, and code-scanning results. They are enforcement mechanisms, not a substitute for well-chosen acceptance criteria. NIST's Secure Software Development Framework similarly frames verification and secure development as lifecycle practices, rather than something supplied by the authoring tool.
Give each requirement a stable identifier
A lightweight contract could live in an issue template or a repository-controlled change request, and be reviewed before implementation:
~~~yaml change: usage-summary-v2 risk: security-sensitive requirements: - id: AUTH-01 statement: "A tenant cannot read another tenant's usage." evidence: "integration:usage-tenant-boundary" - id: TIME-02 statement: "Ranges use inclusive start and exclusive end." evidence: "integration:usage-time-boundaries" - id: API-03 statement: "Response remains compatible with the published schema." evidence: "contract:usage-response" review: owners: ["platform", "security"] ~~~
This is an illustrative application format, not a GitHub-native schema. It needs a service-side validator and a protected source of truth. Merely committing this YAML in the agent's branch would let the author weaken its own requirements.
Stable IDs make a useful join key between specification, checks, and review. They should not become a game where teams create one assertion per line of code. Each ID should represent a consequential property that can survive implementation refactoring.
For a low-risk text change, a short contract can point to the normal lint, build, and preview checks. For an authorization path, a data migration, or an external side effect, the contract should be more explicit and require an appropriate owner.
TypeScript: make the tenant boundary testable
The implementation should derive security scope from trusted session context, not from a request parameter. Here is a deliberately small service boundary for a usage summary:
~~~typescript type Actor = Readonly<{ tenantId: string; role: "analyst" | "admin"; }>;
type Database = { query<T>( sql: string, params: readonly unknown[] ): Promise<{ rows: T[] }>; };
type DailyUsage = { day: string; event_count: number; };
export async function dailyUsage( db: Database, actor: Actor, start: Date, end: Date, ): Promise<DailyUsage[]> { if ( !actor.tenantId || (actor.role !== "analyst" && actor.role !== "admin") ) { throw new Error("forbidden"); }
const from = start.getTime(); const until = end.getTime(); const maxWindowMs = 31 * 24 * 60 * 60 * 1000;
if ( !Number.isFinite(from) || !Number.isFinite(until) || until <= from || until - from > maxWindowMs ) { throw new RangeError("invalid usage range"); }
const result = await db.query<DailyUsage>( [ "SELECT (occurred_at AT TIME ZONE 'UTC')::date AS day,", " count(*)::int AS event_count", "FROM usage_events", "WHERE tenant_id = $1", " AND occurred_at >= $2", " AND occurred_at < $3", "GROUP BY 1 ORDER BY 1", ].join("\n"), [actor.tenantId, start, end], );
return result.rows; } ~~~
This example assumes the HTTP authentication layer produces Actor from a verified session and supplies a database adapter. It does not itself authenticate the caller. The SQL assumes occurred_at is a PostgreSQL timestamptz column, the application stores timestamps consistently, and the desired day grouping is UTC.
A test that merely mocks db.query and checks that it was called cannot establish tenant isolation. It can establish that the application passes the expected tenant parameter. The stronger evidence is a real database integration test with two tenants, conflicting fixture rows, role-denial cases, and attempts to submit someone else's tenant identifier through the public HTTP interface.
For example, a relevant acceptance-test outline is:
~~~typescript import { strict as assert } from "node:assert"; import { test } from "node:test";
// These helpers belong to the application's authenticated API test harness. test("workspace A cannot observe workspace B's usage", async () => { const app = await createIsolatedTestApp(); try { await app.seedUsage("workspace-a", "2026-10-01T12:00:00Z"); await app.seedUsage("workspace-b", "2026-10-01T12:00:00Z");
const tokenA = await app.issueSession("workspace-a", "analyst"); const response = await app.get("/api/usage?from=2026-10-01&to=2026-10-02", { token: tokenA, query: { tenantId: "workspace-b" }, // Malicious client input });
assert.equal(response.status, 200); assert.deepEqual(response.body.days, [ { day: "2026-10-01", event_count: 1 }, ]); } finally { await app.close(); } }); ~~~
The createIsolatedTestApp and related methods are application-specific test-harness interfaces, not built-in Node.js APIs or a copy-paste runnable example. The test must exercise the real authentication and database paths, or it risks certifying a mock instead of a security invariant.
For defense in depth, consider database-level tenant isolation, including PostgreSQL row security policies when appropriate. Their correct operation depends on database roles, policy configuration, and connection handling; simply enabling a policy is not evidence that every code path is safe.
Python: evaluate evidence without trusting the author
A small policy function can check whether required claims have trustworthy results for the exact proposed commit. It should run inside a CI or review service that obtains results from the CI provider, not read a file that the coding agent itself wrote and called “verified.”
~~~python from dataclasses import dataclass from typing import Literal
Outcome = Literal["pass", "fail", "unknown"] Origin = Literal["trusted_ci", "submitted_by_author"]
@dataclass(frozen=True) class Result: requirement: str commit_sha: str outcome: Outcome origin: Origin
def acceptance_decision( head_sha: str, required: set[str], results: list[Result], requires_owner: bool, ) -> tuple[str, list[str]]: if not head_sha or not required: return "block", ["Missing commit identity or requirements"]
findings: list[str] = [] by_requirement: dict[str, Result] = {}
for result in results: if result.requirement not in required: continue if result.requirement in by_requirement: findings.append(f"Duplicate evidence: {result.requirement}") by_requirement[result.requirement] = result
for requirement in sorted(required): result = by_requirement.get(requirement) if result is None: findings.append(f"Missing evidence: {requirement}") elif result.commit_sha != head_sha: findings.append(f"Stale evidence: {requirement}") elif result.origin != "trusted_ci": findings.append(f"Untrusted evidence: {requirement}") elif result.outcome != "pass": findings.append(f"Unmet requirement: {requirement}")
if findings: return "block", findings if requires_owner: return "owner_review", [] return "eligible_for_repository_rules", []
A review is required even when the evidence is complete.
sample = [Result("AUTH-01", "abc123", "pass", "trusted_ci")] assert acceptance_decision( "abc123", {"AUTH-01"}, sample, True )[0] == "owner_review" ~~~
This is an example of decision logic, not a complete secure integration. A string reading trusted_ci is not cryptographic provenance. The caller must authenticate CI results, bind them to the repository and workflow identity, and confirm that the checks executed the intended source and dependency versions.
The same caution applies to “AI reviewer approved” statuses. They can be useful diagnostic signals. They should not manufacture an independent source of authority when they come from the same prompt, model, or repository files that produced the patch.
Bind approval to the revision that will merge
A common race is to review commit A and then receive an agent-generated commit B before merge. The approval and test evidence for A must not silently authorize B.
I would record at least the repository identity, base revision, head commit SHA, acceptance-contract version, CI run identifiers, and applicable policy version. If the head changes, the evidence must be recomputed. If the base changes materially, the merge path needs the configured freshness or integration checks.
GitHub documents dismissal of stale approvals and the distinction between strict and loose required checks. If a repository uses a merge queue, required GitHub Actions checks must also run for the `merge_group` event; a green pull-request check alone is not proof that the eventual grouped merge was tested.
Do not confuse a commit-bound CI result with a formal proof of correctness. The value is traceability: a reviewer can answer *which revision, under which policy, produced which evidence*.
Protect the verifier from the patch it evaluates
The acceptance gate is a security boundary, and agent-authored code is untrusted input even when the agent operates on a trusted repository. A malicious or merely mistaken patch may modify test scripts, dependency hooks, workflow files, or the files that describe acceptance criteria.
I would apply several constraints:
- Keep policy and required-check definitions under protected ownership. GitHub's CODEOWNERS documentation explains base-branch ownership and how to protect the owner file itself.
- Run patch builds in isolated, least-privilege environments. The GitHub Actions secure-use guidance explicitly warns against running untrusted pull-request code with privileged workflows or credentials.
- Never interpolate untrusted issue titles, PR descriptions, branch names, or model-generated text directly into shell scripts. GitHub documents script-injection paths through workflow contexts.
- Require a trusted identity for required status checks where the hosting platform supports it. Repository rulesets can restrict a check to an expected GitHub App; arbitrary “success” statuses should not satisfy the acceptance contract.
- Treat dependency modifications and generated build artifacts as separate supply-chain risks. Static analysis, dependency checks, and secret scanning complement behavior tests but do not replace them.
A particularly subtle trap is to let the patch choose all the test commands. The agent may not intend to bypass anything; a renamed script or narrowed test selector can still make the evidence incomplete. Acceptance checks must be selected by protected policy, while tests from the PR can be additional evidence.
For generated-code execution boundaries, see my earlier article on isolating agent-produced code. For the broader principle that a tool invocation needs authorization independent of the model, see agent tool authorization.
Where the design can fail
| Failure mode | Detection or mitigation |
|---|---|
| Requirements written after implementation to match the patch | Have a maintainer approve the contract before agent work; version subsequent amendments |
| Tests exercise mocks, not the real authorization boundary | Mark test scope clearly; add database and HTTP integration evidence |
| CI evidence refers to an earlier head SHA | Fail closed on mismatched revision; rerun when the patch changes |
| Agent edits a workflow so checks disappear | Protect required checks and their source; review workflow/policy changes separately |
| A reviewer model produces a confident but unsupported approval | Make its output advisory; require citations to actual files, tests, and conditions |
| A check is flaky or an external service is down | Distinguish unknown from pass; use bounded retries and escalation rather than a green fallback |
| Acceptance evidence passes while the product contract was incomplete | Maintain production incident feedback, security reviews, and human judgment; expand contract examples when justified |
No gate can eliminate specification risk. A perfectly implemented contract can still express the wrong product requirement. That is why a senior reviewer must inspect the *intent* and the *consequences*, not only an automatically assembled report.
Observability should measure review quality, not agent activity
Counting completed agent tasks and green CI runs mostly measures throughput. To decide whether an acceptance contract helps, I would instrument the review pipeline itself.
Useful measures include required-evidence coverage, stale-evidence rejections, unknown/blocked check outcomes, time from initial proposal to reviewed merge, revision count after reviewer feedback, human-found defects after all automated checks passed, and post-merge rollback or defect reports. Segment by change class and risk tier; aggregate rates without exposing repository secrets, customer data, or sensitive patch content as metric labels.
Do not present “approval rate” as a quality score on its own. A permissive gate can produce excellent approval numbers. Compare outcomes against a baseline and investigate false approvals as well as false blocks. For CI and model-evaluation patterns, my article on regression gates for LLM applications explains why an evaluation must be kept representative, while evaluating an agent's full trajectory addresses why a correct-looking final answer can hide a bad process.
Keep an auditable record of the acceptance-contract revision, tests selected, verified checks, reviewer decision, and final merge revision. See decision records for production agents for a related approach to attaching evidence to consequential actions.
Roll out the smallest gate that adds real confidence
I would not start by building a universal AI grading service. Begin with one high-risk category, such as tenant-scoped reads or permission changes. Write two or three behavioral invariants, add a trustworthy integration test, and enforce an owner review.
Next, automate the evidence report and SHA matching. Only after those deterministic boundaries are reliable would I introduce an optional model-based review assistant to suggest missing scenarios or explain surprising diffs. Its suggestions should be independently checked; its scores should not become uncalibrated merge authority.
The trade-off is additional test cost, review time, and contract maintenance. For a low-risk documentation edit, this process may cost more than it prevents. For changes to identity, billing, cross-tenant data, or irreversible operations, the cost of uncertain evidence is much higher.
The goal is not to make every generated patch wait behind another elaborate abstraction. It is to make the decision to merge explainable, reproducible, and proportional to the risk.
Primary technical references
- GitHub: Available repository rules and required status checks
- GitHub: CODEOWNERS and required owner reviews
- GitHub: Secure use of Actions
- GitHub: Script injection and untrusted workflow contexts
- GitHub: Required checks with merge queues
- PostgreSQL: Row security policies
- NIST SP 800-218: Secure Software Development Framework
Topic discovery: Viral Ruparel's essay on coding-agent merge readiness, published October 26, 2026. The acceptance-contract model, multi-tenant reporting scenario, code, diagram, and engineering recommendations above are independently developed for this portfolio article.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article