Ratchet Documentation

The AI-powered CLI that scores, guards, and autonomously improves your codebase — one controlled click at a time.

$ npm install -g ratchet-run
Getting Started#
Install, configure, and run your first autonomous improvement cycle in under 5 minutes.

Prerequisites

Ratchet requires Node.js 18+ and Git. Paid features (torque, improve) require a license key from ratchetcli.com.

Installation

Install Ratchet globally via npm:

bash
npm install -g ratchet-run

Verify the installation:

bash
ratchet --version
# ratchet v1.0.8

Authentication

Log in with your license key. You'll receive one via email after purchasing a plan at ratchetcli.com:

bash
ratchet login your-license-key-here

License Key Safety: Your key is stored locally in ~/.ratchet/license.json. Never commit it to version control. Use the RATCHET_LICENSE_KEY environment variable in CI.

Initialize Your Project

Navigate to your project root and run ratchet init. Ratchet auto-detects your project type and writes a .ratchet.yml configuration file:

bash
cd my-project
ratchet init

Ratchet will detect your framework, test runner, and project structure, then generate a starter config:

Output
✓ Detected: Node.js / TypeScript (Express)
✓ Wrote .ratchet.yml
✓ Detected test runner: Jest
✓ Set test_command: "npm test"
✓ Guard profile: refactor (default)

Run `ratchet scan` to score your codebase, or `ratchet torque` to start improving.

Your First Torque Run

torque is Ratchet's autonomous improvement engine. By default it runs 7 clicks — each click is a bounded AI agent cycle: read → analyze → edit → verify. You can configure the click count, scope, and guard profiles.

1

Scan first

Get a baseline score before making changes.

2

Run torque

Start the autonomous improvement loop with default settings.

3

Review the log

Check ratchet log to see every change Ratchet made and why.

4

Tighten & PR

Finalize the run with ratchet tighten --pr to create a pull request.

bash
# Baseline score
ratchet scan

# Run 7 autonomous improvement clicks (default)
ratchet torque

# Run 3 clicks on a specific target
ratchet torque --target api --clicks 3

# Plan first, then execute (review mode)
ratchet torque --plan-first

What to expect: Each click takes 30–90 seconds depending on project size. Ratchet makes targeted, scoped edits — never rewrites entire files unless necessary. Every change is logged with a reason. If a change breaks tests, the guard system reverts and escalates.

Typical First Run Output

bash
$ ratchet torque

  ⚡ Ratchet v1.0.8 — Torque Mode
  ─────────────────────────────────
  Target:     full codebase
  Guard:      refactor (3 files / 60 lines max)
  Scope:      staged (auto-detected clean state)
  Clicks:     7 (default)

  Click 1/7  ✓ Error handling — added try/catch to auth middleware
  Click 2/7  ✓ Type safety — inferred missing TypeScript types in user.ts
  Click 3/7  ✓ Security — sanitized SQL input in user queries
  Click 4/7  ✓ Testing — added edge case tests for payment module
  Click 5/7  ✓ Code quality — extracted duplicate validation logic
  Click 6/7  ✓ Performance — added DB index hint for hot query
  Click 7/7  ✓ Error handling — centralized error response format

  ─────────────────────────────────
  Score: 68 → 84 (+16 pts)
  Status: GUARDED  (all tests passing)
  ─────────────────────────────────

  Run `ratchet tighten` to finalize or `ratchet log` to review changes.
CLI Reference#
Complete reference for every Ratchet command and flag.

init [dir]

Auto-detects your project type and writes a .ratchet.yml configuration file. Run this once per repository.

ArgumentDescription
dirTarget directory (default: current working directory)

Ratchet detects: language/framework, test runner, package manager, build system, and coding conventions. The generated config uses sensible defaults — review and tweak as needed.

You can also manually create .ratchet.yml. See the Configuration section for a full annotated example.

bash
ratchet init
ratchet init ./my-service

torque

The core autonomous improvement engine. Runs a bounded loop of AI agent cycles ("clicks") that scan, plan, edit, verify, and iterate on your codebase. Each click is self-contained and guarded.

FlagDefaultDescription
--targetallTarget name from .ratchet.yml targets[].name to scope improvements to.
--clicks7Number of improvement cycles to run (1–50). Each click is a bounded agent cycle.
--plan-firstfalsePlan all changes first, print a summary, then execute. Use for review mode.
--scopediffScope mode: diff (current changes), branch (all branch changes), staged (git staged), glob (glob pattern), file:paths (comma-separated paths).
--guardsrefactorGuard profile: tight, refactor, broad, or atomic. Controls how aggressively Ratchet modifies files per click.
--no-escalatefalseDisable smart guard escalation. Ratchet will not broaden scope on consecutive passes.
--no-guard-escalationfalseAlias for --no-escalate. Prevents the guard system from escalating its own limits.
--no-architectfalseSkip architect-level analysis (import graphs, dependency structure). Run only targeted file edits.
--no-pr-commentfalseSkip posting PR comments on completion (if connected to GitHub/GitLab).
--timeout300Per-click timeout in seconds. Set to 0 for no timeout.
--jsonfalseOutput machine-readable JSON instead of the human-readable progress view.
bash
# Standard 7-click run
ratchet torque

# Aggressive: 15 clicks, broad guards, no PR comments
ratchet torque --clicks 15 --guards broad --no-pr-comment

# Review mode: plan first, then confirm
ratchet torque --clicks 3 --plan-first

# Targeted: only the "api" target, tight guards
ratchet torque --target api --guards tight --clicks 5

# Glob scope: only TypeScript files in src/
ratchet torque --scope "glob:src/**/*.ts"

# Staged files only (for PRs)
ratchet torque --scope staged

# JSON output (for scripting)
ratchet torque --clicks 3 --json > run.json

improve

Full autonomous improvement pipeline: scan → fix → rescan → report. Runs the full loop until the score threshold is met or click budget is exhausted. Simpler than torque for goal-oriented runs.

FlagDefaultDescription
--scopediffScope mode (same options as torque): diff, branch, staged, glob, file:paths.
--targetallTarget name to improve (from .ratchet.yml).
bash
# Improve until score ≥ 85 or budget exhausted
ratchet improve

# Improve only staged files
ratchet improve --scope staged

scan [dir]

Scores the codebase across 6 categories (Testing, Security, Type Safety, Error Handling, Performance, Code Quality). Provides a baseline before running improvements. Works on any directory.

FlagDefaultDescription
--fail-onExit with code 1 if the overall score falls below this threshold (0–100). Use in CI.
--fail-on-categoryFail if a specific category drops below a score. Format: name=score (e.g., security=70).
--output-jsonfalseOutput results as JSON for programmatic consumption.
--explainfalsePrint detailed reasoning for each score deduction.
bash
# Score the current project
ratchet scan

# Score with detailed explanations
ratchet scan --explain

# CI mode: fail if score < 80
ratchet scan --fail-on 80

# JSON output for pipelines
ratchet scan --output-json > score.json

# Fail on specific category
ratchet scan --fail-on-category "security=70" --fail-on-category "testing=60"

# Scan a specific subdirectory
ratchet scan ./packages/api

status

Shows the current or most recent Ratchet run — its state (running, guarded, failed, complete), score delta, click count, and any active guards. Essential for monitoring long-running torque sessions.

bash
$ ratchet status

  Run ID:    run_k8s2x9m
  Status:    RUNNING  (Click 4/7)
  Started:   2 minutes ago
  Score:     71 → 79 (+8 pts)
  Guards:    active (refactor — 3 files / 60 lines)
  Scope:     branch
  Target:    full codebase

  Last click: ✓ Type Safety — added missing null checks in payment.ts
  Next:      (3 more clicks queued)

log

Displays the Ratchet change log for a target or run. Shows every file modified, the AI reasoning behind the change, the guard level used, and whether tests passed.

FlagDefaultDescription
--targetFilter log to a specific target name from .ratchet.yml.
--runlastShow log for a specific run ID.
bash
# Show log from the last run
ratchet log

# Show log for a specific run
ratchet log --run run_k8s2x9m

# Filter by target
ratchet log --target api

tighten

Finalizes the current run. Validates that all changes are committed, tests pass, and guards are satisfied. Optionally creates a pull request if --pr is specified and a remote is detected.

FlagDefaultDescription
--prfalseCreate a pull request on the current branch. Detects GitHub, GitLab, or Bitbucket.
bash
# Finalize without PR
ratchet tighten

# Finalize and create a pull request
ratchet tighten --pr

report

Generates a detailed markdown or PDF report of a completed run, including score breakdown, file changes, AI reasoning, and recommendations for next steps.

FlagDefaultDescription
--runlastRun ID to generate a report for. Defaults to the most recent run.
--formatmarkdownOutput format: markdown or pdf.
--outputstdoutOutput file path. Use -o report.md to write to file.
bash
# Generate markdown report for last run
ratchet report > improvements.md

# Generate PDF for a specific run
ratchet report --run run_k8s2x9m --format pdf -o report.pdf

# Inline markdown to stdout
ratchet report --run run_k8s2x9m

vision

Opens an interactive dependency graph visualization in your browser. Ratchet analyzes import/export relationships, module boundaries, and coupling to show you the architecture of your codebase.

FlagDefaultDescription
--staticfalseGenerate a static HTML file instead of launching a live server.
--focusFocus the graph on a specific module/package name.
--filterShow only nodes matching this pattern (regex).
--export-pdffalseExport the graph as a PDF instead of opening the browser.
--max-nodes500Maximum number of nodes to render (for large codebases).
--focus-hops2When using --focus, how many dependency hops to include.
bash
# Interactive dependency graph
ratchet vision

# Focus on a specific module with 3 hops
ratchet vision --focus auth-service --focus-hops 3

# Static HTML for sharing
ratchet vision --static -o graph.html

# Export PDF
ratchet vision --export-pdf -o architecture.pdf

# Large codebase: limit nodes
ratchet vision --max-nodes 300

badge [dir]

Generates a shields.io badge URL for embedding in your README. The badge reflects the current score category (A/B/C/D/F) and color-codes it.

bash
# Generate badge URL for current project
ratchet badge

# Generate badge for a subdirectory
ratchet badge ./packages/api

# Output:
# https://img.shields.io/badge/ratchet-B%20(79)-00d4ff?style=flat-square

Embed in your README:

markdown
![Ratchet Score](https://img.shields.io/badge/ratchet-B%20(79)-00d4ff?style=flat-square)

build

Rebuilds the Ratchet CLI binary from source. Useful when you've modified Ratchet's core or are running from the git repository. Downloads the latest runner and recompiles the native binary.

bash
ratchet build

login & logout

Authenticate with your Ratchet account or clear stored credentials.

bash
ratchet login your-api-key-here
ratchet logout

Environment variable: Set RATCHET_API_KEY to authenticate without storing credentials on disk. Useful for CI environments and containers.

Configuration (.ratchet.yml)#
Full annotated reference for every configuration option.

The .ratchet.yml file lives in your project root. Run ratchet init to generate a starter, then customize.

Complete Example

.ratchet.yml
# =============================================================================
# Ratchet Configuration — Full Reference
# =============================================================================

# --- Agent & Model Settings ---
agent:
  # The AI model provider to use for improvement cycles.
  # Options: openai, anthropic, ollama, azure, google
  provider: anthropic

  # Model name. Must be available for the selected provider.
  model: claude-sonnet-4-6

  # Temperature for generation (0.0 = deterministic, 1.0 = creative)
  temperature: 0.3

  # Maximum tokens per response (affects context window usage)
  max_tokens: 8192

  # Base URL for self-hosted / proxy providers
  # base_url: https://api.openai.com/v1

# --- Global Defaults ---
defaults:
  # Default number of improvement clicks per torque/improve run
  clicks: 7

  # Shell command to run tests. Ratchet verifies this passes after each click.
  # Empty string disables test gating.
  test_command: "npm test"

  # Auto-commit changes after each click (default: false — manual review mode)
  auto_commit: false

  # Default guard profile for new runs
  guard_profile: refactor

  # Default scope mode
  scope: diff

  # Timeout per click in seconds (0 = no timeout)
  timeout: 300

  # Fail the run if tests fail after any click
  fail_on_test: true

  # Skip CI checks (for local runs)
  skip_ci: false

# --- Targets ---
targets:
  # Define multiple scopes within the same repository.
  # Each target can be scoped to a subdirectory or feature area.

  - name: api
    path: ./src/api
    description: "REST API layer — controllers, routes, middleware"
    guard_profile: tight
    scope: staged

  - name: core
    path: ./src/core
    description: "Core business logic and domain models"
    guard_profile: refactor

  - name: full
    path: ./
    description: "Full codebase improvement"
    guard_profile: broad
    scope: diff

# --- Boundaries ---
boundaries:
  # Hard constraints that Ratchet will never cross.

  - path: "./node_modules/**"
    rule: no-modify
    reason: "Third-party code — never modify"

  - path: "./dist/**"
    rule: no-modify
    reason: "Build output — generated files"

  - path: "./src/**/*.test.ts"
    rule: preserve-pattern
    reason: "Test files must retain their structure for IDE integration"

  - path: "./src/migrations/**"
    rule: no-delete
    reason: "Database migrations are immutable once merged"

  - path: "./config/secrets.*"
    rule: no-modify
    reason: "Secret files — never touch"

  - path: "./generated/**"
    rule: preserve-pattern
    reason: "Auto-generated code — modify source, not generated output"

# Valid rule types:
#   no-modify     — Ratchet will not edit files matching this path
#   preserve-pattern — Ratchet will not change file structure, only contents
#   no-delete     — Ratchet will not delete files matching this path

# --- Guard Profiles (inline overrides) ---
# Guard profiles control how many files/lines Ratchet can touch per click.
# You can reference named profiles or define them inline:

guards:
  # Named reference
  profile: refactor

  # Or inline definition:
  inline:
    max_files_per_click: 5
    max_lines_per_file: 80
    allow架构_refactors: true
    allow_new_files: true
    allow_delete: false

# --- Score Thresholds ---
thresholds:
  # Minimum score to consider a run "successful"
  target_score: 85

  # Fail categories below these scores
  fail_on_category:
    testing: 60
    security: 75
    error_handling: 50

# --- Notifications ---
notifications:
  # Post run summary to GitHub PR
  github_pr_comment: true

  # Post to Slack webhook
  slack_webhook: null   # set to your Slack webhook URL

  # Emit CI status checks
  ci_status: true

# --- Advanced ---
advanced:
  # Parallel clicks (experimental — default: 1)
  parallel_clicks: 1

  # Enable architect-level analysis (import graphs, coupling)
  architect_enabled: true

  # Cache analysis between runs (faster subsequent runs)
  cache_enabled: true

  # Custom file extensions to scan
  extensions:
    - .ts
    - .tsx
    - .js
    - .jsx
    - .py
    - .go
    - .rs

  # Files/folders to always exclude from analysis
  exclude:
    - "**/node_modules/**"
    - "**/dist/**"
    - "**/build/**"
    - "**/.git/**"
    - "**/*.test.*"
    - "**/*.spec.*"
    - "**/__tests__/**"

Configuration Precedence

Ratchet resolves config in this order (later overrides earlier):

  1. Built-in defaults (hard-coded)
  2. Project .ratchet.yml in project root
  3. User-level ~/.ratchet/config.yml
  4. Environment variables (RATCHET_*)
  5. CLI flags (highest precedence)

Environment Variables

VariableDescription
RATCHET_API_KEYAPI key for authentication (overrides stored credentials)
RATCHET_CONFIGPath to a custom config file
RATCHET_MODELDefault model override
RATCHET_NO_CACHESet to 1 to disable caching
RATCHET_LOG_LEVELDebug logging: debug, info, warn, error
Scoring System#
How Ratchet evaluates and scores your codebase across 6 weighted categories.

Score Overview

The Ratchet Score is a 0–100 weighted composite of 6 categories. Higher is better. Scores ≥ 90 are A, 80–89 is B, 70–79 is C, 60–69 is D, and below 60 is F.

Testing
25 pts
Security
15 pts
Type Safety
15 pts
Error Handling
20 pts
Performance
10 pts
Code Quality
15 pts

Category Breakdown

Testing (25 points)

Measures test coverage, edge case handling, and test quality.

SubcategoryMax PtsChecks
Coverage10Lines/functions covered by tests vs. total
Edge Cases8Null/undefined inputs, boundary conditions, error paths
Test Quality7Use of assertions over conditionals, no flaky sleeps

Security (15 points)

Detects common vulnerabilities and insecure patterns.

SubcategoryMax PtsChecks
Input Validation5SQL injection, XSS, command injection patterns
Auth/Authz4Missing auth checks, hardcoded secrets, weak crypto
Dependency Health3Known CVEs in package dependencies
Secrets Management3API keys, tokens, credentials in source

Type Safety (15 points)

Measures how well your codebase uses type systems to prevent runtime errors.

SubcategoryMax PtsChecks
Type Coverage7Percentage of code with explicit type annotations
Strict Mode4strictNullChecks, noImplicitAny enabled
Discriminated Unions2Use of exhaustive type unions over loose enums
Generics Usage2Appropriate use of generics over any types

Error Handling (20 points)

Evaluates how gracefully your code handles and reports failures.

SubcategoryMax PtsChecks
Try/Catch Coverage8Async operations, external I/O wrapped in error handlers
Error Propagation5Errors not silently swallowed, meaningful error messages
Fallback Behavior4Graceful degradation, circuit breakers, retry logic
Centralized Error Format3Consistent error response structures

Performance (10 points)

Identifies common performance anti-patterns.

SubcategoryMax PtsChecks
Query Efficiency4N+1 queries, missing indexes, full scans
Memory Patterns3Memory leaks, unbounded collections, large allocations
Async/Await Usage3Sequential awaits that could be parallel

Code Quality (15 points)

General code cleanliness, maintainability, and best practices.

SubcategoryMax PtsChecks
DRY / Duplication5Repeated logic, copy-paste patterns
Naming & Clarity4Descriptive names, consistent conventions
Function Size3Functions within 50 lines, no god functions
Dead Code3Unused exports, unreachable code, commented-out blocks

Score Calculation

Each subcategory score is normalized to its point maximum, then summed. The final score is:

formula
total_score = (
  (testing_score / 25) * 100 * 0.25 +
  (security_score / 15) * 100 * 0.15 +
  (type_safety_score / 15) * 100 * 0.15 +
  (error_handling_score / 20) * 100 * 0.20 +
  (performance_score / 10) * 100 * 0.10 +
  (code_quality_score / 15) * 100 * 0.15
)

# Final score: 0–100 (rounded to 1 decimal)

Score History

Ratchet stores score history in ~/.ratchet/history/. Each run logs a timestamped score snapshot so you can track improvement over time. View it with:

bash
ratchet scan --output-json | jq '.score_history'
Guard Profiles#
Control how aggressively Ratchet modifies files per improvement click.

Guard profiles are Ratchet's safety system. They define hard limits on how many files can be modified per click and how many lines can be changed — preventing a single click from rewriting your entire codebase.

Profile Comparison

ProfileMax Files/ClickMax Lines/FileBest For
tight340Production, sensitive codebases, PRs
refactor (default)580General improvement, most projects
broad10150Greenfield, large refactors
atomic120Maximum safety, surgical changes only

Profile Details

Tight

The most conservative profile. Designed for production codebases where stability is paramount. Maximum 3 files and 40 lines changed per click. Ideal for CI runs on main or critical modules.

yaml
guards:
  profile: tight
# Equivalent inline:
# max_files_per_click: 3
# max_lines_per_file: 40
# allow_new_files: false
# allow_delete: false

Refactor (Default)

Balanced between safety and productivity. Allows up to 5 files and 80 lines per click. This is the default and recommended profile for most projects.

yaml
guards:
  profile: refactor

Broad

For large refactoring tasks or greenfield projects. Allows up to 10 files and 150 lines per click. Use with --plan-first to review before execution.

yaml
guards:
  profile: broad

Atomic

Maximum safety. One file, up to 20 lines changed. Each change is reviewed before the next. Useful for running Ratchet as a reviewer alongside human approval.

yaml
guards:
  profile: atomic

Smart Guard Escalation

By default, Ratchet employs smart escalation: if a click succeeds (tests pass, no boundary violations), the next click may slightly increase its scope budget — but never beyond the defined profile maximum. This lets Ratchet "warm up" while staying within your safety limits.

Smart escalation only broadens per-click scope incrementally. Ratchet will never escalate past the profile's hard maximums. Disable with --no-escalate or --no-guard-escalation if you need strict constant limits.

bash
# Disable escalation — all clicks stay at tight limits
ratchet torque --guards tight --no-escalate

# Disable escalation via config
guards:
  profile: refactor
  auto_escalate: false

Disabling Guards

You cannot fully disable guards — they are a core safety mechanism. However, broad profile with a high click count provides the most expansive improvement surface while still maintaining basic scope limits.

🚫

Never run torque without guards in production. The guard system is what prevents Ratchet from making uncontrolled mass changes. Use --plan-first to review all changes before they execute.

Scope Locking#
Control exactly which files Ratchet can touch using Git-aware scoping.

Scope locking ensures Ratchet only modifies files within your intended change boundary. This prevents AI agent "hallucination drift" — where an agent might wander into unrelated parts of the codebase. All scopes are Git-aware and validated against your repository state.

Scope Modes

diff (Default)

Only touches files that have uncommitted changes in the current working tree. Ideal for in-progress work where you want Ratchet to improve what you're already touching.

bash
ratchet torque --scope diff

branch

Scopes to all files changed on the current branch compared to main (or your default branch). Useful for reviewing all changes in a feature branch before merging.

bash
ratchet torque --scope branch

staged

Only touches files that are currently staged in Git (git add). Excellent for PR workflows: stage the files you want improved, then run Ratchet on exactly those.

bash
# Stage files you want improved
git add src/api/*.ts

# Run Ratchet on staged changes
ratchet torque --scope staged

glob

Scope to files matching a glob pattern. Ratchet will only touch files matching the pattern, regardless of their Git status.

bash
# Only TypeScript files in src/
ratchet torque --scope "glob:src/**/*.ts"

# Only test files
ratchet torque --scope "glob:**/*.test.ts"

# Only files in the utils directory
ratchet torque --scope "glob:src/utils/**"

file:paths

Explicit list of file paths. Ratchet will only touch those exact files. Paths are comma-separated.

bash
ratchet torque --scope "file:src/auth/login.ts,src/auth/logout.ts,src/auth/session.ts"

# Alias (no "file:" prefix also works)
ratchet torque --scope "src/auth/login.ts,src/auth/logout.ts"

Git-Aware Enforcement

Ratchet validates scopes against Git state at the start of each click. If the Git working tree changes (e.g., a git checkout mid-run), Ratchet pauses and asks for confirmation before continuing.

Branch protection: When connected to GitHub/GitLab, Ratchet automatically detects protected branches and applies tight guards + staged scope on protected branches, even if a broader scope is configured.

Scope in Configuration

Set default scope per target in .ratchet.yml:

yaml
targets:
  - name: api
    path: ./src/api
    scope: staged      # default scope for this target
    guard_profile: tight

  - name: full
    path: ./
    scope: diff        # default scope
    guard_profile: refactor
CI/CD Integration#
Run Ratchet in GitHub Actions, GitLab CI, and other CI systems with proper exit codes and badge generation.

GitHub Actions

Ratchet integrates with GitHub Actions using ratchet scan --fail-on --output-json. The JSON output parses cleanly into step summaries.

Basic Setup

Add this workflow to .github/workflows/ratchet.yml:

.github/workflows/ratchet.yml
name: Ratchet Code Quality

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  ratchet:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

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

      - name: Install Ratchet
        run: npm install -g ratchet-run

      - name: Run Ratchet scan
        env:
          RATCHET_API_KEY: ${{ secrets.RATCHET_API_KEY }}
        run: |
          ratchet scan \
            --fail-on 80 \
            --fail-on-category "security=70" \
            --fail-on-category "testing=60" \
            --output-json | tee ratchet-report.json

      - name: Upload Ratchet Report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: ratchet-report
          path: ratchet-report.json

      - name: Add Ratchet Badge to PR
        if: github.event_name == 'pull_request'
        run: |
          BADGE_URL=$(ratchet badge --output-url)
          echo "::set-output name=badge::$BADGE_URL"
        id: badge

      - name: Post Ratchet Score Comment
        if: github.event_name == 'pull_request'
        uses: actions/github-script@v7
        with:
          script: |
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: '## Ratchet Score\n\n' +
                '🤖 Ratchet has analyzed this PR. View the full report in the artifacts.\n\n' +
                '![Ratchet](' + process.env.BADGE_URL + ')'
            })

Improve on Merge to Main

Only run autonomous improvement on merges to main, not on every PR:

.github/workflows/ratchet-torque.yml
name: Ratchet Torque

on:
  push:
    branches: [main]

jobs:
  torque:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

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

      - name: Install Ratchet
        run: npm install -g ratchet-run

      - name: Run Torque
        env:
          RATCHET_API_KEY: ${{ secrets.RATCHET_API_KEY }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          ratchet torque \
            --guards refactor \
            --clicks 7 \
            --scope branch \
            --pr

      - name: Tighten & Finalize
        env:
          RATCHET_API_KEY: ${{ secrets.RATCHET_API_KEY }}
        run: ratchet tighten --pr

Exit Codes

Exit CodeMeaning
0Success — score above threshold, all checks passed
1Failure — score below --fail-on threshold or category failed
2Error — Ratchet encountered an error (missing API key, bad config, etc.)
3Guard violation — click exceeded guard limits and was reverted
4Tests failed — test_command returned non-zero after a click
5Timeout — click exceeded the --timeout limit

Badge Generation in CI

Use ratchet badge to generate a dynamic shields.io URL from CI, then use it in your README or PR comments:

bash
# Get the badge URL (returns JSON with url field)
ratchet badge --json

# Example output:
# {"url":"https://img.shields.io/badge/ratchet-B%20(82)-00d4ff?style=flat-square","grade":"B","score":82}

GitLab CI

.gitlab-ci.yml
ratchet_scan:
  image: node:20-alpine
  variables:
    RATCHET_API_KEY: $RATCHET_API_KEY
  script:
    - npm install -g ratchet-run
    - ratchet scan --fail-on 80 --output-json | tee ratchet-report.json
  artifacts:
    reports:
      json: ratchet-report.json
    when: always
    paths:
      - ratchet-report.json
Pricing#
Plans for individuals, startups, teams, and enterprises.
Free
Free
$0/mo

Forever free. No credit card required.

  • scan
  • badge
  • status
  • log
  • report
  • vision
  • 1 target
Builder
Builder
$9/mo$86/yr (save 20%)

For individual developers improving personal projects.

  • Everything in Free
  • 30 cycles/mo
  • improve command
  • 5 targets
  • All guard profiles
  • Email support
Team
Team
$49/mo$470/yr (save 20%)

For small teams moving fast on shared codebases.

  • Everything in Pro
  • 500 cycles/mo
  • 5 seats included
  • Shared team config
  • Team analytics
  • Slack notifications
  • Dedicated support
Enterprise
Enterprise
Custom

Unlimited everything. White-glove onboarding.

  • Everything in Team
  • Unlimited cycles
  • Unlimited seats
  • Self-hosted runner
  • Custom model providers
  • SLA guarantee
  • Custom contract & invoicing

What's a "Cycle"?

A cycle is one complete ratchet improve run or one ratchet torque run — regardless of how many clicks are in it. If you run ratchet torque --clicks 7, that counts as 1 cycle.

Cycle Tracking

Check your cycle usage at any time:

bash
ratchet status
# Cycles used this month: 23 / 150 (Pro)
# Resets in 11 days

Need More Cycles?

Add cycle top-ups at any time (billed per-use, no commitment):

bash
# Buy 10 extra cycles
ratchet buy --cycles 10

# Upgrade plan
ratchet upgrade --plan pro

Annual billing saves 20% across all plans. scan, vision, badge, status, log, and report are free forever. See full pricing at ratchetcli.com.