К основному содержанию
скилл CX Codex

complexity-optimizer — скилл для Claude Code

Скилл complexity-optimizer находит узкие места алгоритмической сложности в коде и готовит отчёт с безопасными исправлениями.

MIT 156 установок ★ 227 обновлён 2026-08-15

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add pproenca/dot-skills --skill complexity-optimizer -a claude-code
Открыть на GitHub

Что делает complexity-optimizer

Скилл ищет неэффективные вложенные циклы, N+1 запросы к базам данных, лишние сортировки внутри итераций и пересчёты в путях рендеринга. Сначала запускается скрипт scripts/analyze_complexity.py для первичного сканирования. Для Python скрипт строит полное AST, а для остальных языков вроде Go, Rust или TypeScript использует регулярные выражения с эвристиками отступов.

По умолчанию скилл работает только на чтение. Он составляет структурированный отчёт с номерами строк, оценкой текущей сложности и предложениями по снижению до O(n) или O(n log n). Редактирование файлов запускается строго по прямому указанию пользователя. Перед правками агент фиксирует тесты на краевые случаи, чтобы исключить поломку существующего поведения.

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

  • найти скрытые N+1 запросы и вложенные циклы O(n^2)
  • составить отчёт по алгоритмической сложности кодовой базы
  • заменить линейные поиски в циклах на хеш-таблицы и сеты
  • убрать лишние повторные вычисления из путей рендеринга интерфейса

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

  • Просканируй репозиторий и найди самые тяжёлые алгоритмические участки
  • Составь отчёт по сложности для изменений в текущей ветке
  • Оптимизируй найденные циклы в файле и запусти тесты для проверки

Как установить complexity-optimizer

1Через Skills CLI (Vercel)

npx skills add pproenca/dot-skills --skill complexity-optimizer -a claude-code

2Вручную: положить файлы

~/.claude/skills/complexity-optimizer/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/complexity-optimizer/

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

Вопросы о complexity-optimizer

Как установить complexity-optimizer в Claude Code?

Выполните команду npx skills add pproenca/dot-skills --skill complexity-optimizer -a claude-code в терминале.

Что делает complexity-optimizer?

Он анализирует исходный код на наличие неэффективных алгоритмических конструкций и выдаёт отчёт с предложениями по оптимизации без изменения файлов.

Меняет ли скилл исходный код без спроса?

Нет, скилл работает в режиме чтения и правит файлы только при явных командах вроде «optimize» или «refactor».

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

SKILL.md · MIT
---
name: complexity-optimizer
description: Analyze a software codebase for algorithmic complexity and performance hotspots, then propose or implement safe optimizations without breaking behavior. Use when the user asks to scan many files, find inefficient loops, nested iteration, repeated scans, costly rendering/recomputation, N+1 queries, avoidable O(n^2) or O(n) operations, or reduce complexity such as O(n^2) to O(n log n) / O(n), while preserving tests, APIs, outputs, and maintainability.
---

# Complexity Optimizer

Find algorithmic complexity hotspots in a codebase and produce a structured report. Optionally implement low-risk optimizations after explicit consent.

## When to Apply

Use this skill when the user asks to:
- Analyze, audit, scan, or review a codebase for performance hotspots or algorithmic complexity
- Find inefficient loops, nested iteration, N+1 queries, sort-in-loop, render-path recomputation
- Reduce complexity (e.g. O(n^2) → O(n log n) or O(n))
- "Give me a report" on a codebase's complexity profile

Do not use this skill for:
- Micro-optimizations on cold code paths
- Memory tuning (this skill targets time complexity, not allocation profiles)
- Code style refactoring unrelated to complexity

## Workflow Overview

```
Baseline → Rank → Prove behavior → Optimize (opt-in) → Verify
   ↓           ↓                       ↓
 scanner   prioritize hot          rollback if
 + manual  paths & large I/O       tests regress
```

| Step | Action | Tool | Risk |
|------|--------|------|------|
| 1 | Establish baseline: detect stack, test command, hot paths | `scripts/analyze_complexity.py` + manual inspection | read-only |
| 2 | Rank opportunities by impact, separating algorithmic wins from constant-factor cleanup | reasoning | read-only |
| 3 | Locate or add tests covering the function/component | Read + test framework | read-only |
| 4 | Apply optimization (ONLY when user explicitly requests) | Edit/Write | destructive |
| 5 | Run tests, lint, type-check, and a benchmark when warranted; report before/after complexity | Bash test commands | read-only |

## Core Rule

Optimize only when current behavior is understood and can be preserved. Prefer a small, proven improvement with tests over a broad rewrite with unclear correctness.

## Default Behavior

