# Complexity Breaker

> Measure the cyclomatic complexity (lizard) of the functions touched by the current branch, write a findings report, and propose concrete refactors. Report mode (default) never edits source; apply mode acts on proposals as rules.md allows. Use when asked to check, audit or reduce the complexity of what a branch, PR or working tree changed. Tests are ignored.

- Skill: `gustapinto/complexity-breaker` (Agent Skill, multi-file: 7 files)
- Install (CLI): `npx get-skill add gustapinto/complexity-breaker`
- Raw SKILL.md: https://api.skillmd.com/api/skills/gustapinto/complexity-breaker/raw
- Safety review: pending
- Works with: any agent that reads SKILL.md (Claude Code, Claude.ai, Cursor, Codex, Windsurf, 60+ more)
- Category: Data & Analytics
- License: MIT
- Author: Gustavo Henrique Pinto (https://skillmd.com/u/gustapinto)
- Updated: 2026-11-24
- Page: https://skillmd.com/skills/gustapinto/complexity-breaker

---


# complexity-breaker

Finds the functions **this work touched** that are too complex, says whether the
work made them worse, and proposes how to break them up.

| Mode | Invoked as | What it may do |
|---|---|---|
| **report** (default) | the user asks for it, no args | measure, write the report. **Never edits source.** |
| **apply** | args contain `apply` (the optional Stop hook does this) | report, then act on each proposal as `rules.md` says for its effort: `apply`, `ask` or `skip` (step 4). Shipped as `ask` for every effort. |

There is one helper, `scripts/complexity.py`. `$CB` below means the skill's
`scripts` directory: the folder this `SKILL.md` lives in, plus `/scripts`
(typically `~/.claude/skills/complexity-breaker/scripts`, or
`<repo>/.claude/skills/complexity-breaker/scripts` for a project install).
It finds the touched files, measures them with lizard's Python API, and keeps only
the functions that contain a changed line. No temp files, no per-platform script.

Requires `git` and a `python` (try `python`, then `py -3`, then `python3`; on
Windows `python3` is often a Store stub) with `lizard` installed
(`pip install lizard`). If lizard is missing, the script says so and exits 2: tell
the user, do not install it unasked.

## Steps

### 1. Measure what the work touched

Run from the repository root (paths are relative):

```bash
python "$CB/complexity.py" --json
```

- Base branch, in precedence order: `--base REF`; `$COMPLEXITY_BASE`; the first
  line of `./.complexity/base` (a per-repo way to say where PRs go); `origin/HEAD`,
  then `main`/`master`. If the project documents its PR target (CLAUDE.md,
  CONTRIBUTING) and none of the first three is set, pass it as `--base`. State
  which base was used in the report.
- "Touched" means committed since the merge-base, plus staged, unstaged and
  untracked files. Test files and non-code files (docs, JSON, SQL, shell,
  Makefile) are excluded by the script.
- `--files a,b,c` measures exactly those files instead (comma-delimited), e.g. when
  the user names them. `--list-files` only prints the touched files.
  `--threshold N` changes the CCN flag level (default 15). `--max-lines N` changes
  the length warning level (default 30; any function longer than that, in physical
  lines from start to end, is a warning, same meaning as lizard's `-L`).
  `--xml PATH` also writes lizard's raw XML. Without `--json` you get a plain table.
- JSON shape: `{base_ref, base, lizard, threshold, max_lines, files, functions[]}`,
  each function `{ccn, was, ncss, length, touched_lines, file, function, start, end,
  over_threshold, too_long}`. `was` is the CCN at the merge-base: `new` if the
  function did not exist, `?` if its name is ambiguous there (nested anonymous
  callbacks). `over_threshold` is CCN; `too_long` is the length warning.
- `files` empty: write a short report saying nothing touched is measurable, and stop.
- Exit 2 or an error message: say so in the report (or to the user if no report can
  be written) and stop; do not invent numbers.
- Nothing over either limit: say so in one line to the user and stop. Write a
  report only if the user asked for one explicitly (a hook-triggered run with a
  clean result leaves no file behind).

### 2. Write the report

Path: `$PWD/.complexity/<session>.report.md` (create the directory).
`<session>` is, in order: the session name if the user gave the session one; else
`<branch>-<sid8>` when the invoking message supplies a session id (the hook does);
else `<branch>-<YYYYMMDD-HHMM>`. Slugify it (lowercase, `[a-z0-9._-]`, `/` becomes
`-`). Never overwrite an existing report: if the file exists, append `-2`, `-3`, ...
Earlier reports of the same session stay, because step 4 reads them.

Do not edit `.gitignore` or commit the report. If `.complexity/` is not ignored,
say so in your final message and let the user decide.

The report is built from the template, never from memory:

1. Read `templates/report.template.md` (next to this file, under the skill directory).
2. Fill every `{{placeholder}}` from the JSON of step 1, and repeat the proposal
   block once per function to propose on.
3. Delete every HTML comment, including the instructions at the top.

Do not add, rename, reorder or drop sections or table rows. The template says how
each field is filled (verdict rules, row guidance, `<br>` for line breaks inside
cells, `\|` for a literal pipe), so it is the contract; this file only adds what
does not fit inside it.

### 3. Propose refactors, from the actual code

**Read each function you propose on, whole**, not just the diff, before writing its
proposal. A proposal is a table (see the template): the first column holds the row
labels and the second the content, and every proposal ends with its own **Caveat**
row. The caveat belongs to that proposal and that function: say what is uncertain
or unverified about it. A generic disclaimer repeated across proposals is not a
caveat. There is no separate Caveats section.

Which functions get a proposal:

- Over the CCN threshold: always. Order is `introduced`, `worsened`, `inherited`,
  then by payoff (CCN removed per unit of effort and risk).
- Length-only warnings (CCN within the threshold): a warning, not a defect. Same
  table, shorter content. Decide whether the length is several jobs in sequence
  (give the seams by line range) or declarative code (a JSX tree, a table, a big
  literal, a query), where "Leave as is" with the reason is a valid answer. Do not
  force a split on declarative code.
- `inherited` functions: say whether touching it again is the moment to extract, or
  to leave it alone. For `worsened` ones, extract only what the work added, so the
  fix stays small and reviewable.

**Be honest about Effort**, because the rules table in step 4 acts on it. **S** means: a mechanical,
local change inside one function or file, no public signature change, no behaviour
change, and something the project's existing checks can plausibly verify (guard
clauses, extracting a block into an unexported helper, a table instead of a
`switch`). Anything that moves logic across files or packages, changes a signature
or contract, or has no test or check near it is **M** or **L**, even if the diff is
small. If the project says a rule must live in one place (CLAUDE.md invariants,
stored-data contracts), a proposal that touches that code is at least **M**.

End with the template's **Order of attack** list.

### 4. Apply (apply mode only)

Skip this step in report mode: fill the template's **Outcome** table with "Report
only, nothing applied" and stop.

**4a. Load the rules.** Read `.complexity/rules.md` in the repo if it exists,
otherwise `rules.md` next to this file (the skill directory). It is a table of
`effort | action`, with the actions `apply`, `ask` and `skip`. Look up each
proposal's Effort row; an effort with no row uses the `*` row; no `*` row, or a
missing or malformed table, means `ask`. Never infer `apply` from anything but an
explicit row. Name the file used, and the resolved action per effort, in the
report's **Rules** row.

Then handle each proposal by its action:

- **`skip`**: do nothing; Outcome status `Skipped (rule)`.
- **`ask`**: step 4b.
- **`apply`**: step 4c directly.
- "Leave as is" proposals take no action whatever the table says; status
  `Not applicable`.

**4b. `ask` proposals.** Use AskUserQuestion, `multiSelect: true`, one option per
proposal (at most 4 per question; ask in rounds if there are more). Each option's
label names the function and effort; its description says in one sentence what would
change, the estimated CCN after, and the main risk from the Risk row. The automatic
"Other" is how the user declines all.

- Do not ask about a function whose proposal the user already **declined** earlier in
  this session: read the Outcome tables of this session's earlier reports in
  `.complexity/` and skip those (status `Declined`).
- If a question cannot be asked (no interactive user), leave the proposal as
  `Awaiting permission`. Never treat silence as consent.
- Approved proposals go through 4c.

**4c. Implement**, one proposal at a time, smallest possible diff:

1. Re-read the function first; it may have changed since the report was written.
2. Implement exactly what the proposal says. No behaviour change, no signature or
   public-name change, no drive-by edits, no edits to test files to make a check pass.
3. Verify with the narrowest check the project documents (CLAUDE.md, Makefile,
   package.json): for example `gofmt` + `go vet` + `go test` on the package, or
   `tsc` + the unit tests of the folder. If the project documents a "before saying
   done" matrix, follow the row that matches. A check that was skipped or does not
   exist makes the change **unverified**: say so in the Outcome and in the proposal's
   Caveat row.
4. If the check fails, undo **your own edit** (apply the reverse edit; never
   `git checkout`/`reset`/`stash`) and mark it `Reverted` with the failure.
5. Re-run `complexity.py --files <the touched files>` and record the **measured** CCN
   and lines after, next to the estimate.

**4d. Update the report's Outcome table** for every proposal (status, measured CCN
before→after, verification). The Outcome table is the only section edited after the
proposals were written. Never commit, and never stage anything.

## Honesty rules

- Only functions containing a changed line are measured. Say so; never claim a
  statement about the whole codebase from this report.
- CCN counts branches, including `&&`, `||`, `?:` and, in JSX, conditional
  rendering. A high CCN on a UI component often reflects markup conditionals, not
  logic; say which it is when you read the code.
- lizard counts nested callbacks as separate entries, and the enclosing function's
  CCN includes their branches.
- Length counts physical lines, including comments and blanks, and a function's
  length includes the callbacks nested in it. Compare `lines` with `ncss` before
  calling something long: a well-commented function can be 40 lines and 20 NCSS.
- `was` is matched by function name; `?` means ambiguous. Do not guess it.
- Caveats are per proposal and specific to it; never a shared disclaimer.
- Estimates are estimates. Never present a predicted CCN as measured; the Outcome
  table has a separate measured column.
- Report mode never edits source. Apply mode edits only what step 4 allows. Neither
  mode commits.

## The end-of-turn hook

`scripts/hook.py` is **optional** and not active until you wire it into
`settings.json` (see README.md): a `UserPromptSubmit` hook
snapshots the touched files when a turn starts, and a `Stop` hook compares at the
end. If this turn changed measurable source it blocks the stop **once** and asks
for this skill in apply mode. Details, so you can explain them to the user:

- It never fires twice in a row (`stop_hook_active`), so the skill's own refactors
  do not re-trigger it; the next prompt re-snapshots.
- Test files and non-code files do not count, nor does a branch's old diff.
- Off switches: `COMPLEXITY_BREAKER=off` in the environment, or a file
  `.complexity/off` in the repo. `COMPLEXITY_DEBUG=1` prints hook errors.
- Per-repo base branch: write it to `.complexity/base` (gitignored globally).

## Final message to the user

Report path (full absolute path), the over-threshold list in one line each
(`CCN was→now`, location), then what apply mode did: what was applied (with the
measured CCN), what was reverted and why, and what is waiting for the user's
permission. Add any caveat that changes how to read it (base branch chosen, files
skipped, checks that were unverified, `.complexity/` not ignored).

