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):
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:
- Read
templates/report.template.md (next to this file, under the skill directory).
- Fill every
{{placeholder}} from the JSON of step 1, and repeat the proposal
block once per function to propose on.
- 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:
- Re-read the function first; it may have changed since the report was written.
- 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.
- 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.
- If the check fails, undo your own edit (apply the reverse edit; never
git checkout/reset/stash) and mark it Reverted with the failure.
- 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).
1---2name: complexity-breaker3description: >-4 Measure the cyclomatic complexity (lizard) of the functions touched by the5 current branch, write a findings report, and propose concrete refactors.6 Report mode (default) never edits source; apply mode acts on proposals as7 rules.md allows. Use when asked to check, audit or reduce the complexity of8 what a branch, PR or working tree changed. Tests are ignored.9license: MIT10metadata:11 source: https://skillmd.com/skills/gustapinto/complexity-breaker12---1314# complexity-breaker1516Finds the functions **this work touched** that are too complex, says whether the17work made them worse, and proposes how to break them up.1819| Mode | Invoked as | What it may do |20|---|---|---|21| **report** (default) | the user asks for it, no args | measure, write the report. **Never edits source.** |22| **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. |2324There is one helper, `scripts/complexity.py`. `$CB` below means the skill's25`scripts` directory: the folder this `SKILL.md` lives in, plus `/scripts`26(typically `~/.claude/skills/complexity-breaker/scripts`, or27`<repo>/.claude/skills/complexity-breaker/scripts` for a project install).28It finds the touched files, measures them with lizard's Python API, and keeps only29the functions that contain a changed line. No temp files, no per-platform script.3031Requires `git` and a `python` (try `python`, then `py -3`, then `python3`; on32Windows `python3` is often a Store stub) with `lizard` installed33(`pip install lizard`). If lizard is missing, the script says so and exits 2: tell34the user, do not install it unasked.3536## Steps3738### 1. Measure what the work touched3940Run from the repository root (paths are relative):4142```bash43python "$CB/complexity.py" --json44```4546- Base branch, in precedence order: `--base REF`; `$COMPLEXITY_BASE`; the first47 line of `./.complexity/base` (a per-repo way to say where PRs go); `origin/HEAD`,48 then `main`/`master`. If the project documents its PR target (CLAUDE.md,49 CONTRIBUTING) and none of the first three is set, pass it as `--base`. State50 which base was used in the report.51- "Touched" means committed since the merge-base, plus staged, unstaged and52 untracked files. Test files and non-code files (docs, JSON, SQL, shell,53 Makefile) are excluded by the script.54- `--files a,b,c` measures exactly those files instead (comma-delimited), e.g. when55 the user names them. `--list-files` only prints the touched files.56 `--threshold N` changes the CCN flag level (default 15). `--max-lines N` changes57 the length warning level (default 30; any function longer than that, in physical58 lines from start to end, is a warning, same meaning as lizard's `-L`).59 `--xml PATH` also writes lizard's raw XML. Without `--json` you get a plain table.60- JSON shape: `{base_ref, base, lizard, threshold, max_lines, files, functions[]}`,61 each function `{ccn, was, ncss, length, touched_lines, file, function, start, end,62 over_threshold, too_long}`. `was` is the CCN at the merge-base: `new` if the63 function did not exist, `?` if its name is ambiguous there (nested anonymous64 callbacks). `over_threshold` is CCN; `too_long` is the length warning.65- `files` empty: write a short report saying nothing touched is measurable, and stop.66- Exit 2 or an error message: say so in the report (or to the user if no report can67 be written) and stop; do not invent numbers.68- Nothing over either limit: say so in one line to the user and stop. Write a69 report only if the user asked for one explicitly (a hook-triggered run with a70 clean result leaves no file behind).7172### 2. Write the report7374Path: `$PWD/.complexity/<session>.report.md` (create the directory).75`<session>` is, in order: the session name if the user gave the session one; else76`<branch>-<sid8>` when the invoking message supplies a session id (the hook does);77else `<branch>-<YYYYMMDD-HHMM>`. Slugify it (lowercase, `[a-z0-9._-]`, `/` becomes78`-`). Never overwrite an existing report: if the file exists, append `-2`, `-3`, ...79Earlier reports of the same session stay, because step 4 reads them.8081Do not edit `.gitignore` or commit the report. If `.complexity/` is not ignored,82say so in your final message and let the user decide.8384The report is built from the template, never from memory:85861. Read `templates/report.template.md` (next to this file, under the skill directory).872. Fill every `{{placeholder}}` from the JSON of step 1, and repeat the proposal88 block once per function to propose on.893. Delete every HTML comment, including the instructions at the top.9091Do not add, rename, reorder or drop sections or table rows. The template says how92each field is filled (verdict rules, row guidance, `<br>` for line breaks inside93cells, `\|` for a literal pipe), so it is the contract; this file only adds what94does not fit inside it.9596### 3. Propose refactors, from the actual code9798**Read each function you propose on, whole**, not just the diff, before writing its99proposal. A proposal is a table (see the template): the first column holds the row100labels and the second the content, and every proposal ends with its own **Caveat**101row. The caveat belongs to that proposal and that function: say what is uncertain102or unverified about it. A generic disclaimer repeated across proposals is not a103caveat. There is no separate Caveats section.104105Which functions get a proposal:106107- Over the CCN threshold: always. Order is `introduced`, `worsened`, `inherited`,108 then by payoff (CCN removed per unit of effort and risk).109- Length-only warnings (CCN within the threshold): a warning, not a defect. Same110 table, shorter content. Decide whether the length is several jobs in sequence111 (give the seams by line range) or declarative code (a JSX tree, a table, a big112 literal, a query), where "Leave as is" with the reason is a valid answer. Do not113 force a split on declarative code.114- `inherited` functions: say whether touching it again is the moment to extract, or115 to leave it alone. For `worsened` ones, extract only what the work added, so the116 fix stays small and reviewable.117118**Be honest about Effort**, because the rules table in step 4 acts on it. **S** means: a mechanical,119local change inside one function or file, no public signature change, no behaviour120change, and something the project's existing checks can plausibly verify (guard121clauses, extracting a block into an unexported helper, a table instead of a122`switch`). Anything that moves logic across files or packages, changes a signature123or contract, or has no test or check near it is **M** or **L**, even if the diff is124small. If the project says a rule must live in one place (CLAUDE.md invariants,125stored-data contracts), a proposal that touches that code is at least **M**.126127End with the template's **Order of attack** list.128129### 4. Apply (apply mode only)130131Skip this step in report mode: fill the template's **Outcome** table with "Report132only, nothing applied" and stop.133134**4a. Load the rules.** Read `.complexity/rules.md` in the repo if it exists,135otherwise `rules.md` next to this file (the skill directory). It is a table of136`effort | action`, with the actions `apply`, `ask` and `skip`. Look up each137proposal's Effort row; an effort with no row uses the `*` row; no `*` row, or a138missing or malformed table, means `ask`. Never infer `apply` from anything but an139explicit row. Name the file used, and the resolved action per effort, in the140report's **Rules** row.141142Then handle each proposal by its action:143144- **`skip`**: do nothing; Outcome status `Skipped (rule)`.145- **`ask`**: step 4b.146- **`apply`**: step 4c directly.147- "Leave as is" proposals take no action whatever the table says; status148 `Not applicable`.149150**4b. `ask` proposals.** Use AskUserQuestion, `multiSelect: true`, one option per151proposal (at most 4 per question; ask in rounds if there are more). Each option's152label names the function and effort; its description says in one sentence what would153change, the estimated CCN after, and the main risk from the Risk row. The automatic154"Other" is how the user declines all.155156- Do not ask about a function whose proposal the user already **declined** earlier in157 this session: read the Outcome tables of this session's earlier reports in158 `.complexity/` and skip those (status `Declined`).159- If a question cannot be asked (no interactive user), leave the proposal as160 `Awaiting permission`. Never treat silence as consent.161- Approved proposals go through 4c.162163**4c. Implement**, one proposal at a time, smallest possible diff:1641651. Re-read the function first; it may have changed since the report was written.1662. Implement exactly what the proposal says. No behaviour change, no signature or167 public-name change, no drive-by edits, no edits to test files to make a check pass.1683. Verify with the narrowest check the project documents (CLAUDE.md, Makefile,169 package.json): for example `gofmt` + `go vet` + `go test` on the package, or170 `tsc` + the unit tests of the folder. If the project documents a "before saying171 done" matrix, follow the row that matches. A check that was skipped or does not172 exist makes the change **unverified**: say so in the Outcome and in the proposal's173 Caveat row.1744. If the check fails, undo **your own edit** (apply the reverse edit; never175 `git checkout`/`reset`/`stash`) and mark it `Reverted` with the failure.1765. Re-run `complexity.py --files <the touched files>` and record the **measured** CCN177 and lines after, next to the estimate.178179**4d. Update the report's Outcome table** for every proposal (status, measured CCN180before→after, verification). The Outcome table is the only section edited after the181proposals were written. Never commit, and never stage anything.182183## Honesty rules184185- Only functions containing a changed line are measured. Say so; never claim a186 statement about the whole codebase from this report.187- CCN counts branches, including `&&`, `||`, `?:` and, in JSX, conditional188 rendering. A high CCN on a UI component often reflects markup conditionals, not189 logic; say which it is when you read the code.190- lizard counts nested callbacks as separate entries, and the enclosing function's191 CCN includes their branches.192- Length counts physical lines, including comments and blanks, and a function's193 length includes the callbacks nested in it. Compare `lines` with `ncss` before194 calling something long: a well-commented function can be 40 lines and 20 NCSS.195- `was` is matched by function name; `?` means ambiguous. Do not guess it.196- Caveats are per proposal and specific to it; never a shared disclaimer.197- Estimates are estimates. Never present a predicted CCN as measured; the Outcome198 table has a separate measured column.199- Report mode never edits source. Apply mode edits only what step 4 allows. Neither200 mode commits.201202## The end-of-turn hook203204`scripts/hook.py` is **optional** and not active until you wire it into205`settings.json` (see README.md): a `UserPromptSubmit` hook206snapshots the touched files when a turn starts, and a `Stop` hook compares at the207end. If this turn changed measurable source it blocks the stop **once** and asks208for this skill in apply mode. Details, so you can explain them to the user:209210- It never fires twice in a row (`stop_hook_active`), so the skill's own refactors211 do not re-trigger it; the next prompt re-snapshots.212- Test files and non-code files do not count, nor does a branch's old diff.213- Off switches: `COMPLEXITY_BREAKER=off` in the environment, or a file214 `.complexity/off` in the repo. `COMPLEXITY_DEBUG=1` prints hook errors.215- Per-repo base branch: write it to `.complexity/base` (gitignored globally).216217## Final message to the user218219Report path (full absolute path), the over-threshold list in one line each220(`CCN was→now`, location), then what apply mode did: what was applied (with the221measured CCN), what was reverted and why, and what is waiting for the user's222permission. Add any caveat that changes how to read it (base branch chosen, files223skipped, checks that were unverified, `.complexity/` not ignored).