К основному содержанию
плагин

claude-crap — плагин для Claude Code: что делает и как установить

Плагин контроля качества для Claude Code. Проверяет код метриками сложности CRAP и TDR, блокируя опасные команды и закрытие задач с нарушениями.

MIT ★ 9 обновлён 2026-04-19

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add anthropics/claude-plugins-community
/plugin install claude-crap@claude-community
Открыть на GitHub

Что делает claude-crap

claude-crap встраивает детерминированный контроль качества в сессии Claude Code. Плагин перехватывает операции Write, Edit и Bash. Хук PreToolUse пресекает утечки секретов, деструктивные шелл-команды и выход за пределы путей, а PostToolUse предупреждает об отсутствии тестов или подавлении линтеров вроде @ts-ignore и eslint-disable.

На завершении задачи срабатывает хук Stop. Он считывает отчёты SARIF 2.1.0, вычисляет индекс риска CRAP и коэффициент техдолга TDR через встроенный MCP-сервер. В строгом режиме strict агент не сможет закрыть задачу, пока не доведёт качество до нормы. По умолчанию плагин работает в режиме warn, выводя вердикт без блокировки.

Для запуска плагина обязателен Node.js >= 20. Локальный дашборд поднимается на 127.0.0.1:5117, а настройки строгости можно зафиксировать для всей команды в файле .claude-crap.json.

Какие задачи решает

  • заблокировать деструктивные команды Bash и утечки секретов
  • выявить функции с высоким риском изменений по метрике CRAP
  • найти подавления проверок вроде eslint-disable и @ts-ignore
  • запретить закрытие задач при нарушении порогов техдолга

Примеры запросов агенту

  • Проверь цикломатическую сложность и метрику CRAP для функций в файле src/auth.ts
  • Запусти сканирование проекта и покажи общий рейтинг технического долга TDR
  • Вызови compute_crap и найди функции с недостаточным тестовым покрытием

Как установить claude-crap

Через маркетплейс плагинов

/plugin marketplace add anthropics/claude-plugins-community
/plugin install claude-crap@claude-community

По шагам, с командами для каждой платформы: Плагины Claude Code: маркетплейсы, установка и как собрать свой

Вопросы о claude-crap

Как установить claude-crap в Claude Code?

Выполните в терминале агента обе команды по очереди: сначала /plugin marketplace add anthropics/claude-plugins-community, а затем /plugin install claude-crap@claude-community.

Что делает claude-crap?

Плагин перехватывает вызовы инструментов Claude Code и проверяет правки кода через метрики CRAP и TDR, запрещая опасные операции и закрытие задач с дефектами.

Чем отличается режим strict от warn?

В стандартном режиме warn хук Stop показывает агенту найденные нарушения, но разрешает завершить сессию, а при значении strict в .claude-crap.json плагин возвращает код 2 и блокирует закрытие задачи.

Исходный текст

plugin · MIT
# claude-crap

