Enforce Code Standards on AI-Generated Pull Requests with AST Rules

Your team just integrated an LLM-powered coding assistant into your developer workflow. Within forty-eight hours, pull requests swell with pristine-looking TypeScript components, meticulously commented Python utilities, and elegantly structured Go services.

Then the CI pipeline explodes.

The AI-generated code violates three distinct organizational conventions you established six months ago. It uses console.log instead of your structured Pino logger, introduces raw SQL queries that bypass the repository layer, and implements custom error classes instead of extending your domain-specific base exception. Worse, the code passes code review because it looks clean, well-formatted, and superficially correct.

Traditional linters and static analyzers catch syntax errors, missing semicolons, and unused imports. But they are blind to architectural intent. They don't know that your project mandates result-type error handling over try-catch blocks in business logic, or that your domain models must remain entirely decoupled from HTTP framework decorators.

To bridge this gap, you need a dedicated code review pipeline that checks AI-generated code against project conventions before a human reviewer ever opens the PR.


📋 Table of Contents


The Illusion of Clean AI Code

When developers talk about AI-generated code quality, they usually focus on correctness: Does the function sort the array? Does the SQL query return the correct join?

But engineering velocity isn't just about writing code that compiles; it's about writing code that fits.

When an engineer uses GitHub Copilot, Cursor, or an internal LLM microservice to scaffold a feature, the model draws upon its training data—a vast, chaotic ocean of public repositories with conflicting paradigms, deprecated patterns, and inconsistent architectural styles. Left unchecked, AI tools act as architectural entropy multipliers. They introduce twenty different ways to handle async operations into a codebase that spent two years standardizing on one.

[ AI Code Generation ] ──> [ Standard Linter ] ──> [ Passes! (Syntax OK) ]
                                │
                                ▼
                     [ Architectural Reality ]
                     • Wrong logger imported
                     • Bypassed repository layer
                     • Custom exception used
                                │
                                ▼
                     [ Production Technical Debt ]

Relying on human code reviewers to catch these stylistic and architectural drifts is an expensive failure mode. Human reviewers get tired, miss subtle rule violations, and burn valuable mental energy arguing about repository patterns instead of system design.

Building an automated code review pipeline specifically targeted at AI-generated code convention adherence transforms your review process from an exhaustive stylistic audit into a high-level architectural discussion. Let's look at how to build that pipeline from the ground up.


1. The AST Pattern Enforcer: Moving Beyond Regular Expressions

Scenario:

Your team mandates that all database interactions must pass through the repository layer using your custom db client wrapper. An AI assistant generates a React Server Component or Express route handler that imports pg directly and executes raw SQL queries inline.

Why it matters:

Standard regex-based linters (grep-style rules) fail instantly here. A developer or an AI can easily obfuscate the forbidden import with aliasing (import { Pool as PGPool } from 'pg') or dynamic requires, completely evading simple string matching.

Solution:

Parse the AI-generated code into an Abstract Syntax Tree (AST) using parser tools like @typescript-eslint/parser, Babel, or Tree-sitter, and write programmatic visitors that inspect node relationships rather than raw characters.

Code:

Here is a custom ESLint rule written in TypeScript that detects direct usage of database drivers outside the designated repository directory:

import { ESLintUtils } from '@typescript-eslint/utils';
import * as path from 'path';

const createRule = ESLintUtils.RuleCreator(
  (name) => `https://internal.docs.corp/rules/${name}`
);

export const noDirectDatabaseAccess = createRule({
  create(context) {
    const filename = context.filename;
    // Allow files inside the repository directory
    if (filename.includes(path.normalize('/src/repositories/'))) {
      return {};
    }

    return {
      ImportDeclaration(node) {
        const sourceValue = node.source.value;
        if (sourceValue === 'pg' || sourceValue === 'mongoose' || sourceValue === 'prisma') {
          context.report({
            node,
            message: `Direct database import '${sourceValue}' is prohibited outside the repository layer. Use src/repositories/ instead.`,
          });
        }
      },
    };
  },
  name: 'no-direct-database-access',
  meta: {
    type: 'problem',
    docs: {
      description: 'Disallow direct DB client imports outside repository files.',
    },
    schema: [],
    messages: {
      unexpected: 'Direct database access forbidden here.',
    },
  },
  defaultOptions: [],
});

Why this works:

By operating on the AST node level, the rule inspects semantic structure rather than text. It doesn't matter how the import is formatted, aliased, or spaced—the parser normalizes the code into a syntax tree where import sources are explicitly identifiable.

💡 Practical note: Always normalize file paths when checking directory constraints in custom linters, as Windows path separators (\) will silently break string inclusion checks on Linux-based CI runners.


2. Custom Semantic Linters with Tree-sitter and Custom Rules

Scenario:

Your polyglot microservice architecture includes services written in Python, Go, and TypeScript. You need a unified way to enforce that AI-generated service handlers never instantiate logging objects locally, but instead use the request-scoped logger injected into context.

Why it matters:

Maintaining separate custom linter plugins across three different language ecosystems (ESLint for TS, Ruff/Flake8 for Python, golangci-lint custom linters for Go) creates massive maintenance overhead for your platform engineering team.

Solution:

Leverage Tree-sitter, an incremental parsing library built for language tooling, combined with lightweight query scripts to enforce structural invariants across multiple programming languages using a unified query syntax.

Code:

The following Tree-sitter query in Python targets prohibited local logger instantiations in Python services:

import tree_sitter_python as tspython
from tree_sitter import Language, Parser

PY_LANGUAGE = Language(tspython.language())
parser = Parser(PY_LANGUAGE)

tree = parser.parse(b"""
import logging
def handle_request(event):
    logger = logging.getLogger("my_module")
    logger.info("Processing request")
""")

# Tree-sitter query to find local logging instantiation
query_str = """
(assignment
  left: (identifier) @var_name
  right: (call
    function: (attribute
      object: (identifier) @mod_name
      attribute: (identifier) @func_name
    )
  ) (#eq? @mod_name "logging")
)
"""

query = PY_LANGUAGE.query(query_str)
captures = query.captures(tree.root_node)

for node, name in captures.items():
    if name == "var_name":
        print(f"Violation: Local logger instance detected at line {node.start_point[0] + 1}")

Why this works:

Tree-sitter builds concrete syntax trees resiliently, even when code is syntactically incomplete or malformed—a common trait of raw LLM code generation snippets before full error correction. Its query language allows you to match complex syntax patterns like S-expressions.


3. Context-Aware LLM-as-a-Judge Guardrails

Scenario:

An AI coding assistant generates a function that correctly calculates pricing discounts, but completely violates your team's unwritten architectural convention: domain logic must be pure functions with zero side effects, and any asynchronous operations (like fetching exchange rates) must be performed at the service boundary, not inside domain calculations.

Why it matters:

Static analysis cannot easily determine if a function performs implicit side effects or maintains hidden dependencies unless those constraints are expressed as rigid type systems—which often leads to overly verbose boilerplate code.

Solution:

Deploy a secondary, smaller, fine-tuned LLM or an API-based LLM-as-a-judge (such as Claude 3.5 Sonnet or GPT-4o-mini) specifically conditioned on your CONVENTIONS.md file to review AI-generated diffs before merge.

Code:

Here is a Python script that orchestrates an LLM-as-a-judge review step within your review pipeline, passing the git diff and project conventions as structured prompt inputs:

import os
import openai

client = openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

def review_code_diff(diff_content: str, conventions_guide: str) -> dict:
    prompt = f"""
You are a strict Principal Software Architect reviewing code generated by an AI assistant. 
Review the following Git diff strictly against the provided project conventions.

PROJECT CONVENTIONS:
{conventions_guide}

GIT DIFF:
{diff_content}

Respond strictly in JSON format with the following keys:
- "approved": boolean
- "violations": list of strings detailing specific rule infractions
- "refactoring_suggestion": string explaining how to fix the code if rejected
"""

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        response_format={"type": "json_object"},
        messages=[{"role": "user", "content": prompt}],
        temperature: float = 0.0
    )
    
    return response.choices.message.content

Why this works:

LLMs excel at semantic pattern matching and contextual comprehension. By restricting the output format to strict JSON and constraining the prompt with exact architectural rules, you turn a non-deterministic model into a reliable, automated code reviewer.

⚠️ Gotcha: Never give an LLM-as-a-judge write access to your repository. It should only return structured diagnostics that block or pass the CI check. Giving an LLM autonomous refactoring capabilities without rigorous sandbox validation often introduces infinite loops of compounding code changes.


4. Automated Dependency and Import Boundary Enforcement

Scenario:

Your monolithic backend or monorepo is divided into bounded contexts: billing, inventory, and identity. An AI assistant generates code inside billing that directly imports models and internal services from inventory, creating tight circular coupling between business domains.

Why it matters:

If left unchecked, AI-generated code will rapidly degrade your clean modular architecture into a tightly coupled distributed monolith because LLMs naturally prioritize proximity and convenience over domain boundaries.

Solution:

Use static analysis tools like Dependency Cruiser (for JavaScript/TypeScript) or ArchUnit (for Java/Kotlin/Python via archunit) to programmatically assert architectural boundaries in your CI pipeline.

Code:

Here is a dependency-cruiser configuration (.dependency-cruiser.js) that explicitly forbids the billing module from importing anything from the inventory module:

/** @type {import('dependency-cruiser').IConfiguration} */
module.exports = {
  forbidden: [
    {
      name: 'no-billing-to-inventory-coupling',
      severity: 'error',
      comment: 'Billing bounded context must never directly import from Inventory context.',
      from: { path: '^src/billing' },
      to: { path: '^src/inventory' },
    },
    {
      name: 'no-circular-dependencies',
      severity: 'warn',
      comment: 'Circular dependencies between modules will break AI context windows and modular refactoring.',
      from: {},
      to: { circular: true },
    },
  ],
  options: {
    doNotFollow: {
      path: 'node_modules',
    },
    tsPreCompilationDeps: true,
    parser: 'tsc',
  },
};

Why this works:

Dependency Cruiser reads your import graphs statically and evaluates them against declarative rules. When an AI generates a file violating module boundaries, the CI pipeline halts instantly with a clear graph violation path.


5. Type-Level Contract Validation via Compiler APIs

Scenario:

Your team requires that all API response payloads implement a branded type or a strict interface extending a base ApiResponse<T> wrapper. An AI assistant generates endpoint handlers returning raw object literals (return { status: 200, data: user }).

Why it matters:

Runtime errors caused by mismatched data shapes slip past standard unit tests when mock data doesn't mirror real database output structures.

Solution:

Write custom TypeScript Compiler API scripts or leverage Zod schema inference checks to verify that every route handler exports functions matching exact type signatures defined in your architectural guidelines.

Code:

A TypeScript Compiler API script that scans all service controller files to ensure every exported function returns a Promise wrapping a branded response type:

import * as ts from 'typescript';

function validateControllerSignatures(fileName: string) {
  const program = ts.createProgram([fileName], { strict: true });
  const checker = program.getTypeChecker();
  const sourceFile = program.getSourceFile(fileName);

  if (!sourceFile) return;

  ts.forEachChild(sourceFile, (node) => {
    if (ts.isFunctionDeclaration(node) && node.name) {
      const symbol = checker.getSymbolAtLocation(node.name);
      if (symbol) {
        const type = checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration!);
        const signatures = checker.getSignaturesOfType(type, ts.SignatureKind.Call);

        for (const signature of signatures) {
          const returnType = checker.getReturnTypeOfSignature(signature);
          const typeString = checker.typeToString(returnType);

          if (!typeString.includes('ApiResponse<')) {
            console.error(
              `Architecture Violation: Function '${node.name.text}' returns '${typeString}', but must return 'ApiResponse<T>'.`
            );
            process.exit(1);
          }
        }
      }
    }
  });
}

validateControllerSignatures(process.argv[2]);

Why this works:

Rather than trusting superficial lint rules, this script hooks directly into the TypeScript compiler's type checker (TypeChecker), evaluating resolved types even when inferred through complex generic wrappers.


6. The CI/CD Integration Layer: GitHub Actions & Webhooks

Scenario:

You have built a robust suite of custom AST linters, boundary checkers, and LLM guardrails. Now you need to wire them together into an automated GitHub Actions pipeline that runs on every pull request containing AI-generated code.

Why it matters:

If the pipeline takes twenty minutes to run or blocks PRs with unclear error messages, developers will bypass the checks or lose trust in the automation. The feedback loop must be fast, informative, and integrated directly into the GitHub PR interface.

Solution:

Build a multi-stage GitHub Actions workflow that executes fast static checks first, followed by expensive semantic and LLM checks, posting inline comments directly onto the offending lines.

Code:

Here is a production-grade GitHub Actions workflow configured for convention enforcement:

name: AI Convention Guardrail

on:
  pull_request:
    branches: [ main ]

jobs:
  validate-conventions:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Code
        uses: actions/checkout@v4
        with:
          fetch-depth: 2

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      - name: Install Dependencies
        run: npm ci

      - name: Run AST Pattern Enforcement
        run: npx eslint . --ext .ts,.tsx --rule 'project/no-direct-database-access: error'

      - name: Run Module Boundary Checks
        run: npx depcruise --validate .dependency-cruiser.js src/

      - name: Run LLM-as-a-Judge Architectural Audit
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          python3 .github/scripts/ai_convention_judge.py \
            --diff-file <(git diff HEAD^1) \
            --conventions-file docs/CONVENTIONS.md

Why this works:

Structuring the workflow in layers ensures fast failure: syntax and structural AST checks run in seconds, failing early before expensive API calls to LLM-as-a-judge reviewers are executed.


7. Feedback Loops: Teaching the AI Generator Your Conventions

Scenario:

Your pipeline successfully blocks non-compliant AI-generated code, but developers complain that they have to constantly prompt Copilot or Cursor with the exact same instructions: "Don't use raw SQL, use our repository layer."

Why it matters:

A pipeline that only blocks bad code without feeding corrections back into the generation loop creates constant friction. Security and architecture enforcement must shift left—from CI/CD blocking to prompt-time conditioning.

Solution:

Automatically compile blocked violation reports and PR feedback into project-level configuration files (.cursorrules, .github/copilot-instructions.md) or inject them directly into your team's shared LLM system prompts.

Code:

A script that aggregates recent linter violations and automatically updates your .cursorrules file with fresh architectural constraints:

import json
from collections import Counter

def update_cursor_rules(violation_logs_path: str, rules_file_path: str):
    with open(violation_logs_path, 'r') as f:
        logs = [json.loads(line) for line in f]
        
    error_counts = Counter([log['rule_id'] for log in logs])
    top_violations = error_counts.most_common(3)
    
    additional_guideline = "\n\n## Auto-Enforced Constraints (Recent CI Failures):\n"
    for rule, count in top_violations:
        additional_guideline += f"- Avoid triggering rule `{rule}` (failed {count} times this week).\n"
        
    with open(rules_file_path, 'a') as f:
        f.write(additional_guideline)

if __name__ == "__main__":
    update_cursor_rules("ci_violations.jsonl", ".cursorrules")

Why this works:

By closing the loop between CI failures and IDE generation instructions, the pipeline stops acting purely as a gatekeeper and becomes an active self-correcting feedback mechanism for your AI tooling ecosystem.


Comparison: Choosing Your Enforcement Strategy

Strategy Setup Complexity Execution Speed Catches Architectural Intent? Best Used For
Standard ESLint / Ruff Low Extremely Fast (<5s) ❌ No (Syntax only) Formatting, basic type errors, dead code
AST Pattern Enforcers Medium Fast (~10s) ⚠️ Partial (Structural patterns) Bypassing framework wrappers, forbidden imports
Dependency Cruiser / ArchUnit Medium Fast (~15s) ✅ Yes (Module boundaries) Monorepo isolation, avoiding circular coupling
TypeScript Compiler APIs High Moderate (~30s) ✅ Yes (Type contracts) Enforcing complex return types and API shapes
LLM-as-a-Judge Guardrails High Slow (~60s+) ✅ High Semantic Depth Unwritten conventions, naming styles, side effects

A Production-Ready Convention Pipeline Architecture

Relying on human vigilance to keep AI-generated code aligned with organizational standards is a losing battle. As codebases scale and AI adoption accelerates, architectural drift becomes your primary technical debt vector.

By combining AST pattern analysis for structural rules, dependency graph linters for modular boundaries, and context-aware LLM judges for semantic constraints, you create an automated immune system for your repository.

The goal isn't to slow down AI-assisted development—it's to give developers the confidence to generate code rapidly, knowing that an automated pipeline will catch architectural violations before they ever touch production.

Post a Comment

Previous Post Next Post