# Stop Letting AI Agents Approve Their Own Code: Two-Repo Split, Cross-Model Review, and a $40 Cloud Test VM

> Source: <https://dev.to/_088d9c6b7211315f6e47be/stop-letting-ai-agents-approve-their-own-code-two-repo-split-cross-model-review-and-a-40-cloud-2g36>
> Published: 2026-11-24 09:38:31+00:00

**Recommendation:** Give each parallel coding agent its own git worktree and a separate verifier model, and reject any run whose result.json is missing, stale, or fails a SHA-256 config hash check even if the process exited 0.
More in the playbook "Working with AI coding agents": <https://wpnews.pro/playbooks/coding-agents>

I run up to 4 AI coding agents in parallel on a 16 GB MacBook. Whenever two of them launched full `pytest` runs at the same time, macOS hit swap immediately and froze. Worse, when I let the same agent edit code, run tests, and report success, it sometimes relaxed assertions to make a failing test pass or returned an `exit 0` from stale artifacts left in a shared directory.

Telling an LLM in a prompt to "be careful" or "don't touch unrelated files" stops working once the context window fills up. I replaced prompt-based discipline with hard repository boundaries, cross-model code review, and a shared cloud test runner. This setup currently backs my personal quantitative research codebase with nearly 7,000 tests, and every piece of it works just as well for any Python or backend project.

When all my code lived in one repository, an agent fixing a data loader bug could casually edit the task scheduler or read out-of-sample validation data from an exploratory script. No amount of Markdown instructions stopped that reliably.

I split the system into two separate Git repositories:

`task_manager`)` quantation_factor_database`)` tools.agent_harness.cli`) and has zero scheduling privileges.
| Approach | Risk of Cross-Module Edits | Concurrent Merge Conflicts | Trade-Off You Accept | 
|---|---|---|---|
| Single repo + prompt rules | High after long sessions | High | Constant manual cleanup | 
| Monorepo with folder rules | Medium (direct imports still work) | Medium | Painful to split out public code later | 
| **Two separate Git repos** | **Low (process and repo boundary)** | **Low (independent test suites)** | **Must maintain a strict CLI and JSON contract** | 

Splitting into two repos does add overhead. Every cross-repo change requires updating the CLI flags and JSON schema on both sides, and we use Copybara to export allowlisted parts of the execution repo to our public open-source project [`GSX-Eis/jq-factor-lab`](https://github.com/GSX-Eis/jq-factor-lab). In return, an agent working on computation can never touch scheduling rules.

Letting one model write a patch and verify it is an easy way to get false positives. A single model has blind spots around its own assumptions, and when a test fails, it often tries to work around the failure by loosening an assertion or returning a default value so the process exits with `0`.

I also ran into silent cache bugs where a script exited `0` after writing an empty file, or a wrapper read an old report left behind in a shared output folder.

To stop both failure modes, I split work across four steps and different model families:

`worktree`, so 4 agents never overwrite each other's files.`--no-ff` in a temporary When human planning docs and code disagree, agents often copy stale commands from an outdated README. I added a strict precedence rule in `AGENTS.md` at the repo root:

`CLI --help` output (highest authority)`schemas/`)` README.md`
`.planning/`, background only, never copy commands from here)
Our CLI wrapper separates "the subprocess didn't crash" from "the output is valid." Every invocation gets a fresh `execution_id`, writes to `attempts/<execution_id>/result.json`, and checks the SHA-256 hash of the source config. If the file is missing or the hash doesn't match, the wrapper blocks the run with exit code `4` even if the child process returned `0`:

```
EXIT_SUCCESS = 0       # Process exited 0 and schema + SHA-256 checks passed
EXIT_PRECONDITION = 2  # Missing config or boundary violation before start
EXIT_EXECUTION = 3     # Subprocess crashed, timed out, or killed by signal
EXIT_QUALITY_GATE = 4  # Subprocess returned 0, but output is missing or tampered

def verify_bound_result(result_path: Path, expected_run_id: str, config_sha256: str) -> dict:
    # Read only from this invocation's execution_id folder to avoid stale artifacts
    payload = read_json_strict(result_path)
    if payload.get("run_id") != expected_run_id:
        raise ContractGateError("run_id mismatch: refusing stale artifact", code=EXIT_QUALITY_GATE)
    if payload.get("source_config_sha256") != config_sha256:
        raise ContractGateError("config hash mismatch: evidence tampered", code=EXIT_QUALITY_GATE)
    return payload
```

Once the execution repo grew to **418 test files across 12 shards** (nearly 7,000 tests), running suites locally on a 16 GB MacBook became unusable. I banned local `pytest` runs completely and moved all unit, shard, and full regression runs to a single **GCP Spot VM (`8 vCPU / 32 GiB RAM / 100 GB disk`)** with a hard **$40/month** budget.

Sharing one Spot VM behind a lock queue means only one full regression runs at a time, and concurrent worktrees either wait or exit with code `75` to retry. In exchange, the environment stays identical and cheap.

Before syncing code, the local runner acquires `quantation-gcp.lock` across worktrees. On the VM, every run goes through `/usr/local/bin/cloud-test-lease-run.sh` (a kernel `flock` lease) and locks numerical libraries to a single thread so 6 `pytest-xdist` workers don't oversubscribe 8 vCPUs:

```
REMOTE_THREAD_ENV = {
    "OPENBLAS_NUM_THREADS": "1",
    "OMP_NUM_THREADS": "1",
    "VECLIB_MAXIMUM_THREADS": "1",
    "MKL_NUM_THREADS": "1",
    "NUMBA_NUM_THREADS": "1",
}

def build_leased_remote_cmd(lease_cmd: str, lease_id: str, target_cmd: str) -> str:
    # Keep fd 8 open for stdin (such as rsync filter rules) when the lease wrapper backgrounds
    restore_stdin = "exec \"$@\" <&8"
    return f"exec 8<&0; exec {lease_cmd} {lease_id} -- sh -c '{restore_stdin}' sh {target_cmd}"
```

`quant-idle.timer` checks active leases and SSH sessions every 5 minutes and powers off the VM after 20 minutes of idle time (agents are forbidden from running manual shutdown commands). Twice, a merge run hit SSH timeouts because the VM happened to be shutting down right as the job started. We fixed this in `CloudRunner` by checking instance state first and calling `gcloud compute instances start` when the VM is `TERMINATED`.` xdist` workers crashing Numba on `dcor`
Humans leave fallback code around for backwards compatibility, but fallback paths give AI agents extra ways to fail. When SQLite and DuckDB coexisted in our repo, agents occasionally wrote results to the wrong backend inside an exception handler.

I removed SQLAlchemy, SQLite loaders, and automatic `auto` backend detection completely, leaving **DuckDB + Parquet** as the only storage path, guarded by static contract tests that fail if anyone re-imports old database drivers.

On the scheduling side, `quality_gate.sh` runs a 10-step check before every merge, including Ruff, type checks, package boundary linting, and an isolated contract check in a temporary directory:

```
# Hard gate: verify package boundaries and run contract checks in an isolated temp dir
"$python_bin" -m task_manager.tools.arch_linter --boundary --json || GATE_FAILED=1

"$python_bin" - <<'PY'
import sqlite3
from pathlib import Path
from tempfile import TemporaryDirectory

# Test schema contracts in an OS temp dir so we never touch the live workspace state/
with TemporaryDirectory(prefix="contract_gate_") as tmp_dir:
    root = Path(tmp_dir).resolve()
    init_schema(sqlite3.connect(root / "state.db"))
    raise SystemExit(run_cli(["--task-root", str(root), "--json", "check", "contracts"]))
PY
```

Here's where both repositories stand on our latest verified runs:

`--changed --fast` runs finish in 1 to 2 minutes.`quality_gate.sh`)
| Failure Mode | Prompt-Only Fix (Fails) | Engineering Constraint (Works) | Cost You Pay | 
|---|---|---|---|
| Agents edit unrelated core modules | "Don't touch other files" | Two separate repos + `arch_linter` | Must maintain CLI/JSON contract | 
| Same model loosens test assertions | "Check edge cases carefully" | Separate author and reviewer models | Extra review turn and tokens | 
| `exit 0` returned from empty/stale files | Trust process exit code | Fresh `execution_id` dir + config SHA-256 | Extra schema check in wrapper | 
| Concurrent `pytest` freezes 16GB Mac | Ask agents to run sequentially | Ban local `pytest` , route to Spot VM | Must maintain `rsync` filter rules | 
| Worktrees overwrite remote workspace | Coordinate manually in chat | Local lock + remote `flock` lease | One heavy suite runs at a time | 
| Agents pick stale docs or wrong DB | Patch the prompt repeatedly | Strict doc order + delete SQLite path | Must clean up legacy fallbacks | 

Two limitations remain open. First, as I spin up more concurrent branches, queue wait times on a single 8-vCPU Spot VM may become a bottleneck. Second, both repos still carry pre-existing test failures (43 in control, 32 in execution) that we gate on "zero new failures" while paying down the backlog.

When you run multiple AI coding agents in parallel, what breaks first in your workflow: stale context, tests passing on weak assertions, or agents stepping on each other's environments?

*Disclosure: I built and run this system myself, verified every command, exit code, and test count against the actual repositories, and used AI tools to help draft and tighten the English prose.*