[![npm version](https://img.shields.io/npm/v/claude-crap.svg)](https://www.npmjs.com/package/claude-crap)
[![CI](https://github.com/ahernandez-developer/claude-crap/actions/workflows/ci.yml/badge.svg)](https://github.com/ahernandez-developer/claude-crap/actions/workflows/ci.yml)
[![Node.js](https://img.shields.io/badge/node-%3E%3D20-brightgreen.svg)](https://nodejs.org/)
[![Bun](https://img.shields.io/badge/bun-%3E%3D1-black.svg)](https://bun.sh/)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)

> **Deterministic Quality Assurance plugin for Claude Code.**
> Forces the agent through mathematical hooks, CRAP / TDR thresholds,
> and SARIF 2.1.0 reports before a single line of code is allowed to
> ship.

`claude-crap` turns Claude Code into a disciplined QA engineer. It
wraps every `Write`, `Edit`, and `Bash` call with a synchronous
**PreToolUse gatekeeper**, a retrospective **PostToolUse verifier**,
and a final **Stop quality gate** that refuses to close a task until
maintainability, reliability, and security ratings pass policy.

Every decision that touches source code must be backed by a result
from the deterministic MCP engines — `compute_crap`, `compute_tdr`,
`analyze_file_ast`, `ingest_sarif`, `score_project`, and others.
This is the **Fat Platform / Thin Agent** thesis: the LLM is an
efficient worker, but the rails are mathematical and outside the
model's reach.

> **CRAP** stands for **Change Risk Anti-Patterns** — a metric
> originally developed by Alberto Savoia and Bob Evans at Google (2007).
> [Read the original post.](https://testing.googleblog.com/2011/02/this-code-is-crap.html)

[Quick Start](#quick-start) · [Configuration](#configuration) · [How It Works](#how-it-works) · [MCP Tools](#mcp-tools) · [Documentation](#documentation) · [Contributing](#contributing)

---

## Quick Start

```bash
npx claude-crap install
```

This downloads the package, compiles `dist/` from source, creates
`.claude-crap/reports/` in your project, and prints the Claude Code
command to register the plugin:

```
  Next steps — pick ONE of the following:

  1. Native install:
       /plugin install /.../claude-crap

  2. Marketplace install:
       /plugin marketplace add https://github.com/ahernandez-developer/claude-crap
       /plugin install claude-crap@herz
```

Once registered, open any new session. The **SessionStart** hook
prints a briefing with thresholds and the dashboard URL. From that
point the PreToolUse gatekeeper and Stop quality gate run
automatically — no further setup required.

---

## Configuration

> **Default: `warn`.** No config file needed. The Stop gate
> shows all violations but lets tasks close. Teams that want
> hard enforcement can set `"strict"` in `.claude-crap.json`.

The `strictness` value controls how the Stop gate reacts to failures:

| Mode       | Stop exit | Effect                                                         |
| :--------- | :-------: | :------------------------------------------------------------- |
| `strict`   |    `2`    | Task cannot close until rules pass.                            |
| `warn`     |    `0`    | Full verdict visible to agent, but task closes. **Default.**   |
| `advisory` |    `0`    | Single-line nudge only.                                        |

Override per workspace:

```jsonc
// .claude-crap.json — commit to git for team-wide policy
{
  "strictness": "strict"
}
```

Or per session: `CLAUDE_CRAP_STRICTNESS=strict claude`

**Precedence:** env var > `.claude-crap.json` > hardcoded `warn`.

See [docs/quality-gate.md](./docs/quality-gate.md) for the full
CRAP formula, TDR formula, letter ratings, and adoption strategy.

---

## How It Works

| Component | File | Role |
| :-------- | :--- | :--- |
| **PreToolUse gatekeeper** | `plugin/hooks/pre-tool-use.mjs` | Blocks sensitive paths, destructive Bash, hardcoded secrets, path traversal — `exit 2` injects the corrective message into the agent's context. |
| **PostToolUse verifier** | `plugin/hooks/post-tool-use.mjs` | Warns on missing test harness, suppression markers (`eslint-disable`, `@ts-ignore`, `# nosec`), and TODO/FIXME/HACK. |
| **Stop quality gate** | `plugin/hooks/stop-quality-gate.mjs` | Reads the SARIF store, computes CRAP / TDR / reliability / security ratings, and blocks task close if any metric is outside policy. |
| **MCP server** | `src/index.ts` | Stdio-transport server exposing CRAP, TDR, tree-sitter AST, and SARIF engines as deterministic tools. |
| **SARIF store** | `src/sarif/sarif-store.ts` | On-disk consolidated report with finding deduplication. Tolerates malformed entries so a tampered file can't DoS the boot. |
| **Scanner adapters** | `src/adapters/` | ESLint, Semgrep, Bandit, Stryker, `dart analyze`, `dotnet format` — each stamps `effortMinutes` for uniform TDR computation. |
| **Project map** | `src/monorepo/project-map.ts` | Auto-discovers monorepo sub-projects at boot, persists to `.claude-crap/projects.json`. |
| **Dashboard** | `src/dashboard/server.ts` | Fastify on `127.0.0.1:5117` serving a Vue 3 SPA. Offline-capable (vendored runtime). PID-based port management. |

All findings are normalized to **SARIF 2.1.0** — one vocabulary,
exact coordinates, no grep walls in the context window.

See [docs/architecture-overview.md](./docs/architecture-overview.md)
for the boot sequence, data flow, and design decisions.

---

## MCP Tools

Ten deterministic tools and two resources, all with strict JSON Schema validation.

| Tool | Purpose |
| :--- | :------ |
| `compute_crap` | CRAP index for a single function + block verdict against threshold. |
| `compute_tdr` | Technical Debt Ratio and A..E maintainability rating. |
| `analyze_file_ast` | Tree-sitter AST metrics: LOC + per-function cyclomatic complexity. TypeScript, JavaScript, Python, Java, C#. |
| `ingest_sarif` | Merge a raw SARIF 2.1.0 document into the store with deduplication. |
| `ingest_scanner_output` | Route native scanner output through adapter, enrich with `effortMinutes`, persist as SARIF. Supports ESLint, Semgrep, Bandit, Stryker, `dart_analyze`, and `dotnet_format`. |
| `require_test_harness` | Check whether a source file has an accompanying test file. |
| `score_project` | Aggregate workspace into A..E grades. Optional `scope` parameter to score a single monorepo sub-project. |
| `auto_scan` | Auto-detect scanners (including monorepo subdirectories), run them, ingest findings. |
| `bootstrap_scanner` | Detect project type, install the right scanner, configure, and verify. |
| `list_projects` | List all discovered monorepo sub-projects with type, scanner, and availability. |

| Resource | Description |
| :------- | :---------- |
| `sonar://metrics/current` | Live CRAP / TDR / rating snapshot. |
| `sonar://reports/latest.sarif` | Consolidated SARIF document. |

Full schemas, inputs, outputs, and examples in
[docs/mcp-tools.md](./docs/mcp-tools.md).

---

## System Requirements

- **Node.js >= 20** — the only runtime. No .NET, JDK, or Python.
- **Bun >= 1.0** also works (`bun run build`, `bun test`).
- **Claude Code** with local plugin support.
- **Zero native deps** — WASM-backed tree-sitter, no C compiler needed.

Windows: requires a POSIX shell (Git Bash or WSL).
See [CONTRIBUTING.md](./CONTRIBUTING.md) for Windows setup details.

---

## Supported Languages & Scanners

| Language | Extensions | AST analysis | Scanner | Setup |
| :------- | :--------- | :----------: | :------ | :---- |
| TypeScript | `.ts` `.tsx` `.mts` `.cts` | Cyclomatic complexity | ESLint | **Auto-installed** via npm |
| JavaScript | `.js` `.jsx` `.mjs` `.cjs` | Cyclomatic complexity | ESLint | **Auto-installed** via npm |
| Python | `.py` `.pyi` | Cyclomatic complexity | Bandit | `pip install bandit` |
| Java | `.java` | Cyclomatic complexity | Semgrep | `brew install semgrep` |
| C# / .NET | `.cs` | Cyclomatic complexity | `dotnet format` | **Included in .NET SDK** |
| Dart / Flutter | `.dart` | LOC only | `dart analyze` | **Included in Dart/Flutter SDK** |
| Vue | `.vue` | LOC only | ESLint (via root config) | Auto with TypeScript |
| Go | `.go` | LOC only | — | — |
| Rust | `.rs` | LOC only | — | — |
| Ruby | `.rb` | LOC only | — | — |
| PHP | `.php` | LOC only | — | — |
| Swift | `.swift` | LOC only | — | — |
| Kotlin | `.kt` | LOC only | — | — |
| Scala | `.scala` | LOC only | — | — |

**AST analysis** = tree-sitter cyclomatic complexity per function.
**LOC only** = counted toward workspace metrics but no per-function analysis.

### Monorepo auto-discovery

In monorepos, claude-crap automatically discovers sub-projects at
session startup — no per-project configuration needed. The plugin
probes npm workspaces and common directories (`apps/`, `packages/`,
`libs/`, `modules/`, `services/`) to build a **project map**:

```
Session start
  → discover project map
  → detect sub-projects by type (TypeScript, Dart, C#, Python, etc.)
  → install missing scanners (ESLint auto-installed via npm)
  → run each scanner from its project directory
  → aggregate all findings into one SARIF store
  → score_project ready with real data
```

The project map is persisted to `.claude-crap/projects.json` and
exposed via the `list_projects` MCP tool. Use `score_project` with
the optional `scope` parameter to score a single sub-project:

```ts
// Score only one sub-project
score_project({ format: "both", scope: "frontend" })
```

See [docs/supported-languages.md](./docs/supported-languages.md) for
detailed per-language setup and behavior.

**File exclusions** are centralized and cover all major frameworks
out of the box: `dist/`, `build/`, `bundle/`, `vendor/`,
`.next`, `.nuxt`, `.astro`, `.svelte-kit`, `.dart_tool`,
`.expo`, `.angular`, `.turbo`, and more. Custom exclusions can be
added via `.claude-crap.json`:

```jsonc
{
  "strictness": "strict",
  "exclude": ["apps/legacy/", "generated/", "*.proto.ts"]
}
```

---

## Documentation

| Section | Link |
| :------ | :--- |
| Supported languages & scanners | [docs/supported-languages.md](./docs/supported-languages.md) |
| Architecture & boot sequence | [docs/architecture-overview.md](./docs/architecture-overview.md) |
| Quality gate math (CRAP, TDR, ratings) | [docs/quality-gate.md](./docs/quality-gate.md) |
| Project score aggregation | [docs/scoring.md](./docs/scoring.md) |
| Hooks reference | [docs/hooks.md](./docs/hooks.md) |
| MCP tools & resources | [docs/mcp-tools.md](./docs/mcp-tools.md) |
| Scanner adapters | [docs/scanner-adapters.md](./docs/scanner-adapters.md) |
| SDK reference | [docs/sdk.md](./docs/sdk.md) |
| Contributing & dev loop | [CONTRIBUTING.md](./CONTRIBUTING.md) |
| Agent contract | [plugin/CLAUDE.md](./plugin/CLAUDE.md) |
| Changelog | [CHANGELOG.md](./CHANGELOG.md) |

---

## Bug Reports

```bash
npx claude-crap bug-report    # writes claude-crap-bug-report-<ts>.md
npx claude-crap bug-report --stdout
```

Collects plugin version, Node/npm/platform info, doctor output,
SARIF summary, and resolved env vars (secrets auto-redacted).
Review the output, then open an issue at
[github.com/ahernandez-developer/claude-crap/issues](https://github.com/ahernandez-developer/claude-crap/issues).

---

## Contributing

claude-crap welcomes PRs — **including AI-assisted ones.** The plugin is built
for AI-assisted development and dog-foods its own quality gate, so Codex /
Claude Code / Cursor / Copilot diffs are first-class contributions. All we ask
is transparency and the Golden Rule: **no production code without a test.**

Quick version:

1. Fork and branch off `main`.
2. **Write the test first** — the Golden Rule forbids code before a safety net.
3. Run `npm test` — full suite must stay green.
4. Open a PR using the [rigid deduction format](./plugin/CLAUDE.md) and
   describe the user-visible change in the PR body.
5. If AI-assisted, mark the PR and include the agent/model + testing level.

**Do not** bump the `package.json` version or edit `CHANGELOG.md` — version
bumps, release notes, and npm publishes are handled by the maintainer
([@ahernandez-developer](https://github.com/ahernandez-developer)) at release
time.

Full dev loop, test layout, coding conventions, release process, the
AI-assisted PR checklist, and security reporting are all in
[CONTRIBUTING.md](./CONTRIBUTING.md).

---

## License

MIT. See [LICENSE](./LICENSE). Copyright (c) 2026 Alan Hernandez.

© ahernandez-developer · MIT · ahernandez-developer/claude-crap

Похожие плагины

Все плагины по теме «Тесты и QA» →
principle-prove-it-works backnotprop Скилл principle-prove-it-works для Claude Code запрещает ассистенту закрывать задачу без проверки на реальном артефакте. Подключается перед сдачей работы. CX Codex +1 10 300установок tech-debt-tracker borghei Скилл tech-debt-tracker для Claude Code, Codex и Cursor находит технический долг в кодовой базе и выстраивает очередь на рефакторинг. Сканирует код и считает потери от откладывания правок на спринт. CX Codex +1 125установок quality-validation qodex-ai Скилл quality-validation запрещает ИИ-агенту заявлять о готовности задачи без свежих доказательств: запусков тестов, сборки или проверки диффа в Git. CX Codex +1 142установок pyscn ludo-technologies MCP-сервер pyscn анализирует архитектуру, дубликаты и сложность Python-кода прямо через агента. Пригодится при рефакторинге и поиске мёртвого кода в проекте. CX Codex +1 ★ 1 116звёзд репо crap-score dotnet Скилл crap-score считает метрику риска изменений CRAP для методов, классов и файлов в .NET. Помогает найти сложный код с недостаточным тестовым покрытием. CX Codex +1 4 600установок crap-analysis Aaronontheweb Скилл crap-analysis для Claude Code и других агентов вычисляет CRAP Score — риск изменения кода по формуле сложность × (1 - покрытие)². Запускается, когда нужно найти непокрытые тестами методы с высокой цикломатической сложностью. CX Codex +1 593установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой