---
name: code-quality-gates-4188f0a6aca1
description: "Comprehensive code quality validation using Solargraph, Sorbet, and Rubocop for A+ Rails code. Trigger keywords: quality gates, validation, solargraph, sorbet, rubocop, type checking, linting, code quality, static analysis"
version: 1.0.0
---

# Code Quality Gates

This skill provides patterns for comprehensive code quality validation using three complementary tools: Solargraph (LSP diagnostics), Sorbet (type checking), and Rubocop (style enforcement).

## 1. Tool Stack Overview

### Solargraph (Ruby LSP)

**Purpose**: Language server providing IDE-like features and diagnostics

**Setup**:
```bash
gem install solargraph
solargraph config  # Generates .solargraph.yml
```

**Key Features**:
- Method completion and documentation
- Go to definition/references
- Hover information
- Diagnostics (undefined methods, type errors)
- Integration with cclsp MCP

**Diagnostics Patterns**:
- Undefined methods: `NoMethodError` detection
- Unresolved constants: Missing class/module references
- Parameter count mismatches: Wrong arity
- Unused variables: Dead code detection

**cclsp Integration**:
```ruby
# Agents use cclsp MCP tools
mcp__cclsp__get_diagnostics file_path="app/models/user.rb"
# Returns: errors, warnings, hints for the file
```

**Configuration** (`.solargraph.yml`):
```yaml
include:
  - "**/*.rb"
exclude:
  - spec/**/*
  - test/**/*
  - vendor/**/*
reporters:
  - rubocop
  - require_not_found
plugins: []
require_paths: []
domains: []
max_files: 5000
```

---

## 2. Sorbet (Type Checking)

**Purpose**: Static type checker for Ruby with gradual typing

**Setup**:
```bash
# Add to Gemfile
gem 'sorbet'
gem 'sorbet-runtime'

# Initialize
bundle exec srb init

# Generate RBI files for gems
bundle exec tapioca init
bundle exec tapioca gems
```

### Type Sigils

Gradual adoption through file-level type checking levels:

```ruby
# typed: ignore   # Skip this file entirely
# typed: false    # Only check syntax errors
# typed: true     # Check types, infer missing signatures
# typed: strict   # Require explicit signatures
# typed: strong   # No T.untyped allowed
```

### Common Patterns

**Basic Signature**:
```ruby
sig { params(name: String).returns(User) }
def find_by_name(name)
  User.where(name: name).first
end
```

**Void Methods**:
```ruby
sig { params(user: User).void }
def send_notification(user)
  Mailer.deliver(user.email)
end
```

**Nilable Types**:
```ruby
sig { params(id: Integer).returns(T.nilable(User)) }
def find_user(id)
  User.find_by(id: id)  # May return nil
end
```

**Arrays and Hashes**:
```ruby
sig { params(items: T::Array[String]).returns(T::Hash[String, Integer]) }
def count_items(items)
  items.tally
end
```

**Class Methods**:
```ruby
class << self
  sig { returns(T::Array[User]) }
  def active_users
    where(active: true).to_a
  end
end
```

---

## 3. Rubocop (Style Enforcement)

**Purpose**: Ruby static code analyzer and formatter

**Setup**:
```bash
gem install rubocop
rubocop --init  # Generates .rubocop.yml
```

### Auto-fix Strategy

```bash
# Fix safe offenses automatically
rubocop -a

# Fix all offenses (use with caution)
rubocop -A

# Fix specific file
rubocop -a app/models/user.rb

# Check without fixing
rubocop --fail-level error --format simple app/models/user.rb
```

### Common Violations

**Line Length** (default: 120):
```ruby
# Bad
def very_long_method_name_that_exceeds_the_maximum_allowed_line_length_for_ruby_code_according_to_rubocop_standards

# Good
def descriptive_method_name
  # Implementation
end
```

**Frozen String Literal**:
```ruby
# Add to top of file
# frozen_string_literal: true
```

**Inconsistent Indentation**:
```ruby
# Bad
def method
 puts "inconsistent"
  puts "indentation"
end

# Good
def method
  puts "consistent"
  puts "indentation"
end
```

**Trailing Whitespace**:
```ruby
# Bad
def method
  puts "hello"
end

# Good
def method
  puts "hello"
end
```

### Configuration (`.rubocop.yml`):
```yaml
AllCops:
  TargetRubyVersion: 3.2
  NewCops: enable
  Exclude:
    - 'db/schema.rb'
    - 'vendor/**/*'
    - 'node_modules/**/*'

Layout/LineLength:
  Max: 120

Style/Documentation:
  Enabled: false  # Allow missing class docs

Metrics/MethodLength:
  Max: 20

Metrics/AbcSize:
  Max: 20
```

