Skip to main content
Logo image
Apptastic Coder
DevOps

Setting Up Automated AI Code & Design Reviews in GitHub Actions

Implement the Elephant-Goldfish Model and Spec-Driven Development with Automated PR Checks Against spec.md

Save & share
On this page7 sections

Full Article

Read the complete article, including examples, background, practical insights, and technical details.

Automated AI Code and Design Review in GitHub Actions

When a coding agent designs a feature and reviews its own pull request in the same session, it often misses the exact assumptions it made earlier. That’s the core insight behind the Elephant-Goldfish Model and Spec-Driven Development (SDD) in CI/CD:

  • Elephant (your local session): Keep full project context while you and your agent draft a clear spec.md.
  • Goldfish (your CI/CD PR check): Strip all conversational history. Give an automated reviewer only spec.md and the PR diff so it can spot ambiguity, hidden assumptions, and design drift with fresh eyes.

In this tutorial, you’ll set up a working GitHub Actions workflow that checks every pull request against spec.md and posts a structured design & code review directly on the PR.


What You’ll Build

By the end of this guide, your repository will have:

.
├── .github/
│   └── workflows/
│       └── ai-design-review.yml
├── scripts/
│   └── goldfish_review.py
└── spec.md

Every time a pull request is opened or updated:

  1. A deterministic check verifies spec.md exists and contains required sections.
  2. goldfish_review.py sends spec.md + the git diff to an LLM in a zero-history request.
  3. GitHub Actions posts the structured findings as a PR comment.

Step 1: Create a Standalone spec.md

A Goldfish reviewer can only verify what is written down. Create a spec.md in your repository root with explicit boundaries, testable acceptance criteria, and a short decision record:

# Feature Specification: Outbound Webhooks

## Goal
Deliver signed HTTP POST webhook events when an order status changes.

## Constraints & Non-Goals
- Email notifications are out of scope for this feature.
- Maximum 5 delivery retries with exponential backoff (cap: 1 hour).
- Payloads must be signed with `X-Signature-256` using HMAC-SHA256.

## Acceptance Criteria
- [ ] Every webhook event has a stable `event_id` (UUIDv4) for idempotency.
- [ ] Failed deliveries after 5 attempts are marked `dead_letter` and logged.
- [ ] Webhook secrets can be rotated without dropping in-flight events.

## Decision Record
- **Bounded retries (5 attempts):** Chosen over unlimited retries to prevent queue backlogs during multi-day outages.

Tip: Avoid vague adjectives like "secure" or "scalable." Write observable behavior—such as "HMAC-SHA256 signed" or "max 5 retries"—so both tests and the AI reviewer have something concrete to verify.


Step 2: Write the Fresh-Context Reviewer (scripts/goldfish_review.py)

This script reads spec.md and pr.diff, enforces the Goldfish rule (no chat history), and asks the model for specific, evidence-backed findings rather than generic praise.

Create scripts/goldfish_review.py:

import os
import sys
from pathlib import Path
from openai import OpenAI

SPEC_PATH = Path("spec.md")
DIFF_PATH = Path("pr.diff")

SYSTEM_PROMPT = """You are an independent 'Goldfish' design and code reviewer.
You have NO prior conversation history with the author.
Compare the pull request diff strictly against spec.md.

Report ONLY concrete findings under these headings:
1. **Design Drift**: Code behavior that contradicts or omits a requirement in spec.md.
2. **Unstated Assumptions**: Hidden constraints in the diff not documented in spec.md.
3. **Missing Edge Cases / Tests**: Acceptance criteria lacking verification in the diff.

For every finding, include:
- **File / Area**
- **Evidence** (quote the spec line or diff hunk)
- **Consequence** (what breaks or drifts if merged as-is)

If the diff aligns cleanly with spec.md, reply with: "No design drift or spec gaps found."
Keep the review concise and actionable."""


def main() -> int:
    if not SPEC_PATH.exists():
        print("ERROR: spec.md is missing. Every feature PR must include or reference spec.md.", file=sys.stderr)
        return 1

    spec_text = SPEC_PATH.read_text(encoding="utf-8")
    for required in ("## Goal", "## Acceptance Criteria"):
        if required not in spec_text:
            print(f"ERROR: spec.md is missing required section: {required}", file=sys.stderr)
            return 1

    diff_text = DIFF_PATH.read_text(encoding="utf-8") if DIFF_PATH.exists() else ""
    if not diff_text.strip():
        print("No code diff to review.")
        return 0

    # Truncate huge diffs to stay within token budgets
    max_chars = 40_000
    if len(diff_text) > max_chars:
        diff_text = diff_text[:max_chars] + "\n\n... [diff truncated for review] ..."

    client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
    response = client.responses.create(
        model=os.getenv("REVIEW_MODEL", "gpt-4o-mini"),
        input=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {
                "role": "user",
                "content": f"## spec.md\n\n{spec_text}\n\n## Pull Request Diff\n\n```diff\n{diff_text}\n```",
            },
        ],
    )

    review_md = response.output_text.strip()
    Path("review_comment.md").write_text(
        f"### Goldfish AI Design & Spec Review\n\n{review_md}\n",
        encoding="utf-8",
    )
    print("Review generated successfully.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Why this structure works

  • Deterministic pre-check: Missing spec.md or missing ## Acceptance Criteria fails fast in Python before spending a single API token.
  • Zero-history isolation: Each run sends a single stateless request—no leftover assumptions from how the code was written.
  • Model flexibility: Override REVIEW_MODEL via environment variables (or swap the client for Anthropic/Gemini/LiteLLM).

Step 3: Add the GitHub Actions Workflow

Create .github/workflows/ai-design-review.yml:

name: AI Design & Spec Review

on:
  pull_request:
    types: [opened, synchronize, reopened]

permissions:
  contents: read
  pull-requests: write

jobs:
  goldfish-review:
    runs-on: ubuntu-latest
    # Skip forks that don't have access to repository secrets
    if: github.event.pull_request.head.repo.full_name == github.repository

    steps:
      - name: Checkout PR branch
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Generate PR diff
        run: |
          git diff origin/${{ github.base_ref }}...HEAD > pr.diff

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.11"

      - name: Install reviewer dependencies
        run: pip install openai

      - name: Run Goldfish spec review
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
          REVIEW_MODEL: gpt-4o-mini
        run: python scripts/goldfish_review.py

      - name: Post review comment on PR
        if: hashFiles('review_comment.md') != ''
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          gh pr comment "${{ github.event.pull_request.number }}" \
            --body-file review_comment.md

Step 4: Configure Secrets and Test It

  1. In your GitHub repository, go to Settings → Secrets and variables → Actions.
  2. Add a new repository secret named OPENAI_API_KEY.
  3. Create a feature branch, modify spec.md or a source file, and open a pull request.
  4. Watch the AI Design & Spec Review check run in the Actions tab and post its findings as a PR comment.

Step 5: Safe Rollout Tips

  • Start advisory, not blocking: Keep the AI review as an informational PR comment while your deterministic checks (schema validation, unit tests, linters) act as the required merge gates.
  • Avoid fork secret leaks: Keep the if: github.event.pull_request.head.repo.full_name == github.repository guard so external forks cannot trigger jobs with your API key.
  • Update spec.md and code together: When the Goldfish reviewer catches intentional scope changes, update spec.md in the same PR so future coding agents don’t build on stale documentation.

Want to dive deeper into the philosophy behind this workflow? Read Elephant-Goldfish Model: Why Coding Agents Need Independent Design Review and How to Build Spec-Driven Development (SDD) Workflows into CI/CD Using AI Reviewers.

Published
Share this article

Comments load as you scroll…