When the user asks to analyze, scan, audit, review, or "give me a report" for a codebase, produce the full complexity report automatically. Do not require the user to specify report fields.

Default report contents (see `references/report-template.md`):

- Scope analyzed and detected stack/test commands
- Top findings ranked by likely impact
- File and line for each finding
- Current pattern and why it may be costly
- Estimated current complexity
- Recommended change and estimated complexity after
- Risk level
- Tests, benchmarks, or manual checks needed
- Clear statement that **no files were modified**, unless the user explicitly requested implementation

Only edit files when the user uses an explicit edit verb: **implement, fix, optimize, apply, change, refactor**. If the request is analysis-only or a report-only request, do not modify files.

## Workflow Detail

### 1. Baseline

- Identify language, framework, test command, build command, and performance-sensitive paths.
- Inspect existing tests before touching code.
- Run `python3 scripts/analyze_complexity.py <repo>` for a first-pass hotspot list when scanning a repository.

### 2. Rank

- Prioritize hot paths, large-input paths, rendering loops, database/API loops, shared utilities.
- Separate algorithmic complexity from constant-factor cleanup.
- Treat scanner output as leads, not proof.
- For report-only requests, inspect enough surrounding code to estimate current and proposed complexity. Do not stop at raw scanner output.

### 3. Prove behavior

- Locate or add focused tests for the function/component being changed.
- Capture edge cases: empty input, duplicates, ordering stability, null/missing values, errors, permissions, pagination, time zones, mutation side effects.
- If tests are absent and behavior is ambiguous, make the smallest possible refactor or ask for expected behavior before changing semantics.

### 4. Optimize (only on explicit request)

- Replace repeated linear lookup with maps/sets when key equality is stable.
- Replace nested scans with indexing, grouping, two-pointer scans, sweep-line logic, binary search, memoization, batching, or precomputation — only when the data shape supports it.
- In UI code, reduce unnecessary renders with stable props, memoized derived data, virtualization, debounced work, and moving expensive work out of render paths.
- In data access code, remove N+1 with bulk fetches, joins, preloading, caching, or batching while preserving authorization and filtering.

### 5. Verify

- Run relevant tests and type/lint/build commands.
- Add a micro-benchmark or measurement when the complexity improvement is non-obvious or performance-critical.
- Report original complexity, new complexity, files changed, tests run, and any residual risk.

## First-Pass Scanner

```bash
python3 scripts/analyze_complexity.py /path/to/repo --format markdown
python3 scripts/analyze_complexity.py /path/to/repo --format json
python3 scripts/analyze_complexity.py /path/to/repo --changed-only --base origin/main
```

`--changed-only` restricts the scan to files changed vs `--base` (default `HEAD~1`). Use it for PR-focused complexity review.

**Language depth:**

- **Python** (`.py`) — AST-based analysis. High precision: nested loops, sort/membership in loops, query/I/O in loops, all tracked per-function via the Python `ast` module.
- **All other supported languages** (`.js`, `.ts`, `.jsx`, `.tsx`, `.java`, `.go`, `.rb`, `.php`, `.cs`, `.c`, `.cpp`, `.swift`, `.vue`, `.svelte`, `.kt`, `.rs`, `.dart`, `.scala`) — regex-based pattern matching with indent + function-boundary heuristics. Treat findings as leads; verify by reading the surrounding code before recommending fixes.

If the scanner reports nothing, still inspect known hot paths manually. Rendering churn, database query patterns, and framework lifecycle issues often need repository-specific context the scanner cannot see.

**Exit codes:** `0` = scanned successfully, `2` = bad input (non-existent path / file instead of directory / git error), `3` = zero files matched, `130` = interrupted.

**Triage before reporting:** consult `references/false-positives.md` to dismiss known noise patterns (single-call predicates, Redux selectors, SQL-builder fluent methods, render-derived work on small static arrays) before recommending fixes.

**Testing the scanner:** `python3 scripts/test_analyze_complexity.py` runs 13 regression tests that pin the false-positive fixes. Run after modifying the scanner.

## Optimization Safety Checklist

Before editing:

- Confirm the data sizes are large enough for complexity to matter.
- Confirm the optimization preserves output ordering where callers may rely on it.
- Confirm object identity, mutability, and reference sharing are not part of public behavior.
- Confirm caches have a valid invalidation strategy.
- Confirm deduplication does not collapse distinct records that share a display label.
- Confirm database batching preserves tenant, permission, soft-delete, pagination, and sorting constraints.

After editing:

- Run the narrowest relevant test first, then the broader build/lint/typecheck.
- Compare before/after benchmark numbers when a benchmark exists or was added.
- Keep the patch localized — avoid formatting churn in unrelated files.

