Enterprise Coding Agents: Harness Discipline, pstack and Formal Verification (TDD, TLA+ & Lean 4)
How to build production software with coding agents and harness tools like Claude Code and Google Antigravity using risk-tiered TDD, TLA+ model checking, Lean 4 proofs and Lauren Tan's pstack architecture — replacing manual PR review bottlenecks while driving revert rates down as merge velocity climbs.
In 2024, AI coding tools acted like fast autocomplete inside an engineer’s editor. By late 2026, enterprise teams run fleets of coding agents across terminal harnesses, cloud sandboxes and background manager views — producing pull requests faster than any human reviewer can read line by line.
When throughput scales from tens of changes per week to thousands of patches per month, traditional software engineering habits collapse in opposite directions. Teams that keep manual line-by-line review create an impossible human queue; teams that blindly auto-merge agent output ship subtle concurrency bugs, silent regressions and architectural rot (“AI slop”).
The engineering discipline that resolves that paradox is not prompt tuning. It is replacing human eyeball review with harness engineering, structural constraints, independent verification swarms and risk-tiered formal verification (TDD, TLA+ and Lean 4).
Humans own the specification and structural constraints; agents own code generation, proof search and execution; deterministic checkers own the merge gate. If an error class can recur, encode the rule in linters, type boundaries, model checkers or theorem proofs — never in another paragraph of prose instructions.
1. Enterprise agent harnesses: Claude Code vs. Google Antigravity
As we outlined in Harness Engineering and Scaling Managed Agents, the foundation model (Claude Opus 5.5 / Fable 5.2, Gemini 4 Neon, GPT-6.2 Sol, Grok 4.7 or an open-weight model) is now decoupled from the agent harness — the execution runtime that supplies tools, sandboxes, context compaction, permission boundaries and verification loops.
Two harnesses anchor most enterprise coding stacks in late 2026: Claude Code and Google Antigravity.
| Architectural axis | Claude Code | Google Antigravity |
|---|---|---|
| Primary surface | Terminal-first CLI (claude), IDE extensions, web and headless CI runners |
Multi-surface: Antigravity IDE, agy CLI, background Manager view and Python SDK |
| Orchestration model | Linear parent session with dynamic subagent delegation (Agent tool) |
Built-in parallel manager designed to spawn, monitor and coordinate background subagents |
| Configuration & rules | CLAUDE.md, project/user .claude/skills/, lifecycle hooks (PreToolUse, PostToolUse) |
AGENTS.md, .agents/rules/, .agents/skills/, workflows and cross-harness plugin migration |
| Tool & boundary layer | Native MCP servers, scoped shell/file tools, custom deterministic CI/CLI hooks | Native MCP servers, isolated/branched workspaces (share, branch), credential isolation |
| Verification evidence | Command execution, test suites, git diffs and CI webhook gates | Terminal tests plus first-class browser DevTools verification, recordings and structured plan/diff artifacts |
| Model portability | Coupled primarily to Anthropic’s model family | Native Gemini execution with cross-model subagent routing across supported frontier and open-weight tiers |
Enterprise boundary controls around the harness
Whichever harness your teams adopt, production safety depends on the perimeter around the agent rather than trusting the model prompt:
- Disposable execution environments: Run agent tool calls inside ephemeral containers or isolated worktrees/branches (
branchorshareworkspaces) so a broken migration or runaway script never corrupts developer workstations or shared staging databases. - Zero-credential exposure: Keep database passwords, cloud deploy tokens and signing keys behind a proxy or short-lived OIDC / SSH CA broker (see Post-Quantum SSH and Git Infrastructure).
- Formal policy enforcement on live actions: For autonomous agents calling production APIs or internal tools, wrap tool execution in deterministic policy engines — such as AWS Cedar and Dogwood execution-trace policies — that mechanically block out-of-order steps, unapproved mutations or privilege escalations regardless of what the LLM emits.
- Graph-indexed context over blind grep: On large multi-module repositories, pair the harness with an AST + semantic dependency graph (
graphify query/graphify path/graphify explain) so agents inspect exact call boundaries before editing, avoiding whole-repo context bloat.
2. How Lauren Tan’s pstack eliminates human PR bottlenecks while revert rates drop
A common question from engineering leaders adopting coding agents is simple: if agents generate thousands of changes a month, how can anyone safely skip manual pull-request code reviews without breaking production?
The clearest empirical case study comes from Lauren Tan (@poteto, Principal Engineer on SpaceXSI’s Grok Bot team, formerly on the React Compiler core team and Cursor), presented in her November 2026 AI Engineer CODE keynote “All Code Is Slop (Except Mine)” and codified in her open-source agent framework pstack (/poteto-mode).
Her team reported shipping ~3,127 individual PRs in a single month and over 11,000 PRs per month across the team — including patches verified and merged autonomously overnight — while reducing their revert/rollback rate from ~0.98% down to ~0.47%.
That outcome looks paradoxical only if you equate “omitting human line-by-line PR review” with “omitting review.” In pstack, human line-by-line review is replaced by four rigid engineering systems that catch defects more consistently than tired humans skimming 400-line diffs.
TRADITIONAL HUMAN-REVIEW BOTTLENECK
───────────────────────────────────────────────────────────────────────────────
Agent writes PR ──► Prose rules (AGENTS.md) ──► Green unit CI ──► Human skims
often ignored under 400-line diff
long context (rubber-stamp
or 2-day queue)
PSTACK INVERTED-PYRAMID PIPELINE
───────────────────────────────────────────────────────────────────────────────
Codebase walls & Author agent Independent patch-id check +
banned APIs + ──► /deslop + ──► verifier swarm ──► contiguous merge
formal specs /no-comments + (never wrote the (or targeted
(prevent defects self-proof code; runs real rebase if trunk
before diff exists) UI/CLI surface) touched callers)
Mechanism 1: The Inverted Trust Pyramid (Encode Lessons in Structure)
When an agent makes a mistake, most teams append a sentence to AGENTS.md or CLAUDE.md. Over three months, the instruction file grows to thousands of tokens of prose rules that models quietly ignore whenever context fills up.
Tan inverts that pyramid. Trust is cheapest and strongest at the bottom, and weakest at the prose layer at the top:
| Trust layer | Enforcement mechanism | Example from production pstack workflows |
|---|---|---|
| 1. Codebase & architecture (strongest) | Directory walls, module boundaries, strict types | Separate Electron main and renderer trees with automated dependency-graph checks that reject cross-boundary imports at lint time |
| 2. Banned nuance & static analysis | Custom lint rules, compiler errors, zero escape hatches | Categorically banning error-prone APIs (such as raw useEffect in product UI code) outside vetted framework primitives, plus removing ~99% of code comments (/no-comments) so agents cannot lean on stale prose comments as excuses |
| 3. Verification & formal proof | Project-local verify-* harnesses, TLA+, Lean 4 |
Scripted drivers (control-ui, control-cli, Playwright/CDP, PTY harnesses) proving end-to-end runtime state plus formal invariants on critical subsystems |
| 4. Prose instructions (thinnest) | Concise skill playbooks for high-level judgment | Only rules that cannot yet be encoded in types, linters or tests |
The core rule in pstack’s principle-encode-lessons-in-structure is uncompromising: if you catch yourself correcting the same mistake twice, delete the prose explanation and encode a structural check (a lint rule, type constraint, metadata flag or CI test) that makes the bad code impossible to land.
Mechanism 2: Strict Separation of Author and Verifier (autopilot-full & shipping)
Even when humans do not read every line of a PR before merge, pstack never lets the agent that wrote the code approve its own work:
- The Owner builds and strips slop: A single owner agent implements the feature or fix on its branch, runs
/deslopand/no-commentsto strip redundant scaffolding and narrative comments, rebases onto trunk, and runs local self-proof. - Green CI is not a merge verdict: Unit tests and compilation alone prove only that mocked checks passed — not that the application actually works for a user.
- An independent verifier swarm proves live behaviour: At the code-ready commit SHA,
pstackfans out an independent verifier swarm (agents that never wrote a line of the patch). They re-run gates, drive the live surface via project-local verification skills (verify-<app>) through browser CDP or CLI/PTY harnesses (principle-prove-it-works), audit side effects (files written, database rows, git refs) and postPASS,PASS+NOTESorFAIL.
Mechanism 3: git patch-id Verdict Survival & Small Verifiable Units
Why does the revert rate fall from 0.98% to 0.47% even as commit rate climbs?
- Smaller atomic units (
principle-sequence-verifiable-units): Agents do not open 3,000-line mega-PRs. Work is broken into small, single-purpose diffs that end in an automated check. Smaller diffs collide less on rebase, expose smaller blast radii and make any needed revert instantaneous and isolated. - Content-addressed verdict tracking (
git patch-id): On a fast-moving trunk with thousands of merges per month, rebasing a branch changes its commit SHA even when the patch is identical. Instead of blindly trusting stale CI or rebasing forever,pstack’sshippingplaybook comparesgit patch-idbetween the verified SHA and the rebased head, and checks what trunk modified in the meantime:- If trunk touched a file both sides edited, a caller of the patch, a dependency the patch calls, or CI check definitions, a fresh verification run is mandatory.
- If only a lockfile changed on both sides, a frozen install on the merge result verifies dependency resolution directly.
- Contiguous verified runs land bottom-up, one verified unit at a time.
- No silent gate weakening: Any change that loosens a lint rule, raises a threshold or adds a policy allowlist requires both an independent verifier proof and an explicit root countersign.
Mechanism 4: Diverse Multi-Model Routing & Adversarial Review
Through /setup-pstack, roles are split across model families by strength and cost: fast high-throughput coding models execute well-scoped changes and verifier swarm checks, while top-reasoning models (interrogate, arena, reflect) challenge contested designs, compare competing prototypes and audit architectural changes with an auditable decision trail (show-me-your-work).
Enterprise governance caveat: where humans stay in the loop
Removing human line-by-line review on routine, verified changes does not mean removing human authority. Notice that pstack itself enforces an explicit “Always pause” boundary for irreversible writes: force-pushes to shared branches, production deploys, destructive data migrations and customer-facing communications. In regulated enterprises (financial ledgers, healthcare pipelines, university identity systems), formal segregation-of-duties rules still keep human sign-off on specification acceptance, threshold changes, security-policy edits and production promotion — while delegating diff verification to the deterministic + verifier-swarm pipeline.
3. Risk-Tiered Formal Verification Matrix (TDD + TLA+ + Lean 4)
Formal methods historically failed in enterprise software because teams treated them as all-or-nothing: trying to mathematically prove an entire web dashboard crashes velocity immediately. With coding agents, the cost of drafting specifications and proof scripts drops dramatically — provided you apply risk-tiered verification proportionally.
| Risk tier | Scope of change | Required verification stack | Why standard tests aren’t enough |
|---|---|---|---|
| Tier 0 | Ordinary CRUD, UI styling, copy, logging, simple wiring | Classic Red → Green → Refactor TDD + contract checks + live surface drive (verify-*) |
Behaviour is local and deterministic; formal state exploration adds zero value |
| Tier 1 | State machines, async actors, queues, retries & idempotency, distributed sagas, leases/epochs, auth/kill-switch lifecycles | TLA+ (TypeOK, Init, adversarial Next, SafetyInv) checked via TLC / Apalache + Counterexample → Red Test loop |
Unit tests check happy paths and miss rare multi-actor interleavings, timeouts and stale-epoch races |
| Tier 2 | Financial/fixed-point arithmetic, overflow/rounding bounds, quotas, parsers/codecs, policy engines (e.g., AWS Cedar) | Lean 4 machine-checked proof (Init/Std) + escape-hatch audit + #print axioms + differential property tests |
Example tests miss extreme boundaries (0, MIN, MAX, rounding half-points, sign-flip thresholds) across universal inputs |
| Tier 3 | Concurrent stateful protocols coupled with quantitative or algebraic invariants (e.g., distributed settlement ledgers) | TLA+ + Lean 4 + Differential / Property TDD | Both concurrency interleavings and arithmetic conservation laws must hold simultaneously |
4. Practical TLA+ & Lean 4 Agent Workflows
A. TLA+ for Tier 1 concurrency & crash recovery
When an agent implements a distributed lock, lease, retry queue or saga, ask a Spec Author subagent to draft the bounded TLA+ model before production code is written. Crucially, Next must model adversarial failure transitions — crashes, stale retries, duplicate messages and lease expirations — rather than only the happy path.
--------------------------- MODULE IdempotentLease ---------------------------
EXTENDS Naturals, FiniteSets
CONSTANTS Workers, MaxEpoch
VARIABLES holder, epoch, committed, log
vars == <<holder, epoch, committed, log>>
TypeOK ==
/\ holder \in Workers \cup {"NONE"}
/\ epoch \in 0..MaxEpoch
/\ committed \in SUBSET (Workers \X (1..MaxEpoch))
/\ log \in SUBSET (Workers \X (1..MaxEpoch))
Init ==
/\ holder = "NONE"
/\ epoch = 0
/\ committed = {}
/\ log = {}
Acquire(w) ==
/\ epoch < MaxEpoch
/\ holder' = w
/\ epoch' = epoch + 1
/\ UNCHANGED <<committed, log>>
Commit(w, e) ==
/\ holder = w
/\ epoch = e
/\ committed' = committed \cup {<<w, e>>}
/\ log' = log \cup {<<w, e>>}
/\ UNCHANGED <<holder, epoch>>
CrashOrExpire ==
/\ holder # "NONE"
/\ holder' = "NONE"
/\ UNCHANGED <<epoch, committed, log>>
StaleRetry(w, e) ==
/\ e < epoch
/\ UNCHANGED vars
Done ==
/\ epoch = MaxEpoch
/\ holder = "NONE"
/\ UNCHANGED vars
Next ==
\/ \E w \in Workers : Acquire(w)
\/ \E w \in Workers, e \in 1..MaxEpoch : Commit(w, e)
\/ CrashOrExpire
\/ \E w \in Workers, e \in 1..MaxEpoch : StaleRetry(w, e)
\/ Done
Spec == Init /\ [][Next]_vars
\* Declarative safety invariant: stated independently of how Next is coded
SingleCommitPerEpoch ==
\A a, b \in committed : (a[2] = b[2]) => (a[1] = b[1])
=============================================================================
Run TLC exhaustively over a bounded constant set (Workers = {w1, w2}, MaxEpoch = 2):
tlc -workers auto -config formal/tla/IdempotentLease.cfg formal/tla/IdempotentLease.tla
Whenever TLC uncovers an invariant breach, it prints a minimal trace (State 1 -> State 2 -> ... -> State N). Under the Counterexample → Red Test loop:
- Preserve the exact TLC trace.
- Translate that sequence of concurrent events directly into a deterministic failing Red regression test against the production codebase before changing production logic.
- Fix the protocol in production code (never weaken
SafetyInvto accommodate a bug). - Re-run both TLC (confirming
> 1distinct states explored andNo error has been found) and the regression test until green.
B. Lean 4 for Tier 2 arithmetic, codecs & policy invariants
For universal properties (overflow freedom, conservation of value, rounding bounds, parser round-trips), Lean 4 checks every possible input through a small, independent type-checking kernel. Even if the LLM hallucinates a clever-looking proof step, Lean’s kernel rejects it immediately.
Keep enterprise verification modules in zero-Mathlib pure Lean 4 (Init/Std using Nat, Int, BitVec and core tactics like omega, decide and simp) so lake build finishes in seconds inside CI without multi-gigabyte dependencies:
structure LedgerState where
available : Nat
reserved : Nat
deriving Repr, DecidableEq
def reserve (s : LedgerState) (amount : Nat) : Option LedgerState :=
if amount <= s.available then
some { available := s.available - amount, reserved := s.reserved + amount }
else
none
theorem reserve_conserves_total (s s' : LedgerState) (amount : Nat)
(h : reserve s amount = some s') :
s'.available + s'.reserved = s.available + s.reserved := by
unfold reserve at h
split at h
· cases h
simp only []
omega
· cases h
#print axioms reserve_conserves_total
Zero-escape-hatch audit: Agents pressured to “make CI green” will occasionally cheat with sorry, admit, custom axiom declarations, unsafe, @[implemented_by ...], or compiler-trusting tactics (native_decide). Every Lean CI check must run a static audit rejecting all escape hatches and verify that #print axioms <TheoremName> depends solely on standard foundational axioms (propext, Classical.choice, Quot.sound) — or reports does not depend on any axioms.
C. Closing the Spec-to-Code Gap
A passing TLC run proves the abstract protocol, and a passing Lean proof proves the Lean model — not your TypeScript, Python, Go or Rust implementation — until three bridges connect them:
- Refinement Mapping Table: Require every Tier 1–3 PR to record a 1-to-1 table mapping every TLA+ variable/action/invariant or Lean
def/theoremto its exactfile:symbolin production code. - Differential & Property-Based Test Bridge: Just as AWS reconciles Lean 4 models of the Cedar authorization engine against its production Rust evaluator, export golden boundary vectors from Lean (
#eval) and mirrorSafetyInvpredicates inside property-based test runners (fast-check,hypothesis,proptest) driving the real production functions. - Negative Controls: Deliberately mutate one guard or invariant in a temporary check to confirm TLC yields a counterexample, Lean fails to compile, or the bridged property test turns red — proving the verification suite is non-vacuous (not silently passing on
Inv == TRUEorNext == FALSE).
5. Independent Multi-Agent Pipeline & Fail-Closed CI Merge Gate
Never allow a single agent context to write the specification, write the implementation, write the tests and certify the result. Mirror pstack and formal TDD separation across three distinct agent roles:
Requirements / Ticket
│
▼
┌─────────────────────────────────────────┐
│ 1. Spec & Proof Author Agent │ Classifies Tier 0–3; writes TLA+ spec,
│ (Cannot edit production code) │ Lean 4 theorems & failing Red tests
└──────────────────┬──────────────────────┘
│ Red tests + checked spec
▼
┌─────────────────────────────────────────┐
│ 2. Implementation Agent │ Writes minimal production code +
│ (Cannot weaken tests or specs) │ Refinement Mapping Table; runs /deslop
└──────────────────┬──────────────────────┘
│ Code-ready SHA
▼
┌─────────────────────────────────────────┐
│ 3. Independent Verifier Swarm │ Runs formal audits, property bridges,
│ (Never wrote implementation code) │ negative controls & live verify-* checks
└──────────────────┬──────────────────────┘
│ PASS verdict + receipts
▼
Fail-Closed CI Merge Gate
Encode the merge gate so it fails closed whenever any checker is missing, skipped or soft-failed:
# .github/workflows/enterprise-agent-gate.yml
name: Fail-Closed Agent Verification Gate
on:
pull_request:
merge_group:
jobs:
structural-and-unit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci --ignore-scripts
- run: npm run lint:architecture # Folder boundaries & banned-API rules
- run: npm run check # Strict type-checking (zero warnings)
- run: npm test # Unit + property-based differential bridge
formal-verification:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Preflight formal toolchains (fail closed if missing)
run: ./scripts/check-formal-tools.sh --require tla --require lean
- name: Audit TLA+ configs for vacuity and deadlocks
run: ./scripts/check-formal-tools.sh --audit-tla formal/tla/
- name: Run TLC exhaustive model checks
run: tlc -workers auto -config formal/tla/IdempotentLease.cfg formal/tla/IdempotentLease.tla
- name: Build Lean 4 proofs and reject escape hatches
run: |
(cd formal/lean && lake build)
./scripts/check-formal-tools.sh --audit-lean formal/lean/
6. 30/60/90-Day Enterprise Adoption Playbook & Common Pitfalls
Phased rollout
- Days 1–30 (Structural hygiene & local verification): Replace prose bloat in
AGENTS.md/CLAUDE.mdwith strict TypeScript/mypy/Clippy settings, import-boundary lint rules and banned-API lint rules. Build one project-localverify-<app>skill that drives your primary user surface end to end in a clean sandbox. - Days 31–60 (Author/verifier split & Tier 0–1 gates): Enforce separate spec/implementation/verifier roles in Claude Code or Google Antigravity (
autopilot-fullpattern). Introduce TLA+ specs for your top 2–3 highest-churn state machines (auth/session lifecycles, payment/job retries, distributed locks) and wire TLC into CI. - Days 61–90 (Tier 2 Lean 4 proofs & autonomous merge queues): Formalize billing, quota, permission and parser invariants in fast zero-Mathlib Lean 4 bridged via differential property tests. Enable automated
git patch-id-aware merge queues for Tier 0–1 verified patches while preserving explicit human gates on production deploys and policy changes.
Pitfalls that silently break agent verification
| Failure mode | How it happens | Structural fix |
|---|---|---|
| Prose-rule bloat | Teams write 800-line AGENTS.md files instead of linters; agents ignore half of them under long context |
Move every repeat correction into AST lint rules, dependency walls and CI checks |
| Test-tailored weakening | An implementation agent edits an assertion or loosens SafetyInv to turn CI green |
Separate author and verifier agents; enforce code-owner protection on formal/ and test directories |
| Vacuous formal specs | Spec passes TLC with Inv == TRUE, Next == FALSE or CHECK_DEADLOCK FALSE, or Lean uses sorry/native_decide |
Run static --audit-tla / --audit-lean, assert distinct states > 1, inspect #print axioms and require negative controls |
| Stale verdicts after trunk rebase | A PR passes verification on Tuesday, rebases onto breaking trunk changes on Wednesday, and merges un-retested | Check git patch-id and re-run verification whenever trunk modified callers, dependencies, shared files or CI definitions |
| Mock-only test confidence | Unit tests mock out every database, queue and browser boundary; integration collapses in production | Require a live verification lane (verify-*) exercising real runtime behaviour before issuing PASS |
Related engineering notes: Harness Engineering: Evaluation-Driven Testbeds for Frontier AI Agents, Scaling Managed Agents: Brains, Hands and Sessions, and Air-Gapped Local AI Inference: Hardware Economics, Open Models and Zero-Egress Architecture.
Building an AI agent or assistant?
We design agent architectures, evaluation harnesses and secure tool access for universities, NGOs and SMEs — model-agnostic across Claude, Gemini, GPT, Grok and open-weight models, hosted where your data policy requires.