---

## 4. Validation Strategy

### Phase 4 Quality Gate

Runs after each implementation layer (models, services, components):

**validate-implementation.sh Workflow**:

1. **Check Tool Availability**
   ```bash
   check_tool_available solargraph  # → true/false
   check_tool_available sorbet       # → true/false
   check_tool_available rubocop      # → true/false
   ```

2. **Solargraph Diagnostics**
   ```bash
   for file in $FILES; do
     solargraph check "$file"  # Get diagnostics
     # Check for errors
   done
   ```

3. **Sorbet Type Check** (typed files only)
   ```bash
   # Filter to typed files
   typed_files=$(grep -l "# typed:" $FILES)

   # Run type check
   bundle exec srb tc $typed_files
   ```

4. **Rubocop Style Check**
   ```bash
   # Fail on warnings (blocking mode)
   rubocop --fail-level warning --format simple $FILES
   ```

5. **Exit Based on Validation Level**
   - **blocking**: Exit 1 if any fail (prevents progress)
   - **warning**: Exit 2 if any fail (alerts but allows)
   - **advisory**: Exit 0 always (informational)

---

## 5. Guardian Cycle

Runs after Phase 4 for comprehensive type safety:

**guardian-validation.sh Workflow**:

1. **Collect Modified Files**
   ```bash
   FILES=$(bd show $FEATURE_ID | grep -oE "app/[a-z_/]+\.rb")
   ```

2. **Run Sorbet Type Check**
   ```bash
   bundle exec srb tc $FILES
   ```

3. **Analyze Errors** (if any)
   - Missing signatures
   - Type mismatches
   - Undefined methods
   - T.untyped violations

4. **Attempt Auto-Fix** (simple cases)
   ```ruby
   # Add default signature
   sig { returns(T.untyped) }
   def method_name
     # ...
   end
   ```

5. **Re-validate** (max 3 iterations)
   - Run srb tc again
   - Check if errors resolved
   - Log remaining issues

6. **Block or Pass**
   - Exit 0 if all pass
   - Exit 1 if errors remain after max iterations

---

## 6. Tool Integration Patterns

### Pre-Edit Validation

**Hook**: PreToolUse (before Edit tool)

```bash
# Check syntax before applying edit
echo "$NEW_CONTENT" | ruby -c

# If typed file, warn about Sorbet validation
if grep -q "# typed:" "$FILE_PATH"; then
  echo "ℹ️  Sorbet validation will run post-edit"
fi
```

### Post-Write Validation

**Hook**: PostToolUse (after Write tool)

```bash
# Syntax check (always)
ruby -c "$FILE_PATH"

# Rubocop (if available)
rubocop --fail-level error "$FILE_PATH"

# Sorbet (if typed)
if grep -q "# typed:" "$FILE_PATH"; then
  bundle exec srb tc "$FILE_PATH"
fi
```

---

## 7. Error Messages and Fixes

### Solargraph Errors

**Undefined Method**:
```
Error: Method 'email' is not defined on User

Fix: Define the method or add to class
def email
  # ...
end
```

**Unresolved Constant**:
```
Error: Constant 'PaymentService' not found

Fix: Require the file or fix namespace
require_relative 'payment_service'
```

### Sorbet Errors

**Missing Signature**:
```
Error: Method does not have a `sig`

Fix:
sig { params(name: String).returns(User) }
def find_by_name(name)
  # ...
end
```

**Type Mismatch**:
```
Error: Expected String but found Integer

Fix: Convert type or update signature
name.to_s  # Convert Integer to String
```

**Undefined Method on Typed Value**:
```
Error: Method `email` does not exist on `T.untyped`

Fix: Add type annotation
sig { params(user: User).void }  # Now user has type
def send_email(user)
  user.email  # Safe - user is typed as User
end
```

### Rubocop Violations

**Style/FrozenStringLiteralComment**:
```
Fix: Add to top of file
# frozen_string_literal: true
```

**Layout/LineLength**:
```
Fix: Break long lines
# Bad
very_long_method_call_with_many_parameters(param1, param2, param3, param4)

# Good
very_long_method_call_with_many_parameters(
  param1,
  param2,
  param3,
  param4
)
```

---

## 8. Best Practices

### Gradual Adoption

**Phase 1**: Start with Rubocop
```yaml
# .rubocop.yml - relaxed rules
Metrics/MethodLength:
  Max: 30  # Increase limits initially
```

**Phase 2**: Add Solargraph for diagnostics
```bash
solargraph check app/models/*.rb  # Check specific directories
```

**Phase 3**: Introduce Sorbet with `# typed: false`
```ruby
# typed: false  # Minimal checking
class User
  # No signatures required yet
end
```

**Phase 4**: Gradually upgrade to `# typed: true`
```ruby
# typed: true  # Type inference enabled
class User
  sig { params(name: String).returns(User) }  # Add signatures
  def self.find_by_name(name)
    # ...
  end
end
```

### File-by-File Strategy

Focus on new files first:
```
New files → # typed: true (type-safe from start)
Old files → # typed: false (legacy, upgrade gradually)
Core files → # typed: strict (critical paths)
```

### Continuous Integration

Run quality gates in CI:
```yaml
# .github/workflows/quality.yml
- name: Rubocop
  run: bundle exec rubocop

- name: Sorbet
  run: bundle exec srb tc

- name: Solargraph
  run: solargraph check app/**/*.rb
```

---

## 9. Configuration Templates

### .claude/reactree-rails-dev.local.md

```yaml
---
enabled: true
quality_gates_enabled: true
guardian_enabled: true
validation_level: blocking  # blocking, warning, advisory
guardian_max_iterations: 3
---
```

### .solargraph.yml

```yaml
include:
  - "**/*.rb"
exclude:
  - spec/**/*
  - test/**/*
  - vendor/**/*
  - db/schema.rb
reporters:
  - rubocop
  - require_not_found
max_files: 5000
```

### .rubocop.yml

```yaml
AllCops:
  TargetRubyVersion: 3.2
  NewCops: enable
  Exclude:
    - 'db/schema.rb'
    - 'vendor/**/*'

Layout/LineLength:
  Max: 120

Style/FrozenStringLiteralComment:
  Enabled: true
  EnforcedStyle: always
```

### sorbet/config

```
--dir
.
--ignore=/vendor/
--ignore=/tmp/
```

---

## 10. Troubleshooting

### Solargraph Not Working

```bash
# Rebuild index
solargraph clear
solargraph download-core

# Check configuration
solargraph config
```

### Sorbet Type Errors

```bash
# Regenerate RBI files
bundle exec tapioca gems

# Check Sorbet version
bundle exec srb --version

# Run with verbose output
bundle exec srb tc --verbose
```

### Rubocop False Positives

```ruby
# Disable specific cop for line
# rubocop:disable Style/FrozenStringLiteralComment
code_here
# rubocop:enable Style/FrozenStringLiteralComment

# Disable for file
# rubocop:disable all
```

---

## Summary

Code Quality Gates provide three layers of validation:

1. **Solargraph**: IDE-like diagnostics (undefined methods, constants)
2. **Sorbet**: Static type checking (type safety, signatures)
3. **Rubocop**: Style enforcement (conventions, best practices)

**Integration Points**:
- Phase 4 Quality Gates (after each layer)
- Guardian Validation Cycle (after full implementation)
- PreToolUse/PostToolUse Hooks (real-time validation)

**Gradual Adoption**:
- Start with Rubocop (easiest)
- Add Solargraph (diagnostics)
- Introduce Sorbet (type safety)
- Tighten rules over time

**Result**: A+ type-safe, well-styled Rails code with comprehensive quality validation.


---
Source attribution: David-Li0406
Original project: https://github.com/David-Li0406/meta-skill-evloving/blob/ca3a335628981df10c36e00cb9850df2c247ab9a/skill-flow/data/skills-refined-36k/skillsmp/code-quality-gates-2/SKILL.md
License: Apache-2.0
License information: https://www.apache.org/licenses/LICENSE-2.0
Original upstream instructions; downloaded from Dave AI.

## Upstream license notice

Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.



# Dave AI resource metadata

Creator / publisher: David-Li0406
Original project: https://github.com/David-Li0406/meta-skill-evloving/blob/ca3a335628981df10c36e00cb9850df2c247ab9a/skill-flow/data/skills-refined-36k/skillsmp/code-quality-gates-2/SKILL.md
Attribution basis: Source repository record

Fields of work: Development & Engineering, Product Management
Roles: Backend Developer, DevOps / SRE, Product Manager, QA / Test Engineer, Technical Product Manager
Specialties: Backend, Testing
Tools: Rubocop, Solargraph, Sorbet
Country applicability: Country not specified
Classification basis: Source catalog labels
Instruction SHA-256: 8604968e6ffe78cf132a6bc5ca2c11f8709c60cab3cbc9f6442e60d06890c519