## Rollback

If the optimization breaks a test or changes observable behavior:

1. **Revert the changed file(s) immediately:**
   ```bash
   git restore <file>           # restore a single file
   git restore -SW <file>       # restore both index and working tree
   ```
   If multiple files were modified: `git restore -SW .` (only within the affected directory).

2. **Re-run the failing test** to confirm restoration.

3. **Report the failure to the user** with:
   - The exact test/assertion that failed
   - The semantics that diverged (ordering, mutation, key equality, etc.)
   - Whether to retry with a different transformation, or stay with the original code

4. **Do not** re-attempt the same optimization with a small tweak. If a transformation breaks behavior, either the data shape doesn't support it, or there's an unstated invariant — re-read the code before trying again.

## References

- `references/optimization-playbook.md` — common O(n^2) → O(n log n) / O(n) transformations, framework-specific patterns, and "What Not To Do".
- `references/report-template.md` — structure for the final analysis or audit output.
- `references/false-positives.md` — catalog of scanner findings that look real but aren't. Consult before recommending fixes.
- `scripts/_sections.md` — scanner invocation, flags, exit codes, and limitations.

© pproenca · MIT · pproenca/dot-skills

Похожие скиллы

Все скиллы по теме «Код-ревью и рефакторинг» →
remotion-performance-optimizer ncklrs Скилл remotion-performance-optimizer находит узкие места в Remotion-композициях: лишние перерисовки, тяжёлые расчёты, неоптимальные ассеты. Выдаёт отчёт с конкретными правками и оценкой ускорения. CX Codex +1 171установок Performance Optimizer daffy0208 Скилл Performance Optimizer для Claude Code задаёт процесс профилирования и ускорения кода: от метрик Core Web Vitals и кэширования до устранения N+1 запросов в базе данных. CX Codex +1 228установок refactor-method-complexity-reduce официальный github Скилл refactor-method-complexity-reduce рефакторит выбранный метод, снижая когнитивную сложность через вынос логики в хелперы. Подходит для длинных ветвлений и вложенных условий. CX Codex +1 9 992установок 163-java-profiling-refactor Juan Antonio Breña Moral Скилл 163-java-profiling-refactor берёт готовый отчёт профилирования и правит Java-код по найденным узким местам: CPU, память, потоки. Полезен, когда анализ уже сделан и пора что-то менять. CX Codex +1 359установок 145-java-refactoring-high-performance Juan Antonio Breña Moral Скилл 145-java-refactoring-high-performance для Claude Code помогает оптимизировать Java-код по результатам профилирования: снижать аллокации и улучшать горячие пути CPU. CX Codex +1 327установок performance-optimizer davila7 Скилл performance-optimizer для Claude Code ищет узкие места в коде, базе данных и API, предлагает исправления и сравнивает показатели до и после. CX Codex +1 70установок

Из того же набора139

Весь набор →
typescript-advanced-patterns Скилл typescript-advanced-patterns для Claude Code содержит 40 правил по продвинутому TypeScript: type-level программированию, API библиотек и возможностям TS 5.x. Углубляет паттерны typescript-refactor. CX Codex +1 162установок react-hook-form-audit Скилл react-hook-form-audit ищет 16 антипаттернов React Hook Form в проекте Next.js на App Router и пишет markdown-отчёт с номерами строк. Только чтение, код не меняет. CX Codex +1 158установок codex-goals Скилл codex-goals для Codex помогает формулировать и проверять долгосрочные цели: задавать измеримый результат, способ проверки и условие остановки. Описывает постановку многошаговых задач с понятным финалом. CX Codex +1 158установок expo-design-system Скилл expo-design-system для Claude Code помогает строить и проверять общие компоненты Expo и React Native для веба и iOS. Подключается при работе с токенами, темами и повторно используемым интерфейсом. CX Codex +1 156установок nextjs-bundle-optimizer Скилл nextjs-bundle-optimizer для Claude Code измеряет размер бандла и время сборки Next.js и помогает проверять оптимизации по одной. Проверяет оптимизации при росте First Load JS или замедлении сборки. CX Codex +1 152установок implementation-design-patterns Скилл implementation-design-patterns для Claude Code помогает определить паттерн Gang of Four по описанию задачи и понять, когда его применять или избегать. CX Codex +1 151установок better-auth Скилл по Better Auth для TypeScript: помогает поднять инстанс, выбрать адаптер, настроить сессии и перейти с другой auth-библиотеки. CX Codex +1 150установок diataxis Скилл diataxis раскладывает техническую документацию на четыре режима: туториал, инструкция, справочник, объяснение. Помогает решить, что писать на конкретной странице. CX Codex +1 149установок

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

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