unknot 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/CHANGELOG.md +11 -0
- package/LICENSE +21 -0
- package/README.md +203 -0
- package/bin/unknot.mjs +5 -0
- package/dist/allow.js +46 -0
- package/dist/cli.js +189 -0
- package/dist/config.js +36 -0
- package/dist/hook.js +84 -0
- package/dist/init.js +46 -0
- package/dist/model.js +525 -0
- package/dist/projects.js +133 -0
- package/dist/report.js +58 -0
- package/dist/rules/classes.js +124 -0
- package/dist/rules/graph.js +203 -0
- package/dist/rules/index.js +28 -0
- package/dist/rules/react.js +63 -0
- package/dist/rules/shape.js +74 -0
- package/dist/rules/types.js +14 -0
- package/dist/score.js +34 -0
- package/dist/sfc.js +33 -0
- package/package.json +67 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
- Ten rules: `module-cycle`, `import-cycle`, `tangle`, `field-leak`, `shallow-module`, `wide-injection`, `forward-ref`, `prop-drilling`, `wide-directory`, `long-file`.
|
|
6
|
+
- TypeScript and JavaScript, NestJS, Angular, React, Preact, Solid, Vue, Svelte, Astro, monorepos.
|
|
7
|
+
- `unknot init`: records today's debt, adds the Claude Code Stop hook and the rules for agents.
|
|
8
|
+
- `unknot --score` and `unknot --badge`: a grade from A to F in knots per 1000 files.
|
|
9
|
+
- Baseline in `.unknot.allow`: only new findings fail the run.
|
|
10
|
+
- Output formats: `text`, `json`, `sarif`, `github`.
|
|
11
|
+
- The leaderboard of popular AI-ecosystem repositories and the benchmark that produces it.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Pattern Void
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
# unknot
|
|
2
|
+
|
|
3
|
+
[](https://github.com/PatternVoid/unknot/actions/workflows/ci.yml) [](https://www.npmjs.com/package/unknot) [](LEADERBOARD.md) [](LICENSE)
|
|
4
|
+
|
|
5
|
+
**Your agent ties knots. unknot finds them and makes the agent untie them.**
|
|
6
|
+
|
|
7
|
+
Agents write code that compiles, passes tests and still ties itself up: folders that import each other, services that reach into each other's state, wrappers that wrap nothing, props carried through five components. No test fails and no linter complains, because none of it lives in one file. `unknot` reads the whole project with the TypeScript compiler, builds the real dependency graph, and stops the agent the moment a new knot appears.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npx unknot init
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
One command: today's knots are recorded as known debt, Claude Code gets a Stop hook, your `AGENTS.md` gets the rules. From this turn on the agent cannot finish with a new knot in the code.
|
|
14
|
+
|
|
15
|
+
```text
|
|
16
|
+
error[module-cycle]: 4 modules import each other; 2 imports go against the layers
|
|
17
|
+
--> src/payments/refunds.ts
|
|
18
|
+
= note: upward import: src/payments/refunds.ts -> src/orders/orders.service.ts
|
|
19
|
+
= note: upward import: src/common/errors.ts -> src/orders/order.dto.ts
|
|
20
|
+
layers, lowest first: src/common ◀ src/payments ◀ src/shipping ◀ src/orders
|
|
21
|
+
|
|
22
|
+
error[field-leak]: `Mailer.paused` is changed outside `Mailer`: 2 files in 2 modules
|
|
23
|
+
--> src/mail/mailer.service.ts:31
|
|
24
|
+
= note: src/worker/worker.service.ts:58
|
|
25
|
+
Mailer.paused ◀━ src/worker, src/cli
|
|
26
|
+
|
|
27
|
+
error[prop-drilling]: `locale` passes through 3 components that never use it
|
|
28
|
+
--> src/ui/Shell.tsx:4
|
|
29
|
+
Shell ━▶ Layout ━▶ Panel ━▶ Field
|
|
30
|
+
|
|
31
|
+
unknot: 549 files in 8.0s, 3 new (module-cycle 1, field-leak 1, prop-drilling 1), 0 allowed
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Every finding names the exact files and lines and says which way the fix goes. A cycle of fourteen folders becomes "remove these four imports".
|
|
35
|
+
|
|
36
|
+
## How knotted is your codebase
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
npx unknot --score
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
```text
|
|
43
|
+
unknot score: B 24.6 knots per 1000 files (38 findings in 1808 files)
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
A grade from A to F, measured the same way as **[the leaderboard](LEADERBOARD.md)**: the most starred TypeScript repositories of the AI ecosystem, ranked by the knots in their code. Put yours next to them:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
npx unknot --badge
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
```markdown
|
|
53
|
+
[](https://github.com/PatternVoid/unknot)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Zero configuration
|
|
57
|
+
|
|
58
|
+
`npx unknot` runs with nothing installed and nothing configured. There is no architecture to describe first: the layers are read from the code itself. It finds every `tsconfig.json` in the repository, monorepos and project references included, and reads plain JavaScript projects that have none.
|
|
59
|
+
|
|
60
|
+
| Stack | Coverage |
|
|
61
|
+
|---|---|
|
|
62
|
+
| TypeScript, JavaScript | every rule, type-aware through the TypeScript compiler |
|
|
63
|
+
| NestJS, Angular | providers, constructor injection, `inject()`, `forwardRef` |
|
|
64
|
+
| React, Preact, Solid | components and props across files |
|
|
65
|
+
| Vue, Svelte, Astro | `<script>` and `<script setup>` blocks and frontmatter join the import graph under their own file names |
|
|
66
|
+
| Monorepos | workspaces, `references`, path aliases |
|
|
67
|
+
|
|
68
|
+
## The knots
|
|
69
|
+
|
|
70
|
+
| Rule | What it finds |
|
|
71
|
+
|---|---|
|
|
72
|
+
| `module-cycle` | Folders that import each other at runtime. The finding puts them in layer order and names the few imports that go upward. |
|
|
73
|
+
| `import-cycle` | Files that import each other in a loop no folder cycle explains: inside one module, or through a parent folder. |
|
|
74
|
+
| `tangle` | Two classes in different files that use each other. |
|
|
75
|
+
| `field-leak` | Another file assigns to a field of a class with behaviour, or mutates the collection it holds. |
|
|
76
|
+
| `shallow-module` | A file full of functions that only pass their own arguments to another module. |
|
|
77
|
+
| `wide-injection` | A class that takes more than 9 collaborators (services, not values) through its constructor or `inject()`. |
|
|
78
|
+
| `forward-ref` | `forwardRef()` used to silence a dependency cycle in NestJS or Angular. |
|
|
79
|
+
| `prop-drilling` | A prop that travels through 3 or more components that only hand it down. |
|
|
80
|
+
| `wide-directory` | A directory with more than 40 source files and subdirectories. Migrations and generated `components/ui` folders do not count. |
|
|
81
|
+
| `long-file` | A file with more than 1500 lines of code. Blank lines, comments, data tables and dictionaries are not counted. |
|
|
82
|
+
|
|
83
|
+
`npx unknot --list-rules` prints them, `npx unknot --explain <rule>` says what a rule means and how to fix it from first principles.
|
|
84
|
+
|
|
85
|
+
One idea stands behind every rule: **deep modules, narrow interfaces** (John Ousterhout, *A Philosophy of Software Design*).
|
|
86
|
+
|
|
87
|
+
The rules are precise by design. An import the compiler erases is not a dependency, and neither is a lazy `import()` or a `require()` inside a function. A class named only in a type does not tangle. Reading a field is not a leak, and neither is assigning a handler slot such as `onmessage`. A facade that does real work is not a shallow module. Value objects are not wide injections. Decorated controller methods are not wrappers. A parent folder and its children are one module. What `unknot` reports is real.
|
|
88
|
+
|
|
89
|
+
## Old knots stay, new knots do not
|
|
90
|
+
|
|
91
|
+
`unknot init` writes `.unknot.allow`: the structural debt the project has today. From then on the run fails only on **new** findings. Fixing an old entry never fails anything, and a cycle that got smaller still counts as known.
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
npx unknot --update-allow # record the current state again
|
|
95
|
+
npx unknot --adopt # record findings of rules added by a new version
|
|
96
|
+
npx unknot --all # show the known debt too
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Make agents fix what they break
|
|
100
|
+
|
|
101
|
+
### Claude Code
|
|
102
|
+
|
|
103
|
+
`npx unknot init` adds this Stop hook to `.claude/settings.json`. The agent gets the report and keeps working until the structure is clean.
|
|
104
|
+
|
|
105
|
+
```json
|
|
106
|
+
{
|
|
107
|
+
"hooks": {
|
|
108
|
+
"Stop": [{ "hooks": [{ "type": "command", "command": "npx unknot hook", "timeout": 180 }] }]
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
The hook runs only when source files changed, checks the nearest folder with a `.unknot.allow` or `.unknot.json` (the repository root otherwise), and skips a tree it has already passed.
|
|
114
|
+
|
|
115
|
+
### Codex, Cursor and every other agent
|
|
116
|
+
|
|
117
|
+
`npx unknot init` writes these rules into `AGENTS.md`:
|
|
118
|
+
|
|
119
|
+
```markdown
|
|
120
|
+
Run `npx unknot` before finishing a task.
|
|
121
|
+
A finding is fixed from first principles, not by moving code around to hide it:
|
|
122
|
+
which module is the lower layer, why does anyone outside need this field,
|
|
123
|
+
what single call would the caller want. Fix the leaks of one class together.
|
|
124
|
+
Never add entries to `.unknot.allow`.
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## CI
|
|
128
|
+
|
|
129
|
+
```yaml
|
|
130
|
+
- run: npx unknot --format github
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
`--format github` annotates the pull request diff. `--format sarif` feeds GitHub code scanning, `--format json` feeds everything else.
|
|
134
|
+
|
|
135
|
+
| Exit code | Meaning |
|
|
136
|
+
|---|---|
|
|
137
|
+
| 0 | no new findings |
|
|
138
|
+
| 1 | new findings |
|
|
139
|
+
| 2 | usage or setup error |
|
|
140
|
+
|
|
141
|
+
## Options
|
|
142
|
+
|
|
143
|
+
```text
|
|
144
|
+
unknot [dir] [options]
|
|
145
|
+
|
|
146
|
+
--update-allow write every current finding into .unknot.allow
|
|
147
|
+
--adopt record findings of rules added since the baseline, keep the rest
|
|
148
|
+
--all show known debt too
|
|
149
|
+
--score grade the whole project from A to F, known debt included
|
|
150
|
+
--badge print a README badge with the grade
|
|
151
|
+
--rule <id> only these rules (repeat or separate with commas)
|
|
152
|
+
--format <name> text | json | sarif | github
|
|
153
|
+
--json same as --format json
|
|
154
|
+
--list-rules print every rule
|
|
155
|
+
--explain <id> what a rule means and how to fix it
|
|
156
|
+
|
|
157
|
+
unknot init [dir] record today's debt, add the Claude Code Stop hook and the rules for agents
|
|
158
|
+
unknot hook Claude Code Stop hook
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## Configuration
|
|
162
|
+
|
|
163
|
+
Optional `.unknot.json` in the project root:
|
|
164
|
+
|
|
165
|
+
```json
|
|
166
|
+
{
|
|
167
|
+
"projects": ["backend/tsconfig.json", "frontend/tsconfig.app.json"],
|
|
168
|
+
"ignore": ["scripts/**", "src/generated/**"],
|
|
169
|
+
"rules": {
|
|
170
|
+
"long-file": { "max": 1000 },
|
|
171
|
+
"wide-directory": { "max": 25 },
|
|
172
|
+
"wide-injection": { "max": 7 },
|
|
173
|
+
"prop-drilling": { "minComponents": 2 },
|
|
174
|
+
"shallow-module": { "minForwards": 3 },
|
|
175
|
+
"forward-ref": false
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Skipped on their own: test, spec, vitest, cypress and story files, folders named `test`, `tests`, `__tests__`, `__mocks__`, `testing`, `fixtures` and `e2e`, `.d.ts`, `.json`, `node_modules`, minified files and JavaScript build output. An unknown rule, option or key in `.unknot.json` is an error, not a silent no-op.
|
|
181
|
+
|
|
182
|
+
## How to untie a knot
|
|
183
|
+
|
|
184
|
+
- **Cycle.** Read the layer order in the finding. Move the piece both sides share into the lower layer, or invert the call. Remove the named upward imports and the whole cycle is gone.
|
|
185
|
+
- **Tangle.** One owner calls both classes; the other side receives a callback or an event and stops knowing its partner.
|
|
186
|
+
- **Field leak.** Ask what the outsider is trying to do and give the class a method that says it: `pause()` instead of `paused = true`.
|
|
187
|
+
- **Shallow module.** Call the target directly, or give the wrapper real work.
|
|
188
|
+
- **Prop drilling.** Let the owner of the value render the consumer as `children`, or let the consumer read a context or store.
|
|
189
|
+
- **Wide injection.** Group collaborators by the job they serve and split the class along those jobs.
|
|
190
|
+
|
|
191
|
+
## Develop
|
|
192
|
+
|
|
193
|
+
```bash
|
|
194
|
+
npm install
|
|
195
|
+
npm run check # types, tests, and unknot on itself
|
|
196
|
+
npm run build
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
New rules and framework support are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
200
|
+
|
|
201
|
+
## License
|
|
202
|
+
|
|
203
|
+
MIT
|
package/bin/unknot.mjs
ADDED
package/dist/allow.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { SEPARATOR } from "./rules/types.js";
|
|
3
|
+
export const ALLOW_FILE = '.unknot.allow';
|
|
4
|
+
const FIRST_RULES = ['module-cycle', 'tangle', 'field-leak', 'shallow-module'];
|
|
5
|
+
const GROUP_RULES = new Set(['module-cycle', 'import-cycle']);
|
|
6
|
+
const HEADER = ['# Structure debt that existed when this project adopted unknot.', '# Fixing an entry never fails the run; anything not listed here does.'];
|
|
7
|
+
const entryOf = (f) => `${f.rule} ${f.key}`;
|
|
8
|
+
export function readBaseline(file) {
|
|
9
|
+
if (!fs.existsSync(file))
|
|
10
|
+
return { exists: false, entries: new Set(), rules: new Set() };
|
|
11
|
+
const lines = fs.readFileSync(file, 'utf8').split('\n').map((l) => l.trim());
|
|
12
|
+
const listed = lines.find((l) => l.startsWith('# rules:'));
|
|
13
|
+
return {
|
|
14
|
+
exists: true,
|
|
15
|
+
entries: new Set(lines.filter((l) => l && !l.startsWith('#'))),
|
|
16
|
+
rules: new Set(listed ? listed.slice(8).trim().split(/\s+/).filter(Boolean) : FIRST_RULES),
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export function writeBaseline(file, findings, rules) {
|
|
20
|
+
const body = [...new Set(findings.map(entryOf))].sort();
|
|
21
|
+
fs.writeFileSync(file, [...HEADER, `# rules: ${[...rules].sort().join(' ')}`, ...body].join('\n') + '\n');
|
|
22
|
+
}
|
|
23
|
+
const folderOf = (file) => (file.includes('/') ? file.slice(0, file.lastIndexOf('/')) : '.');
|
|
24
|
+
const within = (dir, folder) => dir === folder || dir.startsWith(folder + '/');
|
|
25
|
+
export function judge(findings, baseline, active) {
|
|
26
|
+
const groups = [...baseline.entries].filter((e) => GROUP_RULES.has(e.slice(0, e.indexOf(' ')))).map((e) => ({ entry: e, rule: e.slice(0, e.indexOf(' ')), members: new Set(e.slice(e.indexOf(' ') + 1).split(SEPARATOR)) }));
|
|
27
|
+
const matched = new Set();
|
|
28
|
+
const verdict = { fresh: [], known: [], unadopted: [], fixed: [] };
|
|
29
|
+
for (const f of findings) {
|
|
30
|
+
const entry = entryOf(f);
|
|
31
|
+
const members = f.key.split(SEPARATOR);
|
|
32
|
+
const subset = GROUP_RULES.has(f.rule) ? groups.find((g) => g.rule === f.rule && members.every((m) => g.members.has(m))) : undefined;
|
|
33
|
+
const inside = f.rule === 'import-cycle' ? groups.find((g) => g.rule === 'module-cycle' && members.every((m) => [...g.members].some((folder) => within(folderOf(m), folder)))) : undefined;
|
|
34
|
+
const cover = baseline.entries.has(entry) ? entry : (subset ?? inside)?.entry;
|
|
35
|
+
if (cover) {
|
|
36
|
+
matched.add(cover);
|
|
37
|
+
verdict.known.push(f);
|
|
38
|
+
}
|
|
39
|
+
else if (baseline.exists && !baseline.rules.has(f.rule))
|
|
40
|
+
verdict.unadopted.push(f);
|
|
41
|
+
else
|
|
42
|
+
verdict.fresh.push(f);
|
|
43
|
+
}
|
|
44
|
+
verdict.fixed = [...baseline.entries].filter((e) => !matched.has(e) && active.includes(e.slice(0, e.indexOf(' '))));
|
|
45
|
+
return verdict;
|
|
46
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { ALLOW_FILE, judge, readBaseline, writeBaseline } from "./allow.js";
|
|
4
|
+
import { readConfig, SetupError } from "./config.js";
|
|
5
|
+
import { stopHook } from "./hook.js";
|
|
6
|
+
import { install } from "./init.js";
|
|
7
|
+
import { collect, emptyModel } from "./model.js";
|
|
8
|
+
import { createProgram, expandProject, findTsconfigs, globToRegExp, isSource, looseProject } from "./projects.js";
|
|
9
|
+
import { realName } from "./sfc.js";
|
|
10
|
+
import { FORMATS, render } from "./report.js";
|
|
11
|
+
import { checkRules, RULES, runRules } from "./rules/index.js";
|
|
12
|
+
import { describe } from "./rules/types.js";
|
|
13
|
+
import { badge, score, scoreLine } from "./score.js";
|
|
14
|
+
const HELP = `unknot [dir] [options]
|
|
15
|
+
|
|
16
|
+
Structure linter for TypeScript: deep modules, narrow interfaces.
|
|
17
|
+
Findings listed in ${ALLOW_FILE} are known debt and do not fail the run.
|
|
18
|
+
|
|
19
|
+
--update-allow write every current finding into ${ALLOW_FILE}
|
|
20
|
+
--adopt record findings of rules added since the baseline, keep the rest
|
|
21
|
+
--all show known debt too
|
|
22
|
+
--score grade the whole project from A to F, known debt included
|
|
23
|
+
--badge print a README badge with the grade
|
|
24
|
+
--rule <id> only these rules (repeat or separate with commas)
|
|
25
|
+
--format <name> ${FORMATS.join(' | ')}
|
|
26
|
+
--json same as --format json
|
|
27
|
+
--list-rules print every rule
|
|
28
|
+
--explain <id> what a rule means and how to fix it
|
|
29
|
+
--version, --help
|
|
30
|
+
|
|
31
|
+
unknot init [dir] record today's debt, add the Claude Code Stop hook and the rules for agents
|
|
32
|
+
unknot hook Claude Code Stop hook: check the project the agent worked in
|
|
33
|
+
|
|
34
|
+
Exit code: 0 clean, 1 new findings, 2 usage or setup error.`;
|
|
35
|
+
class UsageError extends SetupError {
|
|
36
|
+
}
|
|
37
|
+
function parse(argv) {
|
|
38
|
+
const out = { dir: '.', update: false, adopt: false, all: false, score: false, badge: false, format: 'text', rules: [], explain: null, mode: 'check' };
|
|
39
|
+
const dirs = [];
|
|
40
|
+
if (argv[0] === 'hook' || argv[0] === 'help')
|
|
41
|
+
return { ...out, mode: argv[0] };
|
|
42
|
+
if (argv[0] === 'init') {
|
|
43
|
+
if (argv.length > 2 || argv[1]?.startsWith('-'))
|
|
44
|
+
throw new UsageError('unknot init takes one optional directory');
|
|
45
|
+
return { ...out, mode: 'init', dir: argv[1] ?? '.' };
|
|
46
|
+
}
|
|
47
|
+
const queue = argv.flatMap((a) => (a.startsWith('--') && a.includes('=') ? [a.slice(0, a.indexOf('=')), a.slice(a.indexOf('=') + 1)] : [a]));
|
|
48
|
+
const value = (flag) => {
|
|
49
|
+
const v = queue.shift();
|
|
50
|
+
if (v === undefined)
|
|
51
|
+
throw new UsageError(`${flag} needs a value`);
|
|
52
|
+
return v;
|
|
53
|
+
};
|
|
54
|
+
while (queue.length) {
|
|
55
|
+
const a = queue.shift();
|
|
56
|
+
if (a === '--update-allow')
|
|
57
|
+
out.update = true;
|
|
58
|
+
else if (a === '--adopt')
|
|
59
|
+
out.adopt = true;
|
|
60
|
+
else if (a === '--all')
|
|
61
|
+
out.all = true;
|
|
62
|
+
else if (a === '--score')
|
|
63
|
+
out.score = true;
|
|
64
|
+
else if (a === '--badge')
|
|
65
|
+
out.badge = true;
|
|
66
|
+
else if (a === '--json')
|
|
67
|
+
out.format = 'json';
|
|
68
|
+
else if (a === '--format') {
|
|
69
|
+
const f = value(a);
|
|
70
|
+
if (!FORMATS.includes(f))
|
|
71
|
+
throw new UsageError(`unknown format ${f}: use ${FORMATS.join(', ')}`);
|
|
72
|
+
out.format = f;
|
|
73
|
+
}
|
|
74
|
+
else if (a === '--rule')
|
|
75
|
+
out.rules.push(...value(a).split(','));
|
|
76
|
+
else if (a === '--explain') {
|
|
77
|
+
out.explain = value(a);
|
|
78
|
+
out.mode = 'explain';
|
|
79
|
+
}
|
|
80
|
+
else if (a === '--list-rules')
|
|
81
|
+
out.mode = 'list';
|
|
82
|
+
else if (a === '-h' || a === '--help')
|
|
83
|
+
out.mode = 'help';
|
|
84
|
+
else if (a === '-v' || a === '--version')
|
|
85
|
+
out.mode = 'version';
|
|
86
|
+
else if (a.startsWith('-'))
|
|
87
|
+
throw new UsageError(`unknown option ${a}`);
|
|
88
|
+
else
|
|
89
|
+
dirs.push(a);
|
|
90
|
+
}
|
|
91
|
+
if (dirs.length > 1)
|
|
92
|
+
throw new UsageError(`one directory at a time, got ${dirs.join(' and ')}`);
|
|
93
|
+
out.dir = dirs[0] ?? '.';
|
|
94
|
+
const unknown = [...out.rules, ...(out.explain ? [out.explain] : [])].find((id) => !RULES.some((r) => r.id === id));
|
|
95
|
+
if (unknown)
|
|
96
|
+
throw new UsageError(`unknown rule ${unknown}: see --list-rules`);
|
|
97
|
+
if (out.update && out.adopt)
|
|
98
|
+
throw new UsageError('--update-allow and --adopt do not go together');
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
function version() {
|
|
102
|
+
const file = path.join(import.meta.dirname, '..', 'package.json');
|
|
103
|
+
return JSON.parse(fs.readFileSync(file, 'utf8')).version;
|
|
104
|
+
}
|
|
105
|
+
function check(opts) {
|
|
106
|
+
const root = path.resolve(opts.dir);
|
|
107
|
+
if (!fs.statSync(root, { throwIfNoEntry: false })?.isDirectory())
|
|
108
|
+
throw new UsageError(`${root}: no such directory`);
|
|
109
|
+
const config = readConfig(root);
|
|
110
|
+
checkRules(config);
|
|
111
|
+
const ignore = (config.ignore ?? []).map(globToRegExp);
|
|
112
|
+
const configs = config.projects?.length ? config.projects.map((p) => path.resolve(root, p)) : findTsconfigs(root);
|
|
113
|
+
const seen = new Set();
|
|
114
|
+
const loose = configs.length ? null : looseProject(root);
|
|
115
|
+
const projects = loose ? [loose] : configs.flatMap((c) => expandProject(c, seen));
|
|
116
|
+
if (!projects.length)
|
|
117
|
+
throw new UsageError(`no TypeScript or JavaScript sources under ${root}`);
|
|
118
|
+
const model = emptyModel(root);
|
|
119
|
+
const started = Date.now();
|
|
120
|
+
const covered = new Set();
|
|
121
|
+
for (const project of projects) {
|
|
122
|
+
const files = [...project.parsed.fileNames, ...project.components];
|
|
123
|
+
if (files.every((f) => covered.has(f)))
|
|
124
|
+
continue;
|
|
125
|
+
const program = createProgram(project);
|
|
126
|
+
collect(model, program, (file) => isSource(file, root, ignore));
|
|
127
|
+
for (const sf of program.getSourceFiles())
|
|
128
|
+
covered.add(realName(sf.fileName));
|
|
129
|
+
}
|
|
130
|
+
const active = RULES.map((r) => r.id).filter((id) => config.rules?.[id] !== false);
|
|
131
|
+
const findings = runRules(model, config).filter((f) => !opts.rules.length || opts.rules.includes(f.rule));
|
|
132
|
+
const allowPath = path.join(root, ALLOW_FILE);
|
|
133
|
+
const baseline = readBaseline(allowPath);
|
|
134
|
+
const verdict = judge(findings, baseline, opts.rules.length ? opts.rules : active);
|
|
135
|
+
if (opts.update || opts.adopt) {
|
|
136
|
+
if (opts.rules.length)
|
|
137
|
+
throw new UsageError('--rule cannot be combined with writing the baseline');
|
|
138
|
+
const kept = opts.update ? findings : [...verdict.known, ...verdict.unadopted];
|
|
139
|
+
writeBaseline(allowPath, kept, active);
|
|
140
|
+
console.log(`unknot: ${kept.length} findings recorded in ${ALLOW_FILE}${opts.adopt && verdict.fresh.length ? `; ${verdict.fresh.length} new findings left to fix` : ''}`);
|
|
141
|
+
return opts.adopt && verdict.fresh.length ? 1 : 0;
|
|
142
|
+
}
|
|
143
|
+
if (opts.score || opts.badge) {
|
|
144
|
+
if (opts.rules.length)
|
|
145
|
+
throw new UsageError('--rule cannot be combined with the score');
|
|
146
|
+
const graded = score(findings, model.files.size);
|
|
147
|
+
if (opts.format === 'json')
|
|
148
|
+
console.log(JSON.stringify(graded, null, 2));
|
|
149
|
+
else
|
|
150
|
+
console.log(opts.badge ? badge(graded) : scoreLine(graded));
|
|
151
|
+
return 0;
|
|
152
|
+
}
|
|
153
|
+
console.log(render(opts.format, verdict, RULES, { files: model.files.size, seconds: (Date.now() - started) / 1000, showKnown: opts.all, tty: !!process.stdout.isTTY }));
|
|
154
|
+
return verdict.fresh.length ? 1 : 0;
|
|
155
|
+
}
|
|
156
|
+
export function main(argv = process.argv.slice(2)) {
|
|
157
|
+
try {
|
|
158
|
+
const opts = parse(argv);
|
|
159
|
+
if (opts.mode === 'help')
|
|
160
|
+
console.log(HELP);
|
|
161
|
+
else if (opts.mode === 'version')
|
|
162
|
+
console.log(version());
|
|
163
|
+
else if (opts.mode === 'list')
|
|
164
|
+
for (const r of RULES)
|
|
165
|
+
console.log(`${r.id.padEnd(16)} ${r.scope.padEnd(42)} ${describe(r, {})}`);
|
|
166
|
+
else if (opts.mode === 'hook')
|
|
167
|
+
stopHook(process.argv[1]);
|
|
168
|
+
else if (opts.mode === 'init') {
|
|
169
|
+
const root = path.resolve(opts.dir);
|
|
170
|
+
if (!fs.existsSync(path.join(root, ALLOW_FILE)))
|
|
171
|
+
check({ ...opts, update: true });
|
|
172
|
+
else
|
|
173
|
+
console.log(`unknot: ${ALLOW_FILE} already there, debt left as recorded`);
|
|
174
|
+
for (const line of install(root))
|
|
175
|
+
console.log(`unknot: ${line}`);
|
|
176
|
+
}
|
|
177
|
+
else if (opts.mode === 'explain') {
|
|
178
|
+
const r = RULES.find((x) => x.id === opts.explain);
|
|
179
|
+
console.log(`${r.id} (${r.scope})\n\n${describe(r, readConfig(path.resolve(opts.dir)))}\n\nFix: ${r.fix}`);
|
|
180
|
+
}
|
|
181
|
+
else
|
|
182
|
+
return check(opts);
|
|
183
|
+
return 0;
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
console.error(`unknot: ${error instanceof SetupError ? error.message : `internal error, please report it: ${error.stack ?? error}`}`);
|
|
187
|
+
return 2;
|
|
188
|
+
}
|
|
189
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
export class SetupError extends Error {
|
|
4
|
+
}
|
|
5
|
+
export function readConfig(root) {
|
|
6
|
+
const file = path.join(root, '.unknot.json');
|
|
7
|
+
if (!fs.existsSync(file))
|
|
8
|
+
return {};
|
|
9
|
+
let raw;
|
|
10
|
+
try {
|
|
11
|
+
raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
12
|
+
}
|
|
13
|
+
catch (error) {
|
|
14
|
+
throw new SetupError(`.unknot.json is not valid JSON: ${error.message}`);
|
|
15
|
+
}
|
|
16
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
17
|
+
throw new SetupError('.unknot.json must hold an object');
|
|
18
|
+
const config = raw;
|
|
19
|
+
const strings = (value) => value === undefined || (Array.isArray(value) && value.every((v) => typeof v === 'string'));
|
|
20
|
+
if (!strings(config.projects))
|
|
21
|
+
throw new SetupError('.unknot.json "projects" must be a list of paths');
|
|
22
|
+
if (!strings(config.ignore))
|
|
23
|
+
throw new SetupError('.unknot.json "ignore" must be a list of globs');
|
|
24
|
+
if (config.rules !== undefined && (!config.rules || typeof config.rules !== 'object' || Array.isArray(config.rules)))
|
|
25
|
+
throw new SetupError('.unknot.json "rules" must be an object');
|
|
26
|
+
const unknown = Object.keys(config).find((key) => !['projects', 'ignore', 'rules'].includes(key));
|
|
27
|
+
if (unknown)
|
|
28
|
+
throw new SetupError(`.unknot.json has an unknown key "${unknown}": use projects, ignore, rules`);
|
|
29
|
+
for (const project of config.projects ?? [])
|
|
30
|
+
if (!fs.existsSync(path.resolve(root, project)))
|
|
31
|
+
throw new SetupError(`.unknot.json "projects": ${project} does not exist`);
|
|
32
|
+
return config;
|
|
33
|
+
}
|
|
34
|
+
export function enabled(config, rule) {
|
|
35
|
+
return config.rules?.[rule] !== false;
|
|
36
|
+
}
|
package/dist/hook.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { ALLOW_FILE } from "./allow.js";
|
|
7
|
+
const SOURCE = /\.([cm]?[jt]sx?|vue|svelte|astro)$/;
|
|
8
|
+
const RECENT = '3 hours ago';
|
|
9
|
+
const ADVICE = 'Fix each finding from first principles (which layer is lower, why outsiders need the field, what the wrapper adds); do not add them to the allow file.';
|
|
10
|
+
function git(cwd, ...args) {
|
|
11
|
+
const r = spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
|
|
12
|
+
return r.status === 0 ? r.stdout : null;
|
|
13
|
+
}
|
|
14
|
+
function readInput() {
|
|
15
|
+
try {
|
|
16
|
+
return JSON.parse(fs.readFileSync(0, 'utf8') || '{}');
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return {};
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function projectRoot(cwd, top) {
|
|
23
|
+
for (let dir = cwd; dir.startsWith(top); dir = path.dirname(dir)) {
|
|
24
|
+
if (fs.existsSync(path.join(dir, ALLOW_FILE)) || fs.existsSync(path.join(dir, '.unknot.json')))
|
|
25
|
+
return dir;
|
|
26
|
+
if (dir === top)
|
|
27
|
+
break;
|
|
28
|
+
}
|
|
29
|
+
return top;
|
|
30
|
+
}
|
|
31
|
+
export function stopHook(cli) {
|
|
32
|
+
const input = readInput();
|
|
33
|
+
if (input.stop_hook_active)
|
|
34
|
+
return;
|
|
35
|
+
const given = path.resolve(input.cwd || process.cwd());
|
|
36
|
+
const cwd = fs.existsSync(given) ? fs.realpathSync(given) : given;
|
|
37
|
+
const top = git(cwd, 'rev-parse', '--show-toplevel')?.trim();
|
|
38
|
+
if (!top)
|
|
39
|
+
return;
|
|
40
|
+
const root = projectRoot(cwd, top);
|
|
41
|
+
const status = git(top, 'status', '--porcelain', '--untracked-files=all', '-z') ?? '';
|
|
42
|
+
const recent = git(top, 'log', `--since=${RECENT}`, '--name-only', '--pretty=format:', '-z') ?? '';
|
|
43
|
+
const changed = status.split('\0').filter(Boolean);
|
|
44
|
+
const touched = [...changed.map((l) => l.slice(3)), ...recent.split(/[\0\n]/)].some((f) => SOURCE.test(f) && !f.endsWith('.d.ts'));
|
|
45
|
+
if (!touched)
|
|
46
|
+
return;
|
|
47
|
+
const untracked = changed.filter((l) => l.startsWith('??')).map((l) => {
|
|
48
|
+
const stat = fs.statSync(path.join(top, l.slice(3)), { throwIfNoEntry: false });
|
|
49
|
+
return `${l}:${stat?.size}:${stat?.mtimeMs}`;
|
|
50
|
+
});
|
|
51
|
+
const state = createHash('sha256').update(root).update(git(top, 'rev-parse', 'HEAD') ?? '').update(status).update(git(top, 'diff', 'HEAD') ?? '').update(untracked.join('\n')).digest('hex');
|
|
52
|
+
const dir = path.join(os.tmpdir(), 'unknot-hook');
|
|
53
|
+
const mark = path.join(dir, createHash('sha256').update(root).digest('hex').slice(0, 16));
|
|
54
|
+
if (fs.existsSync(mark) && fs.readFileSync(mark, 'utf8') === state)
|
|
55
|
+
return;
|
|
56
|
+
const say = (message) => console.log(JSON.stringify(message));
|
|
57
|
+
const run = (...args) => spawnSync(process.execPath, [cli, root, ...args], { encoding: 'utf8', timeout: 150_000, maxBuffer: 16 * 1024 * 1024 });
|
|
58
|
+
const broken = (r) => (r.status === 0 || r.status === 1 ? null : `unknot could not check ${root}: ${(r.stderr || r.error?.message || 'no output').trim().split('\n')[0]}`);
|
|
59
|
+
if (!fs.existsSync(path.join(root, ALLOW_FILE))) {
|
|
60
|
+
const adopted = run('--update-allow');
|
|
61
|
+
say({ systemMessage: broken(adopted) ?? `${adopted.stdout.trim()} (${path.basename(root)}: first run, existing debt recorded)` });
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
let checked = run();
|
|
65
|
+
let note;
|
|
66
|
+
if (checked.stdout.includes('unknot --adopt')) {
|
|
67
|
+
const adopted = run('--adopt');
|
|
68
|
+
if (adopted.status === 0 || adopted.status === 1)
|
|
69
|
+
note = `${adopted.stdout.trim()} (${path.basename(root)}: debt found by new unknot rules recorded)`;
|
|
70
|
+
checked = run();
|
|
71
|
+
}
|
|
72
|
+
if (checked.status === 0) {
|
|
73
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
74
|
+
fs.writeFileSync(mark, state);
|
|
75
|
+
if (note)
|
|
76
|
+
say({ systemMessage: note });
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const failure = broken(checked);
|
|
80
|
+
if (failure)
|
|
81
|
+
return say({ systemMessage: failure });
|
|
82
|
+
const report = checked.stdout.trim().split('\n').slice(-120).join('\n');
|
|
83
|
+
say({ decision: 'block', reason: `unknot found new structure problems in ${root}. ${ADVICE}\n\n${report}`, ...(note ? { systemMessage: note } : {}) });
|
|
84
|
+
}
|
package/dist/init.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { ALLOW_FILE } from "./allow.js";
|
|
4
|
+
import { SetupError } from "./config.js";
|
|
5
|
+
const HOOK_COMMAND = 'npx unknot hook';
|
|
6
|
+
const AGENT_RULES = `## Structure
|
|
7
|
+
|
|
8
|
+
Run \`npx unknot\` before finishing a task.
|
|
9
|
+
A finding is fixed from first principles, not by moving code around to hide it:
|
|
10
|
+
which module is the lower layer, why does anyone outside need this field,
|
|
11
|
+
what single call would the caller want. Fix the leaks of one class together.
|
|
12
|
+
Never add entries to \`${ALLOW_FILE}\`.
|
|
13
|
+
`;
|
|
14
|
+
function addHook(root) {
|
|
15
|
+
const file = path.join(root, '.claude', 'settings.json');
|
|
16
|
+
const shown = path.relative(root, file);
|
|
17
|
+
let settings = {};
|
|
18
|
+
if (fs.existsSync(file)) {
|
|
19
|
+
try {
|
|
20
|
+
settings = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
throw new SetupError(`${file} is not valid JSON: ${error.message}`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
const stop = settings.hooks?.Stop ?? [];
|
|
27
|
+
if (stop.some((group) => group.hooks?.some((hook) => hook.command?.includes('unknot hook'))))
|
|
28
|
+
return `${shown}: Stop hook already there`;
|
|
29
|
+
settings.hooks = { ...settings.hooks, Stop: [...stop, { hooks: [{ type: 'command', command: HOOK_COMMAND, timeout: 180 }] }] };
|
|
30
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
31
|
+
fs.writeFileSync(file, `${JSON.stringify(settings, null, 2)}\n`);
|
|
32
|
+
return `${shown}: Stop hook added, Claude Code cannot finish a turn that ties a new knot`;
|
|
33
|
+
}
|
|
34
|
+
function addAgentRules(root) {
|
|
35
|
+
const name = ['AGENTS.md', 'CLAUDE.md'].find((candidate) => fs.existsSync(path.join(root, candidate))) ?? 'AGENTS.md';
|
|
36
|
+
const file = path.join(root, name);
|
|
37
|
+
const current = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
|
|
38
|
+
if (current.includes('npx unknot'))
|
|
39
|
+
return `${name}: rules already there`;
|
|
40
|
+
const gap = current ? (current.endsWith('\n') ? '\n' : '\n\n') : '';
|
|
41
|
+
fs.writeFileSync(file, `${current}${gap}${AGENT_RULES}`);
|
|
42
|
+
return `${name}: rules for agents ${current ? 'added' : 'written'}`;
|
|
43
|
+
}
|
|
44
|
+
export function install(root) {
|
|
45
|
+
return [addHook(root), addAgentRules(root)];
|
|
46
|
+
}
|