Skip to content

AI-Assisted Code Review

The Microtec DevSecOps pipeline includes an AI-assisted code review stage that provides automated feedback on pull requests before human reviewers are assigned. This stage runs after unit tests and before the SAST scan.


Purpose

What AI Review Adds

AI code review is not a replacement for human review. It is a first-pass filter that catches:

  • Common anti-patterns and code smells at scale (every PR, not just sampled ones)
  • Security-relevant patterns that static analysis tools miss (e.g. logic-level authorization issues)
  • Documentation gaps and missing XML doc comments on public APIs
  • Violation of Microtec-specific naming conventions

Human reviewers then focus on architecture, business logic, and context-sensitive decisions.


Pipeline Stage

PropertyValue
Stage numberStage 4 — AI Code Review
TriggerPull request to main, stage, PreProd, production branches
BlockingNo — advisory only; does not fail the pipeline
OutputPR comment with findings summary
ModelGPT-4o via Azure OpenAI (UK South region)

What It Checks

1. Security Patterns

The AI review prompt instructs the model to flag:

PatternExample
Hardcoded credentialsvar pass = "Admin@123" in source
Missing authorization attributesController action without [Authorize]
Direct SQL string concatenation$"SELECT * FROM Users WHERE Id = {id}"
Unrestricted file uploadMissing MIME type or size validation
Sensitive data in logs_logger.LogInformation("Token: {token}", jwt)
Missing input validationCommand/DTO property with no [Required] or FluentValidation rule

2. Code Quality

CheckDescription
Method lengthFlags methods exceeding 50 lines
Cyclomatic complexityWarns on deeply nested logic (>4 levels)
Dead codeUnreachable branches, unused parameters
Exception swallowingEmpty catch blocks
Missing AsNoTracking()EF Core read-only queries without tracking hint

3. Naming Conventions

The AI is given the Microtec naming convention guide as system context:

  • CQRS handler naming: Add{Entity}Command, Get{Entity}Query
  • Route conventions: /api/v1/{resource}
  • Service registration interfaces: IScopedService, ITransientService
  • Repository naming: I{Entity}Repository

4. Documentation

  • Public API controllers must have XML <summary> on each action
  • New DTOs should have property-level comments for non-obvious fields
  • New services should document their retry/timeout behaviour

Pipeline Integration

yaml
- stage: AICodeReview
  displayName: 'Stage 4 - AI Code Review'
  dependsOn: UnitTests
  condition: and(succeeded(), eq(variables['Build.Reason'], 'PullRequest'))
  jobs:
    - job: AIReview
      pool:
        vmImage: 'ubuntu-latest'
      steps:
        - task: Bash@3
          displayName: 'Generate diff for AI review'
          inputs:
            targetType: inline
            script: |
              git diff origin/$(System.PullRequest.TargetBranch)...HEAD \
                -- '*.cs' '*.ts' '*.dart' \
                > $(Build.ArtifactStagingDirectory)/diff.patch

        - task: Bash@3
          displayName: 'Submit to Azure OpenAI'
          env:
            AOAI_ENDPOINT: $(AZURE_OPENAI_ENDPOINT)
            AOAI_KEY: $(AZURE_OPENAI_KEY)
          inputs:
            targetType: inline
            script: |
              python3 $(Build.SourcesDirectory)/devops/scripts/ai-review.py \
                --diff $(Build.ArtifactStagingDirectory)/diff.patch \
                --output $(Build.ArtifactStagingDirectory)/ai-review.md \
                --pr-id $(System.PullRequest.PullRequestId) \
                --repo $(Build.Repository.Name)

        - task: Bash@3
          displayName: 'Post review as PR comment'
          env:
            ADO_TOKEN: $(System.AccessToken)
          inputs:
            targetType: inline
            script: |
              python3 $(Build.SourcesDirectory)/devops/scripts/post-pr-comment.py \
                --review $(Build.ArtifactStagingDirectory)/ai-review.md \
                --pr-id $(System.PullRequest.PullRequestId)

Interpreting the Output

The AI review comment is posted to the pull request in the following structure:

## AI Code Review — Build #42

### Summary
3 findings (0 High · 2 Medium · 1 Low)

---

### Finding 1 — [MEDIUM] Missing Authorization
**File:** `Platforms/Src/AppsPortal/Accounting/AppsPortal.Apis/Controllers/JournalController.cs`
**Line:** 87

The `GetAll` action does not have an `[Authorize]` attribute. All ERP API actions
should require authentication. If this endpoint is intentionally public, add a
`[AllowAnonymous]` attribute with a comment explaining why.

**Suggested fix:**
\```csharp
[HttpGet]
[Authorize(Policy = "ErpUser")]   // add this
public async Task<IActionResult> GetAll(...) { ... }
\```

---

### Finding 2 — [MEDIUM] EF Core tracking on read query
...

### Finding 3 — [LOW] Missing XML doc comment
...

Severity Interpretation

SeverityMeaningRecommended Action
HighLikely security vulnerability or data integrity riskMust address before merge
MediumCode quality or potential bugShould address before merge
LowStyle, documentation, or minor suggestionAddress at discretion
InfoInformational observationNo action required

AI Findings Are Not Authoritative

The AI model can produce false positives. Always apply engineering judgement before acting on a finding. If a finding is incorrect, reply to the PR comment with an explanation — this feedback is used to refine the review prompt.


Scope Limitations

The AI review currently covers:

  • C# files (*.cs) — full coverage
  • TypeScript/Angular files (*.ts) — component and service files
  • Dart/Flutter files (*.dart) — service and model files

The following are out of scope for AI review:

  • Bicep infrastructure files (covered by Bicep linter in a separate stage)
  • YAML pipeline files
  • Generated code (EF migrations, auto-generated API clients)
  • Binary or asset files

Excluding Files from AI Review

Add a .aiignore file to the repository root (same syntax as .gitignore) to exclude specific paths from the diff sent to the AI model. This is useful for generated code or vendored dependencies.


Prompt Engineering

The system prompt sent to the model includes:

  1. Microtec architecture context — Clean Architecture layers, CQRS pattern, multi-tenancy model
  2. Security rules — OWASP Top 10, Microtec-specific XApiKey handling, tenant isolation rules
  3. Naming conventions — From Platforms/Solution Items/NamingConventions.md
  4. Output format — Structured markdown with severity classification

The prompt is maintained at devops/scripts/ai-review-system-prompt.md in the repository. Changes to the prompt require a PR to the DevOps repository and approval from the security team.

Internal Documentation — Microtec Platform Team