unknot 0.1.0 → 0.1.1

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 CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.1
4
+
5
+ - `long-file` counts lines of code exactly: blank lines, comments and JSDoc after a template literal are no longer counted. A dictionary with a few formatter functions and `export default { ... }` tables are data.
6
+ - Generated files (`@generated`, `DO NOT EDIT`, `autogenerated` header or a `generated` folder), vendored code (`vendored`, `third_party`), agent folders and `examples` / `benchmarks` beside the product source are not read.
7
+ - `field-leak`: a callback slot of any name assigned from outside is not a leak.
8
+ - `prop-drilling`: binding a prop to an event of a child (`onClick={onKeep}`) is a use, not a pass-through.
9
+ - Score: tangles count once per hub class, prop drilling once per starting component, and a forwardRef pair is not counted again as a tangle.
10
+ - The leaderboard is measured again with these rules at the same commits; `bench/run.mjs --again` repeats a measurement at the recorded commit.
11
+ - A second hand check of 165 findings from the 10 lowest-graded repositories is in `bench/audit/recheck-lowest-grades.json`.
12
+
3
13
  ## 0.1.0
4
14
 
5
15
  - Ten rules: `module-cycle`, `import-cycle`, `tangle`, `field-leak`, `shallow-module`, `wide-injection`, `forward-ref`, `prop-drilling`, `wide-directory`, `long-file`.
package/README.md CHANGED
@@ -1,39 +1,94 @@
1
- # unknot
1
+ <h1 align="center">unknot</h1>
2
2
 
3
- [![ci](https://github.com/PatternVoid/unknot/actions/workflows/ci.yml/badge.svg)](https://github.com/PatternVoid/unknot/actions/workflows/ci.yml) [![npm](https://img.shields.io/npm/v/unknot)](https://www.npmjs.com/package/unknot) [![unknot: A](https://img.shields.io/badge/unknot-A-brightgreen)](LEADERBOARD.md) [![license](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
3
+ <p align="center">
4
+ <b>Architecture linter for TypeScript and JavaScript code written by AI agents.</b><br>
5
+ Finds the structural knots no test and no file-level linter can see, grades the codebase from A to F,<br>and stops the agent before it finishes a task with a new one.
6
+ </p>
4
7
 
5
- **Your agent ties knots. unknot finds them and makes the agent untie them.**
8
+ <p align="center">
9
+ <a href="https://www.npmjs.com/package/unknot"><img src="https://img.shields.io/npm/v/unknot?style=flat-square&color=24292f" alt="npm version"></a>
10
+ <a href="https://github.com/PatternVoid/unknot/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/PatternVoid/unknot/ci.yml?style=flat-square&label=ci" alt="ci"></a>
11
+ <a href="LEADERBOARD.md"><img src="https://img.shields.io/badge/unknot-A-2ea043?style=flat-square" alt="unknot grade: A"></a>
12
+ <img src="https://img.shields.io/node/v/unknot?style=flat-square&color=24292f" alt="node version">
13
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-24292f?style=flat-square" alt="MIT license"></a>
14
+ </p>
6
15
 
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.
16
+ <p align="center">
17
+ <a href="#quick-start">Quick start</a> ·
18
+ <a href="#the-leaderboard">Leaderboard</a> ·
19
+ <a href="#the-rules">Rules</a> ·
20
+ <a href="#agents">Agents</a> ·
21
+ <a href="#ci">CI</a> ·
22
+ <a href="#configuration">Configuration</a>
23
+ </p>
24
+
25
+ <p align="center">
26
+ <img src="https://raw.githubusercontent.com/PatternVoid/unknot/main/assets/terminal.svg" width="880" alt="unknot reports a module cycle, a field leak and prop drilling with exact files and lines, then grades the project B">
27
+ </p>
28
+
29
+ ## Why
30
+
31
+ An agent writes code that compiles and passes every test, and still ties the project into knots: folders that import each other, services that reach into each other's state, wrappers that wrap nothing, props carried through five components. ESLint checks one file at a time and tests check behaviour, so nothing fails. The cost shows up later, when every next change is harder than the last.
32
+
33
+ `unknot` reads the whole TypeScript or JavaScript project through the TypeScript compiler, builds the real dependency graph and reports each knot with the exact files, the lines and the direction of the fix. A cycle of fourteen folders becomes "remove these four imports".
34
+
35
+ <table>
36
+ <tr><td width="220"><b>Whole-project analysis</b></td><td>Type-aware, built on the TypeScript compiler. Erased type imports, lazy <code>import()</code> and handler slots are understood, so what is reported is real.</td></tr>
37
+ <tr><td width="220"><b>Zero configuration</b></td><td><code>npx unknot</code> and nothing else. Layers are read from the code. Monorepos, project references, path aliases and plain JavaScript work out of the box.</td></tr>
38
+ <tr><td width="220"><b>A grade from A to F</b></td><td>One number for the structure of a codebase, on the same scale as <a href="#the-leaderboard">the leaderboard</a> of 104 popular AI repositories.</td></tr>
39
+ <tr><td width="220"><b>Built for agents</b></td><td>A Claude Code Stop hook, <code>AGENTS.md</code> rules for Codex and Cursor, and a CI step. The agent gets the report and keeps working until the structure is clean.</td></tr>
40
+ <tr><td width="220"><b>Fits an existing project</b></td><td>Today's knots are recorded as known debt. Only new ones fail.</td></tr>
41
+ </table>
42
+
43
+ Works with TypeScript, JavaScript, NestJS, Angular, React, Preact, Solid, Vue, Svelte and Astro.
44
+
45
+ ## Quick start
8
46
 
9
47
  ```bash
10
- npx unknot init
48
+ npx unknot # report the knots
49
+ npx unknot --score # grade the project from A to F
50
+ npx unknot init # record today's debt and guard the code from now on
11
51
  ```
12
52
 
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.
53
+ `unknot init` does three things: writes today's knots to `.unknot.allow` as known debt, adds a Stop hook to Claude Code, and puts the rules into `AGENTS.md`. From that turn on the agent cannot finish with a new knot in the code.
14
54
 
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
- ```
55
+ Requires Node 20.11 or newer. Nothing to install, nothing to configure.
56
+
57
+ ## The leaderboard
58
+
59
+ <!-- leaderboard:start -->
60
+ We ran `unknot` with zero configuration over the **104 most starred TypeScript repositories of the AI ecosystem**: 408,275 source files, 7,190 structural findings, every one published with its file and line.
61
+
62
+ | Grade | ![A](https://img.shields.io/badge/-A-2ea043?style=flat-square) | ![B](https://img.shields.io/badge/-B-56a64b?style=flat-square) | ![C](https://img.shields.io/badge/-C-bf8700?style=flat-square) | ![D](https://img.shields.io/badge/-D-bc4c00?style=flat-square) | ![F](https://img.shields.io/badge/-F-cf222e?style=flat-square) |
63
+ |---|---|---|---|---|---|
64
+ | Repositories | 21 | 28 | 26 | 19 | 10 |
33
65
 
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".
66
+ The 15 most starred of them, and where each one stands:
35
67
 
36
- ## How knotted is your codebase
68
+ | Grade | Repository | Stars | Files | Knots / 1000 files | Rank |
69
+ |---|---|---|---|---|---|
70
+ | ![C](https://img.shields.io/badge/-C-bf8700?style=flat-square) | [morluto/rea](https://github.com/morluto/rea) | 479k | 3,380 | 32.3 | 71 of 104 |
71
+ | ![A](https://img.shields.io/badge/-A-2ea043?style=flat-square) | [openclaw/openclaw](https://github.com/openclaw/openclaw) | 395k | 31,517 | 13.0 | 9 of 104 |
72
+ | ![B](https://img.shields.io/badge/-B-56a64b?style=flat-square) | [deepseek-ai/deepseek-harness](https://github.com/deepseek-ai/deepseek-harness) | 287k | 3,797 | 23.7 | 36 of 104 |
73
+ | ![D](https://img.shields.io/badge/-D-bc4c00?style=flat-square) | [n8n-io/n8n](https://github.com/n8n-io/n8n) | 212k | 15,617 | 42.9 | 87 of 104 |
74
+ | ![C](https://img.shields.io/badge/-C-bf8700?style=flat-square) | [firecrawl/firecrawl](https://github.com/firecrawl/firecrawl) | 210k | 271 | 31.5 | 66 of 104 |
75
+ | ![A](https://img.shields.io/badge/-A-2ea043?style=flat-square) | [stablyai/orca](https://github.com/stablyai/orca) | 139k | 30,356 | 12.8 | 8 of 104 |
76
+ | ![A](https://img.shields.io/badge/-A-2ea043?style=flat-square) | [shadcn-ui/ui](https://github.com/shadcn-ui/ui) | 129k | 1,671 | 8.1 | 4 of 104 |
77
+ | ![C](https://img.shields.io/badge/-C-bf8700?style=flat-square) | [thedotmack/claude-mem](https://github.com/thedotmack/claude-mem) | 120k | 1,131 | 28.0 | 54 of 104 |
78
+ | ![D](https://img.shields.io/badge/-D-bc4c00?style=flat-square) | [paperclipai/paperclip](https://github.com/paperclipai/paperclip) | 117k | 6,024 | 39.5 | 82 of 104 |
79
+ | ![A](https://img.shields.io/badge/-A-2ea043?style=flat-square) | [supabase/supabase](https://github.com/supabase/supabase) | 116k | 6,859 | 17.3 | 20 of 104 |
80
+ | ![D](https://img.shields.io/badge/-D-bc4c00?style=flat-square) | [google-gemini/gemini-cli](https://github.com/google-gemini/gemini-cli) | 109k | 1,205 | 47.2 | 94 of 104 |
81
+ | ![A](https://img.shields.io/badge/-A-2ea043?style=flat-square) | [Egonex-AI/Understand-Anything](https://github.com/Egonex-AI/Understand-Anything) | 95k | 204 | 2.0 | 1 of 104 |
82
+ | ![A](https://img.shields.io/badge/-A-2ea043?style=flat-square) | [OpenHands/OpenHands](https://github.com/OpenHands/OpenHands) | 94k | 1,541 | 15.2 | 15 of 104 |
83
+ | ![C](https://img.shields.io/badge/-C-bf8700?style=flat-square) | [koala73/worldmonitor](https://github.com/koala73/worldmonitor) | 91k | 1,316 | 31.6 | 67 of 104 |
84
+ | ![B](https://img.shields.io/badge/-B-56a64b?style=flat-square) | [cheaper-inference/OmniRoute](https://github.com/cheaper-inference/OmniRoute) | 90k | 7,326 | 19.3 | 26 of 104 |
85
+
86
+ Cleanest of all: [Egonex-AI/Understand-Anything](https://github.com/Egonex-AI/Understand-Anything) at 2.0 knots per 1000 files. Knottiest: [teambit/bit](https://github.com/teambit/bit) at 128.5.
87
+
88
+ **[Full leaderboard: all 104 repositories, the method and every finding →](LEADERBOARD.md)**
89
+ <!-- leaderboard:end -->
90
+
91
+ ### Grade your own
37
92
 
38
93
  ```bash
39
94
  npx unknot --score
@@ -43,29 +98,13 @@ npx unknot --score
43
98
  unknot score: B 24.6 knots per 1000 files (38 findings in 1808 files)
44
99
  ```
45
100
 
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
- ```
101
+ `npx unknot --badge` prints a badge for your README:
51
102
 
52
103
  ```markdown
53
104
  [![unknot: B](https://img.shields.io/badge/unknot-B-green)](https://github.com/PatternVoid/unknot)
54
105
  ```
55
106
 
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
107
+ ## The rules
69
108
 
70
109
  | Rule | What it finds |
71
110
  |---|---|
@@ -80,11 +119,21 @@ npx unknot --badge
80
119
  | `wide-directory` | A directory with more than 40 source files and subdirectories. Migrations and generated `components/ui` folders do not count. |
81
120
  | `long-file` | A file with more than 1500 lines of code. Blank lines, comments, data tables and dictionaries are not counted. |
82
121
 
83
- `npx unknot --list-rules` prints them, `npx unknot --explain <rule>` says what a rule means and how to fix it from first principles.
122
+ `npx unknot --list-rules` prints them. `npx unknot --explain <rule>` says what a rule means and how to fix it from first principles.
84
123
 
85
124
  One idea stands behind every rule: **deep modules, narrow interfaces** (John Ousterhout, *A Philosophy of Software Design*).
86
125
 
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.
126
+ **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 callback slot such as `onmessage`. Binding a prop to an event of a child is using it, not drilling it. A dictionary with a few formatter functions is data, not a long file. 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.
127
+
128
+ ### Stack coverage
129
+
130
+ | Stack | Coverage |
131
+ |---|---|
132
+ | TypeScript, JavaScript | every rule, type-aware through the TypeScript compiler |
133
+ | NestJS, Angular | providers, constructor injection, `inject()`, `forwardRef` |
134
+ | React, Preact, Solid | components and props across files |
135
+ | Vue, Svelte, Astro | `<script>` and `<script setup>` blocks and frontmatter join the import graph under their own file names |
136
+ | Monorepos | every `tsconfig.json`, workspaces, `references`, path aliases |
88
137
 
89
138
  ## Old knots stay, new knots do not
90
139
 
@@ -96,7 +145,7 @@ npx unknot --adopt # record findings of rules added by a new version
96
145
  npx unknot --all # show the known debt too
97
146
  ```
98
147
 
99
- ## Make agents fix what they break
148
+ ## Agents
100
149
 
101
150
  ### Claude Code
102
151
 
@@ -138,7 +187,23 @@ Never add entries to `.unknot.allow`.
138
187
  | 1 | new findings |
139
188
  | 2 | usage or setup error |
140
189
 
141
- ## Options
190
+ ## How to untie a knot
191
+
192
+ | Knot | The fix |
193
+ |---|---|
194
+ | 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. |
195
+ | Tangle | One owner calls both classes; the other side receives a callback or an event and stops knowing its partner. |
196
+ | Field leak | Ask what the outsider is trying to do and give the class a method that says it: `pause()` instead of `paused = true`. |
197
+ | Shallow module | Call the target directly, or give the wrapper real work. |
198
+ | Prop drilling | Let the owner of the value render the consumer as `children`, or let the consumer read a context or store. |
199
+ | Wide injection | Group collaborators by the job they serve and split the class along those jobs. |
200
+
201
+ ## Configuration
202
+
203
+ None is needed. Everything below is optional.
204
+
205
+ <details>
206
+ <summary><b>Command line options</b></summary>
142
207
 
143
208
  ```text
144
209
  unknot [dir] [options]
@@ -158,9 +223,10 @@ unknot init [dir] record today's debt, add the Claude Code Stop hook and the
158
223
  unknot hook Claude Code Stop hook
159
224
  ```
160
225
 
161
- ## Configuration
226
+ </details>
162
227
 
163
- Optional `.unknot.json` in the project root:
228
+ <details>
229
+ <summary><b><code>.unknot.json</code></b></summary>
164
230
 
165
231
  ```json
166
232
  {
@@ -177,18 +243,11 @@ Optional `.unknot.json` in the project root:
177
243
  }
178
244
  ```
179
245
 
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
246
+ 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. Generated files (a `@generated`, `DO NOT EDIT` or `autogenerated` header, `generated` folders), vendored code (`vendored`, `third_party`) and `examples` and `benchmarks` folders that sit beside the product source are skipped too. An unknown rule, option or key in `.unknot.json` is an error, not a silent no-op.
183
247
 
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.
248
+ </details>
190
249
 
191
- ## Develop
250
+ ## Contributing
192
251
 
193
252
  ```bash
194
253
  npm install
@@ -196,8 +255,8 @@ npm run check # types, tests, and unknot on itself
196
255
  npm run build
197
256
  ```
198
257
 
199
- New rules and framework support are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md).
258
+ New rules and framework support are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md). Security reports: [SECURITY.md](SECURITY.md).
200
259
 
201
260
  ## License
202
261
 
203
- MIT
262
+ [MIT](LICENSE)
package/dist/model.js CHANGED
@@ -69,8 +69,6 @@ function forwardTarget(fn) {
69
69
  return callee;
70
70
  }
71
71
  function isData(st) {
72
- if (!ts.isVariableStatement(st))
73
- return false;
74
72
  const plain = (init) => {
75
73
  while (init && (ts.isAsExpression(init) || ts.isSatisfiesExpression(init) || ts.isParenthesizedExpression(init)))
76
74
  init = init.expression;
@@ -82,15 +80,18 @@ function isData(st) {
82
80
  return true;
83
81
  if (!ts.isObjectLiteralExpression(init) && !ts.isArrayLiteralExpression(init))
84
82
  return false;
85
- let code = false;
83
+ let code = 0;
86
84
  each(init, (node) => {
87
- if (ts.isFunctionLike(node) || ts.isClassExpression(node))
88
- code = true;
89
- return !code;
85
+ if (!ts.isFunctionLike(node) && !ts.isClassExpression(node))
86
+ return true;
87
+ code += node.end - node.pos;
88
+ return false;
90
89
  });
91
- return !code;
90
+ return code * 5 < init.end - init.pos;
92
91
  };
93
- return st.declarationList.declarations.every((d) => plain(d.initializer));
92
+ if (ts.isExportAssignment(st))
93
+ return plain(st.expression);
94
+ return ts.isVariableStatement(st) && st.declarationList.declarations.every((d) => plain(d.initializer));
94
95
  }
95
96
  function each(root, fn) {
96
97
  const stack = [root];
@@ -108,7 +109,6 @@ function each(root, fn) {
108
109
  }
109
110
  const MUTATORS = new Set(['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin', 'set', 'add', 'delete', 'clear']);
110
111
  const COLLECTIONS = new Set(['Array', 'Map', 'Set', 'WeakMap', 'WeakSet']);
111
- const HANDLER_SLOT = /^on[A-Z_a-z]/;
112
112
  function insideFunction(node) {
113
113
  for (let p = node.parent; p; p = p.parent)
114
114
  if (ts.isFunctionLike(p))
@@ -141,7 +141,7 @@ function isMutation(name, checker) {
141
141
  return false;
142
142
  const whole = unwrapped(access);
143
143
  if (assigned(whole))
144
- return !(HANDLER_SLOT.test(name.text) && checker.getNonNullableType(checker.getTypeAtLocation(access)).getCallSignatures().length > 0);
144
+ return checker.getNonNullableType(checker.getTypeAtLocation(access)).getCallSignatures().length === 0;
145
145
  const outer = whole.parent;
146
146
  if (ts.isElementAccessExpression(outer) && outer.expression === whole)
147
147
  return assigned(unwrapped(outer));
@@ -213,11 +213,13 @@ function typeOnlyImport(node) {
213
213
  const named = clause.namedBindings;
214
214
  return !!named && ts.isNamedImports(named) && named.elements.length > 0 && named.elements.every((e) => e.isTypeOnly);
215
215
  }
216
+ const GENERATED_HEADER = /@generated|do not edit|auto-?generated/i;
217
+ const EVENT_ATTR = /^on[A-Z]/;
218
+ const generated = (sf) => (ts.getLeadingCommentRanges(sf.text, ts.getShebang(sf.text)?.length ?? 0) ?? []).some((c) => c.pos < 500 && GENERATED_HEADER.test(sf.text.slice(c.pos, c.end)));
216
219
  export function collect(model, program, accept) {
217
220
  const checker = program.getTypeChecker();
218
- const scanner = ts.createScanner(ts.ScriptTarget.Latest, true);
219
221
  const rel = (file) => path.relative(model.root, realName(file)).split(path.sep).join('/');
220
- const sources = program.getSourceFiles().filter((sf) => accept(sf.fileName));
222
+ const sources = program.getSourceFiles().filter((sf) => accept(sf.fileName) && !generated(sf));
221
223
  const inScope = new Set(sources.map((sf) => sf.fileName));
222
224
  for (const sf of sources)
223
225
  model.files.add(rel(sf.fileName));
@@ -280,16 +282,25 @@ export function collect(model, program, accept) {
280
282
  }
281
283
  }
282
284
  const lineAt = (pos) => sf.getLineAndCharacterOfPosition(pos).line;
285
+ const starts = sf.getLineStarts();
286
+ const blank = (line) => sf.text.slice(starts[line], starts[line + 1] ?? sf.text.length).trim() === '';
283
287
  const coded = new Set();
284
- for (const st of sf.statements) {
285
- if (isData(st))
286
- continue;
287
- const from = st.getStart(sf);
288
- scanner.setText(sf.text, from, st.end - from);
289
- while (scanner.scan() !== ts.SyntaxKind.EndOfFileToken)
290
- for (let line = lineAt(scanner.getTokenStart()), last = lineAt(scanner.getTokenEnd()); line <= last; line++)
291
- coded.add(line);
292
- }
288
+ const mark = (root) => each(root, (node) => {
289
+ const from = node.getStart(sf);
290
+ if (from >= node.end)
291
+ return;
292
+ const first = lineAt(from);
293
+ const last = lineAt(node.end - 1);
294
+ coded.add(first);
295
+ coded.add(last);
296
+ if (last - first > 1 && (ts.isJsxText(node) || ts.isTemplateLiteralToken(node) || ts.isStringLiteralLike(node)))
297
+ for (let line = first + 1; line < last; line++)
298
+ if (!blank(line))
299
+ coded.add(line);
300
+ });
301
+ for (const st of sf.statements)
302
+ if (!isData(st))
303
+ mark(st);
293
304
  model.lines.set(file, coded.size);
294
305
  const diForwardRef = sf.statements.some((st) => ts.isImportDeclaration(st) && ts.isStringLiteral(st.moduleSpecifier) && DI_PACKAGES.has(st.moduleSpecifier.text) && /\bforwardRef\b/.test(st.importClause?.getText() ?? ''));
295
306
  const componentKeyOf = (tag) => {
@@ -333,7 +344,7 @@ export function collect(model, program, accept) {
333
344
  const holder = value.parent;
334
345
  if (ts.isJsxExpression(holder) && ts.isJsxAttribute(holder.parent) && ts.isIdentifier(holder.parent.name)) {
335
346
  const child = componentKeyOf(holder.parent.parent.parent.tagName);
336
- if (child) {
347
+ if (child && !(holder.parent.name.text !== prop && EVENT_ATTR.test(holder.parent.name.text))) {
337
348
  use.passes.push({ child, attr: holder.parent.name.text, line: lineOf(value) });
338
349
  return;
339
350
  }
package/dist/projects.js CHANGED
@@ -3,6 +3,9 @@ import path from 'node:path';
3
3
  import ts from 'typescript';
4
4
  import { isSfc, isVirtual, realName, scriptOf } from "./sfc.js";
5
5
  const SKIP_DIRS = new Set(['node_modules', 'dist', 'build', '.git', '.next', '.nuxt', '.output', '.svelte-kit', '.astro', 'coverage', 'out', '.turbo', 'vendor']);
6
+ const NOT_PRODUCT = new Set(['generated', '__generated__', 'vendored', 'third_party', 'third-party', '.agents', '.claude', '.cursor', '.codex']);
7
+ const BESIDE_PRODUCT = new Set(['examples', 'example', 'benchmarks', 'benchmark']);
8
+ const CODE_ROOT = new Set(['src', 'app', 'pages', 'routes', 'lib']);
6
9
  const TEST_FILE = /(\.|\/)(spec|test|e2e|stories|bench|vitest|cy|test-d|spec-d)\.[cm]?[jt]sx?$|\/(__tests__|__mocks__|test|tests|testing|fixtures|e2e)\//;
7
10
  export function findTsconfigs(root) {
8
11
  const found = [];
@@ -125,6 +128,9 @@ export function isSource(file, root, ignore) {
125
128
  return false;
126
129
  if (/\.[cm]?jsx?$/.test(rel) && rel.split('/').slice(0, -1).some((part) => SKIP_DIRS.has(part)))
127
130
  return false;
131
+ const parts = rel.split('/').slice(0, -1);
132
+ if (parts.some((part, i) => NOT_PRODUCT.has(part) || (BESIDE_PRODUCT.has(part) && !parts.slice(0, i).some((above) => CODE_ROOT.has(above)))))
133
+ return false;
128
134
  return !ignore.some((re) => re.test(rel));
129
135
  }
130
136
  export function globToRegExp(glob) {
@@ -80,7 +80,7 @@ function forwardRefs(model) {
80
80
  out.push({
81
81
  rule: 'forward-ref',
82
82
  key,
83
- title: `\`${ref.owner}\` reaches \`${ref.target}\` through forwardRef: the two depend on each other`,
83
+ title: `\`${ref.owner}\` reaches \`${ref.target}\` through forwardRef: a dependency cycle is silenced, not removed`,
84
84
  at: `${ref.file}:${ref.line}`,
85
85
  notes: [],
86
86
  body: [`${ref.owner} ◀━━▶ ${ref.target}`],
package/dist/score.js CHANGED
@@ -18,9 +18,27 @@ const GRADES = [
18
18
  ['D', 48, 'orange'],
19
19
  ['F', Infinity, 'red'],
20
20
  ];
21
+ const classOf = (side) => side.slice(side.indexOf('#') + 1);
22
+ function hubs(pairs) {
23
+ let left = pairs;
24
+ let count = 0;
25
+ while (left.length) {
26
+ const degree = new Map();
27
+ for (const pair of left)
28
+ for (const side of pair)
29
+ degree.set(side, (degree.get(side) ?? 0) + 1);
30
+ const [hub] = [...degree].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0];
31
+ left = left.filter((pair) => !pair.includes(hub));
32
+ count++;
33
+ }
34
+ return count;
35
+ }
21
36
  export function score(findings, files) {
22
- const counted = new Map(findings.map((f) => [f.rule === 'field-leak' ? `${f.rule} ${f.key.slice(0, f.key.lastIndexOf('.'))}` : `${f.rule} ${f.key}`, f.rule]));
23
- const weight = [...counted.values()].reduce((sum, rule) => sum + (WEIGHTS[rule] ?? 1), 0);
37
+ const owner = (f) => f.key.slice(0, f.key.lastIndexOf('.'));
38
+ const forwarded = new Set(findings.filter((f) => f.rule === 'forward-ref').map((f) => f.key.replace('->', ' ')));
39
+ const tangled = findings.filter((f) => f.rule === 'tangle').map((f) => f.key.split(' ~ ')).filter(([a, b]) => !b || (!forwarded.has(`${a} ${classOf(b)}`) && !forwarded.has(`${b} ${classOf(a)}`)));
40
+ const counted = new Map(findings.filter((f) => f.rule !== 'tangle').map((f) => [f.rule === 'field-leak' || f.rule === 'prop-drilling' ? `${f.rule} ${owner(f)}` : `${f.rule} ${f.key}`, f.rule]));
41
+ const weight = [...counted.values()].reduce((sum, rule) => sum + (WEIGHTS[rule] ?? 1), 0) + hubs(tangled) * WEIGHTS.tangle;
24
42
  const knots = Math.round((weight / (files + PRIOR_FILES)) * 10000) / 10;
25
43
  const grade = GRADES.find(([, limit]) => knots <= limit)[0];
26
44
  return { grade, knots, findings: findings.length, files };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "unknot",
3
- "version": "0.1.0",
4
- "description": "Architecture guard for TypeScript codebases written with AI agents: finds the knots (import cycles, tangled classes, leaked state, pass-through code, prop drilling) and makes the agent untie them.",
3
+ "version": "0.1.1",
4
+ "description": "Architecture linter for TypeScript and JavaScript code written by AI agents: finds the knots (import cycles, tangled classes, leaked state, pass-through code, prop drilling) and makes the agent untie them.",
5
5
  "keywords": [
6
6
  "lint",
7
7
  "architecture",