autoratchet 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +237 -0
- package/agent-hooks/claude-code/complexity-check.sh +66 -0
- package/agent-hooks/claude-code/settings.json +29 -0
- package/config/biome-cognitive.json +17 -0
- package/config/oxlint-cyclomatic.json +6 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +93 -0
- package/dist/collect.d.ts +68 -0
- package/dist/collect.js +296 -0
- package/dist/compare.d.ts +27 -0
- package/dist/compare.js +68 -0
- package/dist/functions.d.ts +24 -0
- package/dist/functions.js +202 -0
- package/dist/gate.d.ts +53 -0
- package/dist/gate.js +63 -0
- package/dist/git.d.ts +19 -0
- package/dist/git.js +45 -0
- package/dist/identity.d.ts +9 -0
- package/dist/identity.js +21 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +13 -0
- package/dist/internals.d.ts +9 -0
- package/dist/internals.js +9 -0
- package/dist/overrides.d.ts +32 -0
- package/dist/overrides.js +89 -0
- package/dist/report.d.ts +21 -0
- package/dist/report.js +125 -0
- package/package.json +75 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
# AutoRatchet
|
|
2
|
+
|
|
3
|
+
**Prevent code quality regressions, one pull request at a time.**
|
|
4
|
+
|
|
5
|
+
AutoRatchet stops functions in your TypeScript and JavaScript code from getting more complex,
|
|
6
|
+
without asking you to fix the complex code you already have. Install it on a ten-year-old
|
|
7
|
+
codebase today, and from tomorrow no pull request can make it worse.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install -D autoratchet
|
|
11
|
+
npx autoratchet check --base main
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
```text
|
|
15
|
+
Complexity regressions detected:
|
|
16
|
+
|
|
17
|
+
src/payments.ts
|
|
18
|
+
processPayment
|
|
19
|
+
cyclomatic: 19 → 24 (+5)
|
|
20
|
+
cognitive: 28 → 38 (+10)
|
|
21
|
+
|
|
22
|
+
Quality gate failed.
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Why
|
|
26
|
+
|
|
27
|
+
A complexity rule on a legacy codebase fails on hundreds of functions on day one, so teams
|
|
28
|
+
either never turn it on or record the existing failures as accepted ("bulk suppressions").
|
|
29
|
+
Suppressions count *how many* functions are over the limit in each file. A function that was
|
|
30
|
+
already over the limit can then get worse forever without changing the count, and CI stays
|
|
31
|
+
green.
|
|
32
|
+
|
|
33
|
+
AutoRatchet compares every function with the same function on your target branch instead:
|
|
34
|
+
|
|
35
|
+
- **A new function** must stay under the limit.
|
|
36
|
+
- **A function already over the limit** may not get any worse.
|
|
37
|
+
- **A function under the limit** may grow up to it.
|
|
38
|
+
- **Improvements stick.** The target branch is the baseline, so there is no baseline file to
|
|
39
|
+
maintain, and every improvement becomes that function's new ceiling.
|
|
40
|
+
|
|
41
|
+
It measures two things, because each misses regressions the other catches:
|
|
42
|
+
|
|
43
|
+
| Metric | Measures | Limit for new code |
|
|
44
|
+
|--------|----------|-------------------:|
|
|
45
|
+
| Cyclomatic complexity ([Oxlint](https://oxc.rs/docs/guide/usage/linter), modified variant) | Decisions in a function: roughly, testing effort | 10 |
|
|
46
|
+
| Cognitive complexity ([Biome](https://biomejs.dev/linter/rules/no-excessive-cognitive-complexity/)) | How hard the function is to read, weighted by nesting | 15 |
|
|
47
|
+
|
|
48
|
+
New to these metrics? The companion guide,
|
|
49
|
+
[Cyclomatic and cognitive complexity, explained](https://github.com/jagreehal/cyclomatic-and-cognitive-complexity-explained),
|
|
50
|
+
teaches both from scratch with runnable examples, including false positives worth overriding
|
|
51
|
+
and how quality gates get gamed.
|
|
52
|
+
|
|
53
|
+
## Use it
|
|
54
|
+
|
|
55
|
+
Needs Node.js 24 or newer and a git repository.
|
|
56
|
+
|
|
57
|
+
### Locally
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
npx autoratchet check --base main # whole repo
|
|
61
|
+
npx autoratchet check --base main src # only src/
|
|
62
|
+
npx autoratchet check --base main src ':!src/generated'
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`check` compares your working tree, uncommitted changes included, with
|
|
66
|
+
`git merge-base main HEAD`. Files git ignores are skipped. Pathspecs work as in any git command.
|
|
67
|
+
|
|
68
|
+
### In GitHub pull requests
|
|
69
|
+
|
|
70
|
+
```yaml
|
|
71
|
+
# .github/workflows/autoratchet.yml
|
|
72
|
+
name: AutoRatchet
|
|
73
|
+
on:
|
|
74
|
+
pull_request:
|
|
75
|
+
pull_request_review:
|
|
76
|
+
types: [submitted, dismissed]
|
|
77
|
+
|
|
78
|
+
permissions:
|
|
79
|
+
contents: read
|
|
80
|
+
pull-requests: write
|
|
81
|
+
|
|
82
|
+
jobs:
|
|
83
|
+
ratchet:
|
|
84
|
+
runs-on: ubuntu-latest
|
|
85
|
+
steps:
|
|
86
|
+
- uses: actions/checkout@v7
|
|
87
|
+
- uses: actions/setup-node@v7
|
|
88
|
+
with:
|
|
89
|
+
node-version: 24
|
|
90
|
+
- uses: jagreehal/autoratchet@v0.1.0
|
|
91
|
+
with:
|
|
92
|
+
path: src
|
|
93
|
+
override-approval: review
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
The action fails the check on a regression, marks each regressed function in the PR diff,
|
|
97
|
+
writes the report to the job summary, and keeps one comment on the PR updated (it only
|
|
98
|
+
comments once there is something to say).
|
|
99
|
+
|
|
100
|
+
| Input | Default | Meaning |
|
|
101
|
+
|-------|---------|---------|
|
|
102
|
+
| `path` | whole repo | Git pathspecs to measure, space separated |
|
|
103
|
+
| `base` | PR base | Ref to compare against |
|
|
104
|
+
| `threshold` | `10` | Cyclomatic limit for new functions |
|
|
105
|
+
| `cognitive-threshold` | `15` | Cognitive limit for new functions |
|
|
106
|
+
| `override-approval` | `none` | `none`, `strict`, `review` or `label` (see [Overrides](#overrides)) |
|
|
107
|
+
| `approval-label` | `complexity-override-approved` | The label `label` mode looks for |
|
|
108
|
+
| `comment` | `true` | Keep one sticky PR comment |
|
|
109
|
+
| `annotations` | `true` | Mark regressions in the diff |
|
|
110
|
+
| `fail-on-regression` | `true` | Fail the job on a regression or incomplete measurement |
|
|
111
|
+
|
|
112
|
+
Make the job a required status check so a failure blocks merging.
|
|
113
|
+
|
|
114
|
+
### With coding agents
|
|
115
|
+
|
|
116
|
+
AutoRatchet constrains the output rather than relying on instructions to the author, so it
|
|
117
|
+
treats human- and agent-written code the same. For Claude Code, two hooks run the check while
|
|
118
|
+
the agent works and hand any regression straight back to it:
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
mkdir -p .claude/hooks
|
|
122
|
+
cp node_modules/autoratchet/agent-hooks/claude-code/complexity-check.sh .claude/hooks/
|
|
123
|
+
cp node_modules/autoratchet/agent-hooks/claude-code/settings.json .claude/settings.json # or merge its "hooks" block
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
After every edit, the hook checks the file against its last commit. Before the agent finishes,
|
|
127
|
+
it checks every changed file. It blocks on regressions, on files that do not parse, and on any
|
|
128
|
+
new override comment, because an agent may not approve its own exception. The hooks need `git`
|
|
129
|
+
and `jq`. Hooks run on the author's machine, so they are a fast feedback loop; the CI check is
|
|
130
|
+
the enforcement.
|
|
131
|
+
|
|
132
|
+
## Overrides
|
|
133
|
+
|
|
134
|
+
Sometimes a high score is fine: an options object with ten defaults, a fallback chain of `?.`.
|
|
135
|
+
Mark it on the function, with a reason:
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
// oxlint-disable-next-line complexity -- options bag: each default is one line, no logic
|
|
139
|
+
export function createChart({ width = 640, height = 400 /* … */ } = {}) {
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: follows the RFC 3986 parsing steps in order
|
|
144
|
+
export function parseUri(input: string) {
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
An override **approves a score; it does not stop measurement.** AutoRatchet measures a copy of
|
|
148
|
+
your code with every disable comment defused, so:
|
|
149
|
+
|
|
150
|
+
- The PR that adds the override approves that function's current score on that one metric,
|
|
151
|
+
and the report lists the function, metric, score and reason for a reviewer.
|
|
152
|
+
- Every later PR compares against that score. Make the function worse and the check fails.
|
|
153
|
+
- The other metric stays enforced. An Oxlint comment covers cyclomatic only, `biome-ignore`
|
|
154
|
+
covers cognitive only.
|
|
155
|
+
- File-wide disables (`/* oxlint-disable */`, `biome-ignore-all`) approve nothing.
|
|
156
|
+
|
|
157
|
+
Who may approve a new override, with `override-approval`:
|
|
158
|
+
|
|
159
|
+
| Mode | A new override passes when |
|
|
160
|
+
|------|----------------------------|
|
|
161
|
+
| `none` | Always. It is listed in the PR comment for a reviewer. |
|
|
162
|
+
| `strict` | Never. Every new override fails the check. |
|
|
163
|
+
| `review` | Someone other than the PR author, with write access, approves the PR's current head commit. A new push needs a new approval. |
|
|
164
|
+
| `label` | The PR has the `complexity-override-approved` label. Anyone with write access can add labels, including the author, so this keeps out agents whose token cannot label, not people. |
|
|
165
|
+
|
|
166
|
+
For an approval that the author cannot grant themselves, use `review` and also protect `main`:
|
|
167
|
+
require a review from someone else, dismiss stale approvals when new commits arrive, and use
|
|
168
|
+
CODEOWNERS so workflow and configuration changes need their owners' approval.
|
|
169
|
+
|
|
170
|
+
## Outcomes and exit codes
|
|
171
|
+
|
|
172
|
+
| Exit code | Meaning |
|
|
173
|
+
|----------:|---------|
|
|
174
|
+
| 0 | Every function measured, no regressions |
|
|
175
|
+
| 1 | A regression, or a new override that needs approval |
|
|
176
|
+
| 2 | Bad arguments |
|
|
177
|
+
| 3 | Measurement incomplete: a file that does not parse, or a score that cannot be matched to a named function |
|
|
178
|
+
| 4 | AutoRatchet itself failed |
|
|
179
|
+
|
|
180
|
+
AutoRatchet fails closed. A function it could not measure is not evidence that the function is
|
|
181
|
+
fine.
|
|
182
|
+
|
|
183
|
+
## CLI
|
|
184
|
+
|
|
185
|
+
```text
|
|
186
|
+
autoratchet check [--base <ref>] [options] [pathspec...]
|
|
187
|
+
autoratchet compare --base <dir|json> --head <dir|json> [options]
|
|
188
|
+
|
|
189
|
+
--threshold <n> cyclomatic limit for new functions (default 10)
|
|
190
|
+
--cognitive-threshold <n> cognitive limit for new functions (default 15)
|
|
191
|
+
--require-override-approval fail on any new override instead of approving its score
|
|
192
|
+
--format <text|json|markdown> output format (default text)
|
|
193
|
+
-o, --output <file> write the report to a file
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
`--format json` is for dashboards, CI annotations and coding agents. It includes the verdict,
|
|
197
|
+
every regression with file and line, approvals, measurement problems, and the Markdown report.
|
|
198
|
+
|
|
199
|
+
## API
|
|
200
|
+
|
|
201
|
+
```ts
|
|
202
|
+
import { check, formatReport, verdict } from 'autoratchet';
|
|
203
|
+
|
|
204
|
+
const result = await check({ base: 'main', paths: ['src'] });
|
|
205
|
+
if (verdict(result) !== 'pass') {
|
|
206
|
+
console.error(formatReport(result));
|
|
207
|
+
process.exitCode = 1;
|
|
208
|
+
}
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
`compareSources` and `comparePaths` compare two sets of files directly, and `passesComplexityGate`
|
|
212
|
+
is the ratchet rule on its own:
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
current <= Math.max(previous ?? 0, threshold);
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
## How functions are identified
|
|
219
|
+
|
|
220
|
+
Each function is matched across commits by file path and a qualified name from its syntax:
|
|
221
|
+
`PaymentService.validate`, `handlers.onSubmit`, `createChart>helper`,
|
|
222
|
+
`render>items.map()`, `PAYMENT_RULES["flagged-vip-review"]`. Moving a function to another file
|
|
223
|
+
or renaming it makes it look new, so it must meet the limits for new code. Callbacks and table
|
|
224
|
+
entries without a key are named by position, so reordering them pairs a function with another
|
|
225
|
+
function's history; give table entries a key (`['name', fn]`, or an `id`/`key`/`name` property)
|
|
226
|
+
to avoid that.
|
|
227
|
+
|
|
228
|
+
## Limits
|
|
229
|
+
|
|
230
|
+
- JavaScript and TypeScript only (`.js`, `.jsx`, `.ts`, `.tsx` and the `m`/`c` variants).
|
|
231
|
+
- Two metrics: cyclomatic and cognitive complexity.
|
|
232
|
+
- Biome does not report cognitive scores of 0 or 1, so both are recorded as 1.
|
|
233
|
+
- Class field initialisers that are not functions are not measured.
|
|
234
|
+
|
|
235
|
+
## License
|
|
236
|
+
|
|
237
|
+
Apache-2.0. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Claude Code hook: run AutoRatchet on what Claude changed, against the last commit.
|
|
3
|
+
# complexity-check.sh edited PostToolUse (Edit|Write|MultiEdit): the one file just changed, in about a second.
|
|
4
|
+
# complexity-check.sh stop Stop: every changed source file, once per turn, before Claude hands back.
|
|
5
|
+
# Silent when clean. On problems: exit 2 with the report on stderr, which Claude reads and acts on.
|
|
6
|
+
# Blocks on what CI would fail (a function over its limit that got worse, a new function over a limit,
|
|
7
|
+
# a function that crossed a limit, a file that cannot be measured) and on any new complexity override
|
|
8
|
+
# comment: a new override approves a score, and an agent may not approve its own. A person commits those.
|
|
9
|
+
# Needs: jq, git, and AutoRatchet installed (node_modules/.bin/autoratchet).
|
|
10
|
+
set -uo pipefail
|
|
11
|
+
|
|
12
|
+
mode=${1:-edited}
|
|
13
|
+
input=$(cat)
|
|
14
|
+
cd "${CLAUDE_PROJECT_DIR:-.}" || exit 0
|
|
15
|
+
ratchet=${AUTORATCHET:-node_modules/.bin/autoratchet}
|
|
16
|
+
[ -x "$ratchet" ] || exit 0
|
|
17
|
+
git rev-parse --verify -q HEAD >/dev/null || exit 0 # no commit to compare with yet
|
|
18
|
+
|
|
19
|
+
is_source() {
|
|
20
|
+
case "$1" in
|
|
21
|
+
node_modules/* | dist/* | build/* | coverage/* | */generated/* | *.d.ts) return 1 ;;
|
|
22
|
+
*.ts | *.tsx | *.js | *.jsx | *.mts | *.cts | *.mjs | *.cjs) return 0 ;;
|
|
23
|
+
*) return 1 ;;
|
|
24
|
+
esac
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
files=()
|
|
28
|
+
if [ "$mode" = "stop" ]; then
|
|
29
|
+
# A problem Claude could not fix must not trap it in a loop: report, don't block twice.
|
|
30
|
+
active=$(printf '%s' "$input" | jq -r '.stop_hook_active // false')
|
|
31
|
+
while IFS= read -r f; do
|
|
32
|
+
[ -f "$f" ] && is_source "$f" && files+=("$f")
|
|
33
|
+
done < <(git status --porcelain --untracked-files=all | sed -E 's/^.{3}//; s/.* -> //')
|
|
34
|
+
else
|
|
35
|
+
active=false
|
|
36
|
+
f=$(printf '%s' "$input" | jq -r '.tool_input.file_path // .tool_response.filePath // empty')
|
|
37
|
+
f=${f#"$PWD"/}
|
|
38
|
+
[ -n "$f" ] && [ -f "$f" ] && is_source "$f" && files+=("$f")
|
|
39
|
+
fi
|
|
40
|
+
[ ${#files[@]} -gt 0 ] || exit 0
|
|
41
|
+
|
|
42
|
+
# shellcheck disable=SC2086 # split on purpose, e.g. "--threshold 12 --cognitive-threshold 18"
|
|
43
|
+
report=$("$ratchet" check --base HEAD ${AUTORATCHET_ARGS:-} -- "${files[@]}" 2>&1)
|
|
44
|
+
status=$?
|
|
45
|
+
# 1 = regression, 3 = something could not be measured (often a file that does not parse yet).
|
|
46
|
+
# Both go back to Claude. 2 and 4 mean the tool itself failed: say so, but never block on it.
|
|
47
|
+
if [ "$status" -ne 0 ] && [ "$status" -ne 1 ] && [ "$status" -ne 3 ]; then
|
|
48
|
+
printf "autoratchet failed (exit %s), skipping the check:\n%s\n" "$status" "$report" >&2
|
|
49
|
+
exit 0
|
|
50
|
+
fi
|
|
51
|
+
|
|
52
|
+
problems=""
|
|
53
|
+
[ "$status" -eq 3 ] && problems+="$report\n\nMake every changed file parse, then the check can measure it.\n"
|
|
54
|
+
[ "$status" -eq 1 ] && problems+="$report\n\nFix the code, not the score: guard clauses, a lookup table, a switch over a union, named predicates, or a decision table. Do not split a function at an arbitrary point.\n"
|
|
55
|
+
if printf '%s' "$report" | grep -qE 'Approved by a new override|sit on no single function'; then
|
|
56
|
+
overrides=$(printf '%s' "$report" | grep -E '^\s+line [0-9]+: |^ [^ ].*:[0-9]+ ')
|
|
57
|
+
problems+="New complexity override comments:\n$overrides\nRemove them. If you believe a score is a false positive, stop and ask the user; a person commits overrides.\n"
|
|
58
|
+
fi
|
|
59
|
+
|
|
60
|
+
[ -z "$problems" ] && exit 0
|
|
61
|
+
if [ "$active" = "true" ]; then
|
|
62
|
+
printf "Complexity check still failing after a fix attempt (not blocking again):\n%b" "$problems" >&2
|
|
63
|
+
exit 0
|
|
64
|
+
fi
|
|
65
|
+
printf "Complexity check failed:\n%b" "$problems" >&2
|
|
66
|
+
exit 2
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"hooks": {
|
|
3
|
+
"PostToolUse": [
|
|
4
|
+
{
|
|
5
|
+
"matcher": "Edit|Write|MultiEdit",
|
|
6
|
+
"hooks": [
|
|
7
|
+
{
|
|
8
|
+
"type": "command",
|
|
9
|
+
"command": "bash \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/complexity-check.sh edited",
|
|
10
|
+
"timeout": 30,
|
|
11
|
+
"statusMessage": "Checking complexity of the edited file"
|
|
12
|
+
}
|
|
13
|
+
]
|
|
14
|
+
}
|
|
15
|
+
],
|
|
16
|
+
"Stop": [
|
|
17
|
+
{
|
|
18
|
+
"hooks": [
|
|
19
|
+
{
|
|
20
|
+
"type": "command",
|
|
21
|
+
"command": "bash \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/complexity-check.sh stop",
|
|
22
|
+
"timeout": 60,
|
|
23
|
+
"statusMessage": "Complexity ratchet on changed files"
|
|
24
|
+
}
|
|
25
|
+
]
|
|
26
|
+
}
|
|
27
|
+
]
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "../node_modules/@biomejs/biome/configuration_schema.json",
|
|
3
|
+
"formatter": { "enabled": false },
|
|
4
|
+
"assist": { "enabled": false },
|
|
5
|
+
"linter": {
|
|
6
|
+
"enabled": true,
|
|
7
|
+
"rules": {
|
|
8
|
+
"recommended": false,
|
|
9
|
+
"complexity": {
|
|
10
|
+
"noExcessiveCognitiveComplexity": {
|
|
11
|
+
"level": "error",
|
|
12
|
+
"options": { "maxAllowedComplexity": 1 }
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import { comparePaths, verdict } from './compare.js';
|
|
5
|
+
import { check } from './git.js';
|
|
6
|
+
import { formatMarkdown, formatReport, toJson } from './report.js';
|
|
7
|
+
const USAGE = `Usage:
|
|
8
|
+
autoratchet check [--base <ref>] [options] [pathspec...]
|
|
9
|
+
Compare the working tree with merge-base(<ref>, HEAD). Default ref: main.
|
|
10
|
+
Pathspecs limit what is measured, e.g. src ':!src/generated'.
|
|
11
|
+
|
|
12
|
+
autoratchet compare --base <dir|json> --head <dir|json> [options]
|
|
13
|
+
Compare two directories (or JSON snapshots) directly.
|
|
14
|
+
|
|
15
|
+
Options:
|
|
16
|
+
--threshold <n> maximum cyclomatic score for new functions (default 10)
|
|
17
|
+
--cognitive-threshold <n> maximum cognitive score for new functions (default 15)
|
|
18
|
+
--require-override-approval fail on any new override instead of treating it as an approval
|
|
19
|
+
--format <text|json|markdown> output format (default text)
|
|
20
|
+
-o, --output <file> write the report to a file instead of stdout
|
|
21
|
+
|
|
22
|
+
Exit codes: 0 pass, 1 regression, 2 bad arguments, 3 measurement incomplete, 4 tool error.`;
|
|
23
|
+
/** 0 pass, 1 regression, 3 measurement incomplete. 2 and 4 are set below. */
|
|
24
|
+
const EXIT = { pass: 0, fail: 1, incomplete: 3 };
|
|
25
|
+
const FORMATS = { text: formatReport, json: toJson, markdown: formatMarkdown };
|
|
26
|
+
function number(value, flag) {
|
|
27
|
+
if (value === undefined)
|
|
28
|
+
return undefined;
|
|
29
|
+
const n = Number(value);
|
|
30
|
+
if (!Number.isFinite(n) || n < 1)
|
|
31
|
+
throw new UsageError(`${flag} needs a positive number, got "${value}"`);
|
|
32
|
+
return n;
|
|
33
|
+
}
|
|
34
|
+
class UsageError extends Error {
|
|
35
|
+
}
|
|
36
|
+
async function runCommand(command, paths, values, options) {
|
|
37
|
+
if (command === 'check')
|
|
38
|
+
return check({ ...options, base: values.base, paths });
|
|
39
|
+
if (command !== 'compare')
|
|
40
|
+
throw new UsageError(`unknown command "${command}"`);
|
|
41
|
+
if (!values.base || !values.head)
|
|
42
|
+
throw new UsageError('compare needs --base and --head');
|
|
43
|
+
return comparePaths(values.base, values.head, options);
|
|
44
|
+
}
|
|
45
|
+
async function run(argv) {
|
|
46
|
+
const { values, positionals } = parseArgs({
|
|
47
|
+
args: argv,
|
|
48
|
+
allowPositionals: true,
|
|
49
|
+
options: {
|
|
50
|
+
base: { type: 'string' },
|
|
51
|
+
head: { type: 'string' },
|
|
52
|
+
threshold: { type: 'string' },
|
|
53
|
+
'cyclomatic-threshold': { type: 'string' },
|
|
54
|
+
'cognitive-threshold': { type: 'string' },
|
|
55
|
+
'require-override-approval': { type: 'boolean' },
|
|
56
|
+
format: { type: 'string', default: 'text' },
|
|
57
|
+
output: { type: 'string', short: 'o' },
|
|
58
|
+
help: { type: 'boolean', short: 'h' },
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
const [command, ...paths] = positionals;
|
|
62
|
+
if (values.help || !command) {
|
|
63
|
+
console.log(USAGE);
|
|
64
|
+
return values.help ? 0 : 2;
|
|
65
|
+
}
|
|
66
|
+
const format = FORMATS[values.format];
|
|
67
|
+
if (!format)
|
|
68
|
+
throw new UsageError(`--format must be text, json or markdown, got "${values.format}"`);
|
|
69
|
+
const options = {
|
|
70
|
+
cyclomaticThreshold: number(values.threshold ?? values['cyclomatic-threshold'], '--threshold'),
|
|
71
|
+
cognitiveThreshold: number(values['cognitive-threshold'], '--cognitive-threshold'),
|
|
72
|
+
requireOverrideApproval: values['require-override-approval'],
|
|
73
|
+
};
|
|
74
|
+
const result = await runCommand(command, paths, values, options);
|
|
75
|
+
const report = format(result);
|
|
76
|
+
if (values.output)
|
|
77
|
+
fs.writeFileSync(values.output, `${report}\n`);
|
|
78
|
+
else
|
|
79
|
+
console.log(report);
|
|
80
|
+
return EXIT[verdict(result)];
|
|
81
|
+
}
|
|
82
|
+
let code;
|
|
83
|
+
try {
|
|
84
|
+
code = await run(process.argv.slice(2));
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
const usage = error instanceof UsageError || error.code?.startsWith('ERR_PARSE_ARGS');
|
|
88
|
+
console.error(`autoratchet: ${error instanceof Error ? error.message : String(error)}`);
|
|
89
|
+
if (usage)
|
|
90
|
+
console.error(`\n${USAGE}`);
|
|
91
|
+
code = usage ? 2 : 4;
|
|
92
|
+
}
|
|
93
|
+
process.exit(code);
|