AI Coding Agents on a Production Codebase
AI agents can open PRs in minutes. What makes that safe on a production codebase: instruction files, tests as guardrails, small tasks, and a review checklist - with real red/green test runs against a one-shot-style draft.
Table of contents
An AI coding agent can open a pull request against your production codebase before your coffee cools. The question this article answers is not whether to let it - it's what scaffolding makes that safe: instruction files, tests as guardrails, tasks small enough to review, and a checklist for the PRs it opens. The cancellation example below was executed end to end on a real Laravel 13 app - the red and green test runs are embedded verbatim.
Why production codebases are different#
A greenfield script forgives. A production codebase is a web of invariants the agent cannot see in one file: who owns this row, which states this model may leave, whether this endpoint runs twice on retries, what gets audited. An agent optimizing for "make the request work" will produce the shortest path that looks right - and quietly skip every invariant it wasn't told about. Your job is to make the invariants loud.
Instruction files: tell the agent what it can't see#
Most coding agents read a repo-level instruction file - the agents.md convention is the common one, but filename, scoping and nesting support vary by tool, so check what your agent actually reads. Treat the file as the onboarding doc for something with no memory of your incidents: commands, invariants, forbidden zones.
# Commands
- Tests: php artisan test --parallel
- One test: php artisan test --filter=OrderTest
# Invariants (never violate)
- Money is integer minor units. No floats near currency.
- Status changes go through a guarded transition: ownership check, legal-state
check, audit row, one transaction. Never an unguarded write.
- Destructive or bulk operations require a human-written migration, reviewed.
# Forbidden zones (do not edit without being asked)
- database/migrations/**
- config/services.php, .env*Keep it short and current - a stale instruction file is worse than none, because the agent trusts it.
Tests as guardrails: a real catch#
This is a deliberately minimal "before" draft, written in the style of a one-shot AI answer to "Laravel controller to cancel an order" - plausible, compact, and missing four production guarantees:
// Intentionally unsafe teaching draft, written in the style of a one-shot AI
// answer to "Laravel controller to cancel an order": plausible, compact, and
// missing four production guarantees (ownership, state guard, idempotent
// replay, audit). It is the "before" the review checklist is applied to.
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\Request;
class CancelOrderController extends Controller
{
public function __invoke(Request $request, Order $order)
{
$order->status = 'cancelled';
$order->save(); // no lock, no transaction: concurrent requests race here
return response()->json(['message' => 'Order cancelled']);
}
}The four missing guarantees: no ownership check (any authenticated user cancels anyone's order), no state guard (a shipped order gets "cancelled"), no idempotent replay handling (nothing defines what a duplicate cancel request means), no audit trail (no record of who cancelled, when). None of them were stated in the one-line prompt, so nothing forced them into the code.
Here is the draft after review - every check decided under a row lock inside one transaction, so concurrent cancellations serialize instead of racing:
// The draft after the PR review checklist: ownership check, state guard,
// idempotent replay, and an audit trail with actor - all decided under the
// same row lock, inside one transaction, so concurrent requests serialize.
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
class CancelOrderController extends Controller
{
public function __invoke(Request $request, Order $order)
{
return DB::transaction(function () use ($request, $order) {
// Re-read and lock: every check below must see the latest committed state
$order = Order::whereKey($order->id)->lockForUpdate()->firstOrFail();
abort_unless($request->user()->id === $order->user_id, 403);
if ($order->status === 'cancelled') {
return response()->json(['message' => 'Order already cancelled']); // idempotent replay
}
if (!in_array($order->status, ['pending', 'paid'], true)) {
throw new ConflictHttpException("cannot cancel an order in status {$order->status}");
}
$order->status = 'cancelled';
$order->cancelled_at = now();
$order->save();
DB::table('order_events')->insert([
'order_id' => $order->id, 'type' => 'cancelled',
'actor_id' => $request->user()->id, // who cancelled
'created_at' => now(),
]);
return response()->json(['message' => 'Order cancelled']);
});
}
}Registered behind the auth middleware, so unauthenticated requests never reach it:
use App\Http\Controllers\CancelOrderController;
Route::post('/orders/{order}/cancel', CancelOrderController::class)->middleware('auth');And the guardrail suite, with what actually happens when it runs against the draft versus the reviewed version:
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
class CancelOrderTest extends TestCase
{
private function makeOrder(string $status = 'paid', ?int $userId = null): int
{
return DB::table('orders')->insertGetId([
'gateway_ref' => 'PM-' . $status . '-' . uniqid(),
'amount_minor' => 5000, 'currency' => 'EGP',
'status' => $status,
'user_id' => $userId ?? User::factory()->create()->id,
]);
}
public function test_owner_cancels_a_paid_order_with_audit_trail(): void
{
$user = User::factory()->create();
$id = $this->makeOrder('paid', $user->id);
$this->actingAs($user)->postJson("/orders/$id/cancel")->assertOk();
$this->assertSame('cancelled', DB::table('orders')->where('id', $id)->value('status'));
$event = DB::table('order_events')->where('order_id', $id)->where('type', 'cancelled')->first();
$this->assertNotNull($event);
$this->assertSame($user->id, $event->actor_id); // who cancelled
}
public function test_other_users_order_is_forbidden(): void
{
$id = $this->makeOrder('paid');
$this->actingAs(User::factory()->create())->postJson("/orders/$id/cancel")->assertForbidden();
$this->assertSame('paid', DB::table('orders')->where('id', $id)->value('status'));
}
public function test_shipped_order_cannot_be_cancelled(): void
{
$user = User::factory()->create();
$id = $this->makeOrder('shipped', $user->id);
$this->actingAs($user)->postJson("/orders/$id/cancel")->assertStatus(409);
$this->assertSame('shipped', DB::table('orders')->where('id', $id)->value('status'));
}
public function test_cancelling_twice_is_idempotent(): void
{
$user = User::factory()->create();
$id = $this->makeOrder('paid', $user->id);
$this->actingAs($user)->postJson("/orders/$id/cancel")->assertOk();
$this->actingAs($user)->postJson("/orders/$id/cancel")->assertOk();
$this->assertSame(1, DB::table('order_events')->where('order_id', $id)->count());
}
public function test_unauthenticated_requests_get_401_and_change_nothing(): void
{
$id = $this->makeOrder('paid');
$this->postJson("/orders/$id/cancel")->assertUnauthorized();
$this->assertSame('paid', DB::table('orders')->where('id', $id)->value('status'));
$this->assertSame(0, DB::table('order_events')->where('order_id', $id)->count());
}
}Against the draft, 4 of the 5 tests go red - the real output:
1) CancelOrderTest::test_owner_cancels_a_paid_order_with_audit_trail
Failed asserting that null is not null.
2) CancelOrderTest::test_other_users_order_is_forbidden
Expected response status code [403] but received 200.
3) CancelOrderTest::test_shipped_order_cannot_be_cancelled
Expected response status code [409] but received 200.
4) CancelOrderTest::test_cancelling_twice_is_idempotent
Failed asserting that 0 is identical to 1.
FAILURES!
Tests: 5, Assertions: 11, Failures: 4.What each failure demonstrates: (1) no audit row is ever written, so the audit assertions find null. (2) a stranger's cancel returns 200 instead of 403 - no ownership check. (3) a shipped order returns 200 instead of 409 - no state guard. (4) the double-cancel test expects exactly one audit row and finds zero. That failure proves the missing audit trail, not duplicate side effects: the draft's plain re-save happens to be externally harmless here, but nothing in the draft defines what a replay means - which is the actual gap.
(The unauthenticated-request test passes even against the draft because the route's auth middleware blocks before the controller runs - which is exactly why middleware, not controller habit, should carry that guarantee.) Against the reviewed controller:
OK (5 tests, 14 assertions)One honest limit: the row lock makes concurrent cancels serialize by construction, but this five-test suite only exercises sequential requests. It is evidence for the guards, not a parallel-concurrency proof - verifying race behavior takes a two-process test or a concurrency harness, beyond this example's scope.
The point is not that AI output is bad - the draft is a fine starting skeleton. The point is that the suite, not your eyes alone, defines what "correct" means. Tests the agent can run are instructions it cannot talk its way around.
Integration prerequisites (what the tests ran against)
This is not turnkey: the example assumes a pre-existing orders table. In the scratch app it comes from the reconciliation example's base migration with exactly these columns: id, status (string), gateway_ref (string, nullable), amount_minor (unsigned big integer), currency (string), and timestamps. The route registration (with its use App\Http\Controllers\CancelOrderController; import) is the block shown above. The Order model:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $guarded = [];
protected $casts = ['cancelled_at' => 'datetime'];
}The migration adding user_id / cancelled_at to orders and creating the audit table:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('orders', function (Blueprint $table) {
$table->foreignId('user_id')->nullable();
$table->timestamp('cancelled_at')->nullable();
});
Schema::create('order_events', function (Blueprint $table) {
$table->id();
$table->foreignId('order_id');
$table->string('type');
$table->foreignId('actor_id')->nullable(); // who did it
$table->timestamp('created_at')->nullable();
});
}
public function down(): void
{
Schema::dropIfExists('order_events');
Schema::table('orders', function (Blueprint $table) {
$table->dropColumn(['user_id', 'cancelled_at']);
});
}
};The tests' factory inserts payment columns (gateway_ref, amount_minor, currency) because the scratch app shares its orders table with this site's reconciliation example; trim the insert to your own schema. Scope: this is a bounded tutorial example - no refunds, inventory release or notifications, which a complete paid-order cancellation workflow would also need.
Small tasks: size the work to the review#
"Add order cancellation" is one task for a human with context and a bad task for an agent. Split until each diff fits in your head: (1) add the order_events table, (2) add the state guard with tests, (3) add the endpoint with ownership check, (4) wire notifications. Each PR is reviewable in minutes, and a wrong turn costs one small revert instead of an archaeology dig. If you can't describe the acceptance check for the task in one sentence, it's not small enough.
The PR review checklist for AI-written code#
Run this on every agent PR, in this order - the top items are the ones one-shot output misses most:
- Authorization: route middleware for authentication, an ownership/permission check for the resource - where exactly?
- State validity: which states is this operation legal from, decided on freshly locked state, not a stale read?
- Idempotency: what happens when this exact request arrives twice - sequentially and concurrently?
- Data integrity: transactions around multi-write paths; no float math near money.
- Error paths: what does the caller see on failure; is anything half-applied?
- Audit and observability: is the mutation recorded with actor and timestamp?
- Tests: do the new tests fail without the change? (Swap the change out, watch them go red - like the run above.)
- Scope: did the agent touch files outside the task? Instruction-file violations?
What not to delegate#
Some work stays human not because agents are incapable, but because the blast radius is asymmetric:
- Migrations against production data - especially backfills and column drops.
- Auth and permission policy changes - a wrong default here is a breach, not a bug.
- Secrets, infra and deploy configuration.
- Incident response decisions - the agent can gather context; a human takes the pager decision.
- The final merge - review is the control; automating it away removes the point of everything above.
Delegation at a glance#
| Task type | Verdict |
|---|---|
| Boilerplate CRUD, form requests, DTOs | Delegate freely, still run the checklist |
| Test generation for existing behavior | Delegate - and verify the tests actually fail when the behavior breaks |
| Bug fix with a failing test as the spec | Delegate with guardrails |
| Multi-file refactors | Split first, then delegate the pieces |
| Migrations on production data, auth policy, deploy config | Don't delegate |
| The merge button | Never |
Common mistakes#
| Mistake | What it costs |
|---|---|
| No instruction file, or a stale one | The agent invents conventions that fight your codebase |
| Reviewing AI diffs by vibe | The bug is always in the invariant nobody wrote down |
| Tasks sized "add the feature" | Unreviewable diffs; reverts take down neighboring work |
| Trusting generated tests | Tests that pass with the bug still present are worse than none |
| Checks outside a lock or transaction | Two concurrent requests both pass the check; the audit says it happened twice |
| Letting the agent expand scope | "While I was in there" edits hide in the diff |
Key takeaways#
Agents earn production access through scaffolding: an instruction file that states your invariants, a test suite that enforces them, tasks small enough to review, a checklist that catches what one-shot output misses, and a hard line around migrations, auth, and the merge button. The agent writes; you specify, guard, and accept.
References#
- AGENTS.md - the instruction-file convention (support varies by tool): https://agents.md
- The debugging loop these guardrails plug into: /en/blog/debugging-is-the-skill-ai-cant-do-for-you
- Idempotency keys in Laravel: /en/blog/idempotency-keys-laravel-stop-double-charges
- Coding with AI without the dependency: /en/blog/learn-to-code-with-ai-without-dependency
Want an agent-ready test harness and review process for your Laravel codebase? See /en/services.