← 开源

Typecheck your skills. Turn CLAUDE.md, AGENTS.md, and SKILL.md guardrails into deterministic rules across coding-agent harnesses.

Rust
增长势头
+024 小时新增 Star0.0%
400
Star
26
Fork
5
贡献者
创建于 2026-11-28 · 更新于 2026-12-05 · 今日第 24453 名
主要开发者
itsthecsguyKazuyoshiAkiyamakruschdev
README

Ratchet

Typecheck your skills. Turn CLAUDE.md, AGENTS.md, and SKILL.md guardrails into deterministic rules that lint in milliseconds and enforce at tool-call time (~1.8 ms) — across every coding agent you use.

  • Typecheck skills (ratchet lint) — catches bad frontmatter (E006), dead globs (W108), unchecked claims (W102), stale paths/scripts/symbols/env vars (W103), broken links (W105), and cross-file or lockfile contradictions (E005, W106) in ~36 ms on a 35k-file repo.
  • Enforce deterministically (~1.8 ms) — blocks forbidden shell commands, shell/tool file writes (including pre-write pattern: content scans), reads of protected files through the read tool and the usual shell readers (when: read), MCP/tool calls (when: tool), diff/command checks (check: { command: ... }), and skipped test runs before they happen, with opt-in on_opaque and fail_closed hardening.
  • Zero lock-in, zero API keys — single ~4 MB Rust binary, offline by default, works with ordinary markdown files and 9 coding-agent harnesses + Git pre-commit + CI.
## pnpm-only
Always use pnpm. Never use npm, npx or yarn.

```rule
when: run
level: enforce
deny: npm *, npx *, yarn *
use:  npx => pnpm dlx {{args}}
say:  This repo uses pnpm; {{program}} would write a second lockfile.
ok:   pnpm install
bad:  npm install
```

How It Works

No LLM is involved in enforcement. Ratchet hooks directly into your coding agent's native lifecycle hooks (PreToolUse, PostToolUse, Stop):

  Your CLAUDE.md / AGENTS.md / SKILL.md
                  │
                  ▼  ratchet setup (compiles rules + wires native hooks)
  Agent tries: Bash("npm test")
                  │
                  ▼  harness pauses BEFORE execution and pipes JSON to `ratchet`
  ratchet (4 MB Rust binary, ~1.8 ms, 100% offline, zero API calls)
    • lexes the shell command deterministically (including `sh -c`, `cmd /c`, `pwsh -Command`, pipes, redirects, `git -C`, env prefixes)
    • matches against your rules -> returns `deny` + `fix: pnpm test`
                  │
                  ▼  command never executes; harness hands the error back to the model
  Agent self-corrects: Bash("pnpm test") -> allowed

Rules support four enforcement levels (shadow < warn < ask < enforce):

  • enforce (default): blocks violations before execution and gives the agent a concrete fix: command. Need a one-time exception without turning the rule off? Run ratchet approve (or !ratchet approve in Claude Code) to allow that exact command once.
  • ask: pops the harness's native interactive [Allow once / Deny] confirmation prompt on Claude Code and Cursor (and falls back to deny + ratchet approve on binary allow/deny harnesses).
  • warn: shows a user-visible warning without blocking.
  • shadow: logs hits silently so you can measure before enforcing.

Quickstart

Install & Update

# Homebrew (macOS & Linux, prebuilt release binary):
brew install itsthecsguy/tap/ratchet

# cargo-binstall (prebuilt release binary, no compile):
cargo binstall ratchet-cli

# crates.io (build from source, Rust 1.82+):
cargo install ratchet-cli

# Prebuilt release binary via installer (Linux x86_64/arm64, macOS arm64/x86_64, SHA-256 verified):
curl -fsSL https://raw.githubusercontent.com/itsthecsguy/ratchet/main/scripts/install.sh | sh

# Windows PowerShell installer (x86_64, SHA-256 verified):
irm https://raw.githubusercontent.com/itsthecsguy/ratchet/main/scripts/install.ps1 | iex

# Update anytime to the latest release (SHA-256 verified, atomic swap):
ratchet update

1. Typecheck your existing skills

$ ratchet lint
CLAUDE.md:3:3: warning[W102]: unchecked claim: "Always use `pnpm`, never `npm` or `yarn`."
  hint: enforceable as `pnpm-only` (when: run / deny: npm, npx, yarn)
CLAUDE.md:5:21: warning[W105]: broken link `docs/legacy-auth.md` does not exist
  hint: fix the path or remove the broken link/include

Claim split: 1 enforceable (deterministic hooks), 2 prose/judgment (keep as prose; eval with `ratchet test --models`).
0 rules, 0 examples run, 1 unchecked claim, 0 stale references, ~41 always-loaded tokens.

2. One-command setup (enforces by default)

$ ratchet setup
Detected: 1 guidance file · pnpm · harnesses: claude (CLAUDE.md)
Audit: 0 historical hits across 0 commits and 0 sessions.
Install 6 new rules (enforce) and sync hooks for claude?
  [Enter] enforce  [w] warn  [s] shadow  [n] abort >
Wrote 6 rules to .ratchet/checks.yaml (enforce).
Setup complete: 6 rules installed (enforce), 37 fixtures passed, hooks synced for claude.
Enforcing by default. Downgrade any rule: `ratchet demote <id> --to warn|shadow --reason "..."` (or `ratchet wrong <id>` to mute locally).

Pass --level warn or --level shadow for non-blocking rollout, --inline to embed ```rule blocks directly into markdown, and --git-hook --ci to wire pre-commit and GitHub Actions.

3. Dry-run any command or file write

$ ratchet try "npm install lodash"
  enforce  pnpm-only  This repo uses pnpm; npm would write a second lockfile.
    fix: pnpm install lodash
deny (dry-run — would block tool call; command not executed; 1 rule matched: 1 enforce · 0 warn · 0 shadow)

$ ratchet try "pnpm add lodash"
allow (no rules matched) [dry-run — command not executed]

Supported Harnesses

ratchet setup and ratchet sync auto-detect harnesses in your repo or on PATH (or target explicitly with --harness <name|all>). Ratchet-created hook files are locally excluded in .git/info/exclude and cleanly removed by ratchet uninstall.

Harness (--harness) Hook / Plugin File PreToolUse PostToolUse Stop / Finish test --models
Claude Code (claude) .claude/settings.local.json Deny / Warn Yes Block claude[:model][@effort]
Antigravity (antigravity, agy) .agents/hooks.json Deny Yes Continue agy[:model]
Codex CLI (codex) .codex/hooks.json Bash + apply_patch Yes Block codex[:model][@effort]
Cursor (cursor) .cursor/hooks.json Shell + Write Yes Follow-up cursor[:model]
Gemini CLI (gemini) .gemini/settings.json Deny / Warn Yes AfterAgent gemini[:model]
Amp (amp) .amp/plugins/ratchet.ts tool.call tool.result agent.end amp[:model|smart|rush]
GitHub Copilot CLI (copilot) .github/hooks/ratchet.json Deny Yes agentStop copilot[:model]
OpenCode (opencode) .opencode/plugins/ratchet.ts tool.execute.before tool.execute.after ratchet check / CI* opencode[:provider/model]
Windsurf (windsurf) .windsurf/hooks.json Deny (exit 2) post_run_command ratchet check / CI* .ratchet/models.yaml

*OpenCode and Windsurf enforce pre/post tool calls natively; finish/commit rules run via ratchet check and CI. Any custom LLM CLI can be added via .ratchet/models.yaml.


How Ratchet Works (FAQ)

  • Block or warn? Ratchet enforces by default out of the box (hedged sentences like "prefer pnpm" stay capped at warn). Choose [w] warn or [s] shadow interactively during ratchet setup (or pass --level warn|shadow), lower any rule later with ratchet demote <id> --to warn|shadow --reason "...", mute locally in one command with ratchet wrong <id>, or pause hooks with RATCHET=0 / ratchet off.
  • What does the agent see on a block? A structured reason (≤ 600 bytes) with the blocked command/path, rule ID, verbatim quote from your guidance file, and a concrete fix: command so it self-corrects immediately. If a model retries the same denied action in the same session, Ratchet escalates (Blocked again (attempt #N)... Do not retry) to break retry loops.
  • Fixed parser or LLM? Setup and linting are 100% deterministic and offline (zero API keys). For custom repo-specific prose rules beyond built-in templates, pipe into any agent CLI you already have and back into Ratchet's deterministic fixture verifier:
    ratchet propose --prompt | claude -p | ratchet propose --stdin
  • Deterministic rules vs. subjective prose? Shell actions (when: run), protected writes (when: write, including shell write targets like > .env / tee / sed -i and optional pattern: content scans), reads of protected files (when: read: the read tool, and cat / head / grep / source / < file and similar in the shell; the hook reads the command's text, so a shell wildcard, an earlier cd, an interpreter such as python -c, or a recursive search is not followed), MCP/generic tool calls (when: tool), diff/command checks (when: commit, check: { command: ... }), and test freshness (when: finish) enforce deterministically in ~1.8 ms. Add on_opaque: ask|deny or fail_closed: true on high-stakes rules for strict fail-closed handling. Subjective taste stays plain prose; ratchet lint separates the two explicitly, and ratchet test --models benchmarks real models on prose scenarios offline.
  • Small context window (local models)? Keep the rules in .ratchet/checks.yaml instead of inline ```rule blocks. The agent never reads that file, so the hooks enforce the same rules in the same few milliseconds with no prompt tokens spent on them. It also holds diff checks such as check: { diff: { modified_or_deleted: true } } for files that must not change (pinned benchmarks, shipped migrations). See docs/GUIDE.md and examples/ts-service/.ratchet/checks.yaml.
  • Does it catch contradicting rules? Yes — E005 catches rule/example/fix:/finish conflicts and W106 catches cross-file and lockfile contradictions (pnpm/npm, uv/poetry, vitest/jest, biome/eslint, pytest/unittest, ruff/flake8). ratchet git-hook install also runs ratchet lint on staged guidance files in git pre-commit.

Commands

Command Purpose
ratchet setup [--level enforce|ask|warn|shadow] [--inline] [--git-hook] [--ci] [--yes] One-command onboarding: audit, install rules, sync hooks, run fixture self-test.
ratchet sync [--harness <NAME>] [--shared] Write or refresh harness hooks (--shared writes commit-safe hooks with graceful missing-binary fallback for Claude Code, Cursor, Codex, Windsurf, and Gemini CLI).
ratchet lint [PATH...] [--fix [--rules]] [--strict] [--all] [--json] Typecheck skills (E001–E006, W101–W108) including frontmatter, dead globs, stale symbols/env vars, and auto-fix.
ratchet try [--write <PATH> [--content <TEXT>] | --read <PATH> | --tool <NAME> [--args <JSON>]] [--json] [COMMAND] Instant dry-run (~2 ms) against loaded rules (including shell write targets and on_opaque) without executing anything.
ratchet propose --prompt | --stdin | --file <PATH> [--level ...] Generate an LLM rule prompt or deterministically verify and install candidate rules.
ratchet test [--models <spec,...> --runs N --enforce] Run inline ok:/bad: fixtures or benchmark scenarios against real coding agents.
ratchet add --list | <pack> [--inline] [--level ...] Install curated starter packs (git-hygiene, package-manager, secrets, ts-hygiene, etc.).
ratchet approve ["CMD"] [--write <PATH> | --read <PATH> | --tool <NAME>] [--ttl 2m] [--uses 1] [--list | --clear] Allow one blocked command, file write/read, or tool call once without turning the rule off; the agent cannot run it. With no arguments it approves the last blocked call. Quote the command to put Ratchet's flags after it (ratchet approve "git push origin main" --uses 2); unquoted, every word after the first is the command.
ratchet update [--check] [--version <TAG>] [--force] [--json] Self-update Ratchet to the latest GitHub release (SHA-256 verified, atomic replacement).
ratchet status / ratchet audit / ratchet log / ratchet doctor [--fix] Inspect prevented mistakes, self-correction rate (overall & direct retries), historical violations, events, and hook health.
ratchet promote <id> / ratchet demote <id> --to ask|warn|shadow --reason "..." / ratchet wrong <id> Raise, lower (ask prompts interactively on Claude Code & Cursor), or locally mute a rule.
ratchet git-hook install / ratchet ci init / ratchet check --ci | --staged Pre-commit linting/checks (also exposed via .pre-commit-hooks.yaml for pre-commit & prek), GitHub Actions workflow, and anti-weakening PR verification.

Documentation & Development

  • Full Guide & Internals: docs/GUIDE.md — rule keys, all lint codes, .ratchet/models.yaml, hook latency benchmarks, shell parsing, and freshness detection.
  • Rule Format Specification: docs/SKILL-FORMAT.md
  • Code Architecture: ARCHITECTURE.md
cargo clippy --workspace --all-targets -- -D warnings
RUSTFLAGS="-D warnings" cargo test --workspace   # 736 unit & integration tests
cargo build --release                            # target/release/ratchet (~4 MB)
bash scripts/e2e.sh target/release/ratchet       # 549 end-to-end checks across all 9 harnesses

License

Licensed under the MIT License.

排名相邻

AI Rank iPhone 版

随时追踪 AI 模型榜单

在 App Store 下载