# How to Use shadcn/improve to Run an AI‑Powered Code Audit on Your Rails App

> Discover how shadcn/improve lets you audit your Rails codebase with GPT, generate actionable plans, and cut model costs while boosting quality.

- URL: https://railsdev.io/blog/ai-code-audit-shadcn-improve-rails
- Published: 2026-11-12
- Author: Hendra Nicholas (Rails Full-Stack Developer & AI Engineer)

---

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](https://ui.shadcn.com/) 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

```bash
# In your Gemfile
gem 'shadcn-improve', '~> 0.1.0'
```

Run `bundle install` and then generate the configuration file:

```bash
bundle exec improve init
```

This creates `config/improve.yml`, where you’ll set your OpenAI API key and other options.

### 2. Configure the API Key

```yaml
# config/improve.yml
api_key: <%= ENV['OPENAI_API_KEY'] %>
model: gpt-3.5-turbo
temperature: 0.2
```

Set the environment variable in your shell or in `config/credentials.yml.enc`:

```bash
export OPENAI_API_KEY="sk-XXXXXXXXXXXXXXXXXXXX"
```

> **Verification note**  
> The `shadcn-improve` gem 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`:

```yaml
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:

```yaml
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:

```bash
#!/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:

```bash
chmod +x run_audit.sh
```

Then run:

```bash
./run_audit.sh
```

### Ruby Script Example

If you prefer to integrate the audit into a Rake task, here’s a minimal example:

```ruby
# 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
end
```

Run it with:

```bash
bundle exec rake audit:run
```

## Interpreting the Results

The JSON output contains an array of findings, each with a `file`, `line`, `severity`, `issue`, and `suggestion`. Here’s a sample snippet:

```json
{
  "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

1. **Severity** – High severity issues should be fixed immediately.
2. **Impact** – Does the issue affect a critical path (e.g., authentication)?
3. **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.

```yaml
# .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
          fi
```

### Continuous 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

1. **Add to CI** – Hook the audit into your CI pipeline as shown above.
2. **Track Fixes** – Use a spreadsheet or issue tracker to record which findings were addressed and how long it took.
3. **Refine Prompts** – Experiment with prompts that ask for specific patterns (e.g., “Identify any `before_action` callbacks that are never used”).
4. **Explore Other Models** – If you have a higher budget, try `gpt-4` for 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](/blog/agent-skills-for-rails) and [Ruby on Rails AI Integration](/blog/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](https://brakemanscanner.org/) 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](/services/ruby-on-rails-consulting) or [book a discovery call](/#contact).
