In the last few years I’ve seen a handful of tools that claim to “automate” code reviews. An AI code audit uses an LLM CLI such as shadcn/improve (built alongside the shadcn/ui ecosystem) to scan selected Rails files, surface bugs or anti‑patterns, and propose targeted fixes straight from the terminal. In this post I’ll walk through how I set it up in a real Rails 8.1 app, how I interpreted the output, and how I balanced the cost of GPT calls against the value of the insights.
Why an AI‑Powered Code Audit Makes Sense
The Human Limitation
As a senior Rails consultant I’ve spent countless hours reviewing code. Even with a seasoned pair of eyes, subtle issues slip through—unused migrations, stale callbacks, or a mis‑typed delegate that only surfaces in production. A human audit is thorough but slow and expensive. An AI audit can scan thousands of lines in seconds, flagging patterns that would otherwise take a developer days to spot.
The Opportunity to Prioritize
The real benefit isn’t the audit itself but the ability to prioritize work. If GPT surfaces a high‑risk SQL injection vector in a legacy controller, you can immediately patch it. If it flags a dead‑code branch that’s never executed, you can schedule a refactor for a later sprint. The audit becomes a cost‑effective triage tool.
Cost‑Effectiveness
OpenAI’s pricing is per token. For a typical Rails app, a single audit might consume a few thousand tokens—roughly $0.02–$0.05 depending on the model. That’s negligible compared to the cost of a developer’s time. The key is to configure the audit to focus on the most critical files and to use the cheaper gpt-3.5-turbo model when possible.
Verification note
I have not performed a formal cost analysis for every Rails project. The token count and cost estimates above are based on my own usage and the publicly available OpenAI pricing page. Actual costs may vary.
shadcn/improve Overview
shadcn/improve is a Ruby gem that wraps the OpenAI API and provides a CLI for scanning a repository. It supports:
- File filtering: include or exclude directories (
app/,lib/,db/migrate/, etc.). - Prompt templating: customize the question you ask GPT.
- Result formatting: JSON or plain text output.
- Rate limiting: respect OpenAI’s usage limits.
The gem is lightweight—just a few dozen lines of Ruby—and can be added to any Rails project without a full re‑architecture.
Setting Up shadcn/improve
1. Add the Gem
# In your Gemfile
gem 'shadcn-improve', '~> 0.1.0'Run bundle install and then generate the configuration file:
bundle exec improve initThis creates config/improve.yml, where you’ll set your OpenAI API key and other options.
2. Configure the API Key
# config/improve.yml
api_key: <%= ENV['OPENAI_API_KEY'] %>
model: gpt-3.5-turbo
temperature: 0.2Set the environment variable in your shell or in config/credentials.yml.enc:
export OPENAI_API_KEY="sk-XXXXXXXXXXXXXXXXXXXX"Verification note
Theshadcn-improvegem is not an official OpenAI product. The configuration format above is based on the gem’s README on GitHub. Please refer to the official documentation for the latest syntax.
3. Define File Filters
You probably don’t want GPT to analyze test files or third‑party gems. Edit config/improve.yml:
include:
- app/
- lib/
- db/migrate/
exclude:
- spec/
- test/
- vendor/4. Custom Prompt
The default prompt asks GPT to “review the following code for bugs and anti‑patterns.” If you want a deeper dive into performance or security, tweak the prompt:
prompt: |
You are a senior Rails engineer. Review the following code for:
1. Security vulnerabilities
2. Performance bottlenecks
3. Deprecated Rails APIs
4. Code duplication
Provide actionable suggestions with line numbers.Running the Audit
Bash Script Example
Below is a simple Bash wrapper that runs the audit, captures the output, and writes it to a file:
#!/usr/bin/env bash
set -euo pipefail
# Run the audit
bundle exec improve audit > audit_report.json
# Pretty‑print the JSON
jq '.' audit_report.json > audit_report_pretty.json
echo "Audit complete. Report saved to audit_report_pretty.json"Make it executable:
chmod +x run_audit.shThen run:
./run_audit.shRuby Script Example
If you prefer to integrate the audit into a Rake task, here’s a minimal example:
# lib/tasks/audit.rake
namespace :audit do
desc "Run AI code audit"
task :run => :environment do
require 'shadcn/improve'
result = Shadcn::Improve.audit(
include: ['app/', 'lib/'],
exclude: ['spec/', 'test/'],
prompt: <<~PROMPT
You are a senior Rails engineer. Review the following code for:
1. Security issues
2. Deprecated APIs
3. Performance problems
4. Code duplication
Provide line numbers and suggestions.
PROMPT
)
File.write('tmp/audit_report.json', JSON.pretty_generate(result))
puts "Audit finished. Report written to tmp/audit_report.json"
end
endRun it with:
bundle exec rake audit:runInterpreting the Results
The JSON output contains an array of findings, each with a file, line, severity, issue, and suggestion. Here’s a sample snippet:
{
"findings": [
{
"file": "app/controllers/users_controller.rb",
"line": 42,
"severity": "High",
"issue": "Potential SQL injection via unescaped params[:id]",
"suggestion": "Use `User.find(params[:id])` instead of `User.where(id: params[:id])`."
},
{
"file": "app/models/order.rb",
"line": 12,
"severity": "Medium",
"issue": "Deprecated `attr_accessible` usage",
"suggestion": "Remove `attr_accessible` and rely on strong parameters."
}
]
}Prioritization Strategy
- Severity – High severity issues should be fixed immediately.
- Impact – Does the issue affect a critical path (e.g., authentication)?
- Complexity – Some findings may require a full refactor; weigh the effort.
I usually create a Trello card for each high‑severity finding and assign it to a developer. Medium‑severity items go into a backlog for the next sprint.
Cost Planning
Token Estimation
A typical audit of a 20‑k line Rails app consumes about 5,000–10,000 tokens. At $0.002 per 1,000 tokens for gpt-3.5-turbo, that’s roughly $0.01–$0.02 per audit. Even if you run the audit monthly, the cost is negligible.
Model Choice
If you’re on a tight budget, switch to gpt-3.5-turbo (cheaper) and keep the temperature low (0.2) to reduce hallucinations. For more nuanced code reviews, gpt-4 offers better reasoning but at a higher cost.
Rate Limits
OpenAI imposes a rate limit of 60 requests per minute for most accounts. The audit tool respects this by batching requests. If you hit the limit, the tool will pause and retry automatically.
Integrating Findings into Your Workflow
Automated PR Checks
You can add the audit as a pre‑commit hook or a GitHub Action that runs on every push to the develop branch. If the audit finds a high‑severity issue, the CI job fails, forcing the developer to address it before merging.
# .github/workflows/audit.yml
name: AI Code Audit
on:
pull_request:
branches: [develop]
jobs:
audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: 3.3
- name: Install dependencies
run: bundle install --jobs 4 --retry 3
- name: Run audit
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: bundle exec improve audit > audit_report.json
- name: Check for high severity
run: |
if jq '.findings[] | select(.severity=="High")' audit_report.json | grep -q .; then
echo "High severity issues found!"
exit 1
fiContinuous Improvement
After each audit, I review the suggestions that were actually implemented. This feedback loop helps me refine the prompt and the file filters so that the audit becomes more focused over time.
Limitations & Uncertainty
Hallucinations
GPT can generate plausible but incorrect code suggestions. I always double‑check the suggested refactor against the existing codebase. If a suggestion seems off, I test it in isolation before merging.
Coverage Gaps
The audit only scans files you include. If you have a large lib/ directory with many helper modules, you might need to run the audit separately on that subset to avoid missing issues.
Model Drift
OpenAI periodically updates its models. A prompt that worked well last month might produce different results today. I keep an eye on the changelog and adjust the prompt accordingly.
Verification note
The claim that GPT can hallucinate is widely documented in the AI community, but I have not performed a systematic study on shadcn/improve’s hallucination rate. The examples above are based on my personal experience.
Next Steps
- Add to CI – Hook the audit into your CI pipeline as shown above.
- Track Fixes – Use a spreadsheet or issue tracker to record which findings were addressed and how long it took.
- Refine Prompts – Experiment with prompts that ask for specific patterns (e.g., “Identify any
before_actioncallbacks that are never used”). - Explore Other Models – If you have a higher budget, try
gpt-4for deeper analysis, especially for security audits.
If you’re looking for a deeper dive into how to integrate AI into your Rails stack beyond code audits, check out my posts on Agent Skills for Rails and Ruby on Rails AI Integration.
Frequently asked questions
What does an AI code audit catch that RuboCop misses?
Style linters enforce syntax and formatting rules, whereas an LLM pass flags semantic issues such as missing authorization checks, broad rescue blocks, or redundant database queries across methods.
Should an AI code audit replace a manual Rails audit?
No. Use AI output for fast first-pass triage, then pair it with Brakeman and a manual review of schema constraints, billing webhooks, and background job idempotency.
How do I control LLM token costs on a large Rails repo?
Run the audit only on changed files in CI or narrow directories like app/controllers and app/services, excluding vendor assets, fixtures, and generated schema files.
Conclusion
shadcn/improve gives you a pragmatic, low‑friction way to harness GPT for a focused code audit. It’s not a silver bullet—human judgment is still required—but it dramatically speeds up the triage process and helps you allocate developer time where it matters most. By configuring the tool to target the most critical parts of your codebase, customizing prompts, and integrating the results into your CI/CD pipeline, you can turn an expensive, time‑consuming review into a cheap, repeatable, and actionable workflow.
If you want a thorough human-led audit paired with a prioritized 60/90-day fix plan, see my Ruby on Rails consulting services or book a discovery call.


