loadwise 0.6.0 → 0.6.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/PERFORMANCE.md +31 -6
- package/README.md +116 -475
- package/package.json +18 -3
- package/plugin/.claude-plugin/plugin.json +1 -1
package/PERFORMANCE.md
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
1
|
# Checker performance
|
|
2
2
|
|
|
3
|
-
These measurements use the actual CLI on Windows x64
|
|
3
|
+
These measurements use the actual CLI on Windows x64. Each section records the Loadwise version it measured and the Node version where known. Older sections were not re-run for later releases. Use the commands below to measure on your own code and hardware.
|
|
4
|
+
|
|
5
|
+
## Version 0.6.0
|
|
6
|
+
|
|
7
|
+
Re-measured locally on Windows x64 with Node 26.13.1 and TypeScript 6.0.3, with `LOADWISE_AGENT=0`. The OS file cache was warm and other work was running on the machine, so treat small differences as noise.
|
|
8
|
+
|
|
9
|
+
| Benchmark | Runs | Median result |
|
|
10
|
+
| --------------------------------------------------- | ---------------------------- | ----------------------------------------------------------------------------------- |
|
|
11
|
+
| `bench:scan`, 52 modules, 48 findings | 9 fresh programs, 2 warmups | Program creation 127.8 ms, rule analysis 261.4 ms, total 376.0 ms |
|
|
12
|
+
| `bench:scan -- --large`, 3,200 files, `--engine js` | 3 fresh processes per config | `tsconfig.json` 3.96 s, 300 MiB peak RSS; eight referenced projects 5.72 s, 277 MiB |
|
|
13
|
+
| `bench:scan -- --large --native`, 3,200 files | 3 fresh processes per config | `tsconfig.json` 2.34 s, 233 MiB peak RSS; eight referenced projects 2.56 s, 242 MiB |
|
|
14
|
+
| `bench:traces`, 24,000 spans, 480 findings | 12 rounds, 3 warmups | Scan 24.5 ms, JSON parse and scan 73.0 ms |
|
|
15
|
+
| `bench:traces -- --cache-lookups`, 720 findings | 12 rounds, 3 warmups | Scan 15.9 ms, JSON parse and scan 41.8 ms |
|
|
16
|
+
| `bench:patterns` | 12 pairs, 3 warmups | See below |
|
|
17
|
+
| `bench:security`, 12,000 same-name call sites | 7 samples, 2 warmups | Index and first lookup 5.73 ms, other lookups 0.02 ms |
|
|
18
|
+
|
|
19
|
+
Every large-fixture batch checked the 72 exact expected findings across all 3,200 files. The trace runs checked complete result equality each round. The pattern benchmark compared results by hash each pair. The native engine was 1.7 times faster on the single project and 2.2 times faster on the eight referenced projects. On this machine the default `auto` engine picks the native one, so these rows force each engine. The trace and pattern benchmarks no longer compare against a saved earlier implementation, so there is no before and after column for them.
|
|
20
|
+
|
|
21
|
+
| Pattern | Slower form | Faster form |
|
|
22
|
+
| ---------------------------------------------- | ------------------------: | ----------------------: |
|
|
23
|
+
| 300 customers and orders, per-customer queries | 2.343 ms (301 statements) | 0.768 ms (2 statements) |
|
|
24
|
+
| First matching order | 0.970 ms | 0.005 ms |
|
|
25
|
+
| 12,000 membership lookups in 8,000 IDs | 69.460 ms | 0.747 ms |
|
|
26
|
+
| Collect 4,000 transformed IDs | 20.147 ms | 0.019 ms |
|
|
27
|
+
|
|
28
|
+
Not re-measured for 0.6.0: the VS Code, NestJS and TypeORM checkouts, the live PostgreSQL, MongoDB and Redis checks, the Python OpenTelemetry integration, the watch-mode timings and the ORM integration. They need external checkouts, services or tooling that this run did not have. The sections below still describe the versions they name.
|
|
4
29
|
|
|
5
30
|
## Version 0.3.0
|
|
6
31
|
|
|
@@ -41,7 +66,7 @@ All **14** original NestJS membership sites were reviewed against the linked ups
|
|
|
41
66
|
|
|
42
67
|
The original native scan on VS Code used 97,564 requests across the JS/Go boundary. Checking async context before resolving symbols and batching up to 256 candidate identifiers reduced requests to 10,958 in an instrumented build with the ORM rules, before adding the Promise and sorting rules. In a separate six-process interleaved comparison on the same 22 original rules, the baseline median was 24.68 s and the optimized median was 9.92 s. All six JSON outputs matched. That series ran under concurrent local workload. Absolute results vary with system load and project shape. The native compiler still materializes the syntax trees in JS.
|
|
43
68
|
|
|
44
|
-
|
|
69
|
+
As of 0.2.0, the optional real-types integration checked TypeORM 0.3.28, Sequelize 6.37.7, Sequelize 7.0.0-alpha.47, Mongoose 8.19.1, Knex 3.1.0 and Kysely 0.28.8. The current pins are in `test/performance/integration/orms/package.json` and were not re-measured. Both compiler engines reported all 19 seeded findings at the same locations and left the control lines quiet. Separate fixtures used a generated Prisma 7.10.1 client, Drizzle 0.45.4 across PostgreSQL, MySQL and SQLite declarations, and `@types/pg` 8.23.1. A small SQLite check also ran an actual scoped Drizzle query against two tenants. These targeted checks measure behavior on known examples. They do not estimate precision for arbitrary applications.
|
|
45
70
|
|
|
46
71
|
The row-scope fixtures use different fields and authorization helpers in the same project, including `Invoice.organizationId` and `Workspace.workspace_id`. They cover incorrect field names, wrong helper provenance, and a run with row-scope checking disabled. In the SQLite test, Drizzle generated SQL for the physical column `org_id` while the checker recognized the public property `organizationId`.
|
|
47
72
|
|
|
@@ -80,7 +105,7 @@ In the final 22-rule watch test, six alternating edits added and cleared a findi
|
|
|
80
105
|
|
|
81
106
|
The polyglot source checker separately scanned 756 real Python 3.12 standard-library files (production modules, tests excluded). It returned zero findings on four runs. With parsing-error validation enabled, its first check took 386 ms and three further runs had a 383 ms median including native process startup.
|
|
82
107
|
|
|
83
|
-
## Trace exports
|
|
108
|
+
## Trace exports (0.2.1 and earlier)
|
|
84
109
|
|
|
85
110
|
The trace benchmark used 24,000 spans (11.1 MiB of JSON), including 4,800 eligible DB spans and 480 expected groups. It checked the complete output on every run. The optimized reader indexes attributes in one pass and reuses bounded operation-signature fingerprints.
|
|
86
111
|
|
|
@@ -91,7 +116,7 @@ The trace benchmark used 24,000 spans (11.1 MiB of JSON), including 4,800 eligib
|
|
|
91
116
|
|
|
92
117
|
These are local medians from an interleaved run against the saved pre-optimization implementation. The trace numbers exclude process startup and disk I/O. Run `npm run bench:traces` to reproduce the workload, or add `-- --cache-lookups` for the 720-finding fixture with identical key reads.
|
|
93
118
|
|
|
94
|
-
## Application behavior
|
|
119
|
+
## Application behavior (0.2.1 and earlier, SQLite part re-run in 0.6.0 above)
|
|
95
120
|
|
|
96
121
|
The application-pattern benchmark uses Node's in-memory SQLite, prepared statements and an index. Fetching one page of 300 customers and their orders took 301 statements with per-customer lookups and two with batching. Both variants returned equal, ordered results including customers with zero orders. The collection comparisons include the cost of building the lookup Set.
|
|
97
122
|
|
|
@@ -99,7 +124,7 @@ A separate integration check used Python 3.12, the OpenTelemetry SDK and its sql
|
|
|
99
124
|
|
|
100
125
|
Run `npm run bench:patterns` to compare application code. Its output measures the example workload. It makes no prediction about network round-trips, production caches or real database latency.
|
|
101
126
|
|
|
102
|
-
## Live database checks
|
|
127
|
+
## Live database checks (0.2.1 and earlier)
|
|
103
128
|
|
|
104
129
|
| Engine | Measured outcome on isolated test data |
|
|
105
130
|
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
@@ -107,4 +132,4 @@ Run `npm run bench:patterns` to compare application code. Its output measures th
|
|
|
107
132
|
| MongoDB 8.2.3 | A collection scan examined 20,000 documents for one match. Indexing reduced that to one. Deep skip walked 15,010 index entries even though top-level documents examined was only ten. The keyset query returned the same documents and passed. A separate sort spilled 79 times and was detected. |
|
|
108
133
|
| Redis 7.2.16 | Python instrumentation captured a real `KEYS` operation. Incremental `SCAN` returned the same fixture key and passed. Eight default-redacted GETs produced a batching finding. Eight reads of a visible synthetic key produced a request-local reuse finding. One GET reused eight times returned the same values and passed. |
|
|
109
134
|
|
|
110
|
-
SQL Server, MySQL, MariaDB, DynamoDB, Cassandra and additional language/driver combinations are covered by contract fixtures
|
|
135
|
+
SQL Server, MySQL, MariaDB, DynamoDB, Cassandra and additional language/driver combinations are covered by contract fixtures only. The live database checks above establish a different level of evidence.
|
package/README.md
CHANGED
|
@@ -2,15 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/loadwise) [](https://github.com/IbrahimHafez1/loadwise/actions/workflows/check.yml) [](https://scorecard.dev/viewer/?uri=github.com/IbrahimHafez1/loadwise) [](LICENSE)
|
|
4
4
|
|
|
5
|
-
Loadwise checks a
|
|
5
|
+
Loadwise checks a TypeScript or JavaScript project before it ships. Its deepest coverage is backend and database code, and it also checks React, Next.js, Vue and Angular frontends. One CLI runs five checkers:
|
|
6
6
|
|
|
7
|
-
- **Performance** (`loadwise perf`): repeated database work, ORM and query integrity, blocking calls, collection complexity, schema-aware indexes, OpenTelemetry traces, executed query plans and an optional read-only database inspection.
|
|
8
|
-
- **Reliability** (`loadwise rel`): unhandled rejections and swallowed errors, races and transaction-client escapes, missing timeouts and idempotency keys, migration safety and breaking API changes.
|
|
7
|
+
- **Performance** (`loadwise perf`): repeated database work, ORM and query integrity, blocking calls, collection complexity, React, Vue and Angular rendering and cleanup work, schema-aware indexes, OpenTelemetry traces, executed query plans and an optional read-only database inspection.
|
|
8
|
+
- **Reliability** (`loadwise rel`): unhandled rejections and swallowed errors, races and transaction-client escapes, missing timeouts and idempotency keys, React effect and state bugs, migration safety and breaking API changes.
|
|
9
9
|
- **Maintainability** (`loadwise maint`): deep nesting, branch complexity, duplicate implementations, dependency cycles and the folder, placement and data-access rules a team declares.
|
|
10
|
-
- **Security** (`loadwise sec`): request data reaching sensitive operations, authentication and cryptography, exposed credentials, Docker and Compose configuration, declared row scopes, and optionally dependency advisories.
|
|
10
|
+
- **Security** (`loadwise sec`): request data reaching sensitive operations, authentication and cryptography, exposed credentials including secrets bundled into client code, unsafe HTML in JSX, Vue and Angular, `javascript:` URLs in JSX, Docker and Compose configuration, declared row scopes, and optionally dependency advisories.
|
|
11
11
|
- **Accessibility** (`loadwise a11y`): images without alt text, unlabelled form controls, click handlers on non-interactive elements, invalid ARIA and missing page language in JSX, HTML, Vue, Svelte and Angular templates. Skipped on projects without frontend sources.
|
|
12
12
|
|
|
13
|
-
Each finding has a stable `#id` for review. Where a checker can generate an edit, it shows the diff and any assumptions to verify. Supported source rules accept a `loadwise-reviewed` comment with a reason for intentional code.
|
|
13
|
+
Each finding has a stable `#id` for review. Where a checker can generate an edit, it shows the diff and any assumptions to verify. Supported source rules accept a `loadwise-reviewed` comment with a reason for intentional code. Every rule has its own page under [docs/rules](docs/rules/), linked from the rule tables below.
|
|
14
14
|
|
|
15
15
|
> **Pre-1.0.** Loadwise is under active development. Until 1.0, rule ids, CLI flags, the JSON report and the config schema can change in a minor release. Every such change is listed in the [changelog](CHANGELOG.md), and a moved or renamed rule keeps accepting its old id where possible. False-positive reports are the most useful feedback: [open one](https://github.com/IbrahimHafez1/loadwise/issues/new?template=false-positive.yml).
|
|
16
16
|
|
|
@@ -26,7 +26,7 @@ npm install --save-dev loadwise
|
|
|
26
26
|
npx loadwise --version
|
|
27
27
|
```
|
|
28
28
|
|
|
29
|
-
By default `loadwise check`
|
|
29
|
+
By default `loadwise check` runs all five checkers; see the [corpus rule scorecard](bench/corpus/scorecard.md) for measured precision and recall across real-world open-source backends.
|
|
30
30
|
|
|
31
31
|
**Autofix example:** `npx loadwise fix --yes` rewrites eligible issues in place and verifies TypeScript projects with a post-edit typecheck:
|
|
32
32
|
|
|
@@ -42,7 +42,7 @@ By default `loadwise check` reports actionable findings across Performance, Reli
|
|
|
42
42
|
|
|
43
43
|
### Try a finding and a fix
|
|
44
44
|
|
|
45
|
-
From
|
|
45
|
+
From a project where you ran `npm install --save-dev loadwise`, copy the bundled example to a disposable file and scan it. The copy command refuses to overwrite an existing file.
|
|
46
46
|
|
|
47
47
|
```sh
|
|
48
48
|
node -e "require('node:fs').copyFileSync('node_modules/loadwise/examples/slow.ts', 'loadwise-demo.ts', require('node:fs').constants.COPYFILE_EXCL)"
|
|
@@ -75,48 +75,45 @@ The second scan should report two findings. Remove the disposable copy when fini
|
|
|
75
75
|
| `loadwise fix --yes` | Scans the current project once and applies eligible edits across the configured checkers. |
|
|
76
76
|
| `loadwise agent init [--mode ask\|auto] [--hook [block\|warn\|off]]` | Writes project instructions for coding agents. Use `--hook` to configure a pre-commit hook. |
|
|
77
77
|
|
|
78
|
-
`
|
|
79
|
-
|
|
80
|
-
Choose the checkers by name, separated by spaces. With no names, Loadwise uses the project's configured checkers.
|
|
81
|
-
|
|
82
|
-
```bash
|
|
83
|
-
npx loadwise fix --all # all generated edits, including review suggestions
|
|
84
|
-
npx loadwise fix --all performance # performance only
|
|
85
|
-
npx loadwise fix --all performance security # performance and security
|
|
86
|
-
npx loadwise fix --all reliability # reliability only
|
|
87
|
-
npx loadwise fix --all accessibility # accessibility only
|
|
88
|
-
npx loadwise fix --yes maintainability # automatic maintainability edits only
|
|
89
|
-
```
|
|
78
|
+
`check` accepts these flags and passes them to every selected checker:
|
|
90
79
|
|
|
91
|
-
|
|
80
|
+
- `--json` prints one object with a key per selected checker, `{ "performance": report, "reliability": report, "maintainability": report, "security": report, "accessibility": report }`. A checker that was skipped or could not run has `null`.
|
|
81
|
+
- `--format text|json|sarif|github` picks the output; `--json` is `--format json`. `sarif` prints SARIF 2.1.0 with one run per checker for GitHub code scanning, and `github` prints `::warning`/`::error`/`::notice` workflow annotations. The checker commands accept it too. Exit codes do not depend on the format.
|
|
82
|
+
- `--include-contextual` also shows lower-priority findings (one-off blocking calls in CLI startup, test and seed sources and similar), each with its reason. JSON counts the hidden ones in `contextualFindingCount`; in the expanded view they appear in `findings` with a `contextualReason`.
|
|
83
|
+
- `--staged` or `--changed-since <git-ref>` reports only findings on changed lines (see [Changed lines](#changed-lines)).
|
|
84
|
+
- `--fail-on contract|all` sets the exit threshold. By default, performance, reliability, security and accessibility fail on displayed findings, and a full maintainability scan fails on contract violations. Changed-line maintainability scans fail on any displayed finding. Configured rule levels can change these defaults.
|
|
85
|
+
- `--min-impact <low|medium|high|critical>` reports only findings at that level or above (see [Impact levels](#impact-levels)).
|
|
86
|
+
- `--config <file>`, `--ignore <rule-id>` and `--workspace <name|path>` are described under [Configuration](#configuration); `--online` adds the [dependency checks](#dependency-checks).
|
|
87
|
+
- `--write-baseline [file]` records the current findings and `--baseline [file]` reports only findings not recorded. The default file is `loadwise-baseline.json` in the checked directory, with one section per checker; the checker commands take the same flags and read or write only their own section. Entries match on rule, file and flagged code (the finding id), never the line number, with a count per entry so N recorded copies allow N findings. Text output ends with `N baseline findings hidden.` and `--json` adds `baselineHidden`. A full comparison reports unmatched entries in `baselineStale`; a partial one, such as a changed-line or single-file scan, reports `null`. Refresh the baseline using its original scope and settings. Not combinable with `--fix`, and `--write-baseline` not with `--staged` or `--changed-since`. `loadwise rel migrations` keeps its own baseline.
|
|
92
88
|
|
|
93
|
-
|
|
89
|
+
**Exit codes:** **0** passed, **1** a checker met its exit threshold, **2** invalid input or configuration in any checker, a checker that produced no result, or a scan that skipped a file. A JavaScript or TypeScript file that does not parse, or whose analysis fails, is skipped while every other file is still reported; it is named on stderr and in a `skippedFiles` array of `{ file, reason }` in `--json` output (also with `--fix` and `--write-baseline`). `check` keeps that checker's findings, marks its SARIF run as not successful and emits a GitHub warning for each skipped file. A file that exists but cannot be read (the schema snapshot, `package.json`, a review directive) prints a note on stderr; an absent file stays silent.
|
|
94
90
|
|
|
95
|
-
|
|
91
|
+
**Projects and workspaces.** The source checkers use the directory's `tsconfig.json` or `jsconfig.json`. Without one, `check` looks for workspace packages (`package.json` `workspaces`, `pnpm-workspace.yaml` or `lerna.json`) and checks each one's config in one report, grouped per package. A package with a `package.json` and no config has its JavaScript and TypeScript sources inferred from the project inventory and checked with ES2022 and NodeNext defaults; a package whose TypeScript sits under a sub-folder's own `tsconfig.json` still needs a config at its root. When performance and reliability are selected together, they share a type-check unless a baseline is being written. Source scans are read-only; when fixes are available, text reports include a `Fix all:` command such as `npx loadwise perf -p tsconfig.json --fix --only <ids>`.
|
|
96
92
|
|
|
97
|
-
|
|
93
|
+
**Cache.** `loadwise check` reuses the previous result for an unchanged Git project from the `loadwise` folder of the OS cache directory. Any edit to a tracked or untracked (not ignored) file, a package install that rewrites `node_modules`, a different flag or a new Loadwise version runs a fresh scan; `LOADWISE_NO_CACHE=1` always scans afresh. Fixes, `--staged`, `--changed-since`, `--online` and `--write-baseline` runs are never cached.
|
|
98
94
|
|
|
99
|
-
|
|
95
|
+
**Memory.** On large projects the checkers run with a larger Node memory limit, 60% of the machine's memory, at least 4096 MB and at most 16384 MB (never below Node's own default). A `--max-old-space-size` you set in `NODE_OPTIONS` is never overridden. Direct `loadwise perf`, `loadwise sec` and `loadwise maint` runs re-launch once to apply the limit. If a checker still runs out of memory, `check` names it and the limit it had, tells you to raise it with `NODE_OPTIONS=--max-old-space-size=<megabytes>`, and exits 2. The native engine (`--engine native`) uses much less memory on most projects.
|
|
100
96
|
|
|
101
|
-
|
|
97
|
+
### Fixes
|
|
102
98
|
|
|
103
99
|
```bash
|
|
104
|
-
npx loadwise fix --
|
|
100
|
+
npx loadwise fix --yes # automatic edits for the configured checkers
|
|
101
|
+
npx loadwise fix --all # all generated edits, including review suggestions
|
|
102
|
+
npx loadwise fix --all performance security # only the named checkers
|
|
103
|
+
npx loadwise fix --yes maintainability --dry-run # preview unified diffs without writing
|
|
105
104
|
```
|
|
106
105
|
|
|
107
|
-
|
|
106
|
+
Checker names (`performance`, `reliability`, `maintainability`, `security`, `accessibility`) are separated by spaces; with none, Loadwise uses the project's configured checkers. `fix` lists manual changes and findings that need individual review by location and ID; a fix that touches lines reserved for review also needs individual review. Loadwise checks the remaining edits together before writing, and performance and security share a type-check when both are selected. It exits 2 if a selected checker fails or is skipped, source lines have changed, or automatic fixes conflict, and 0 on success even when manual findings remain. Manual findings have no generated edit; with `--all`, inspect the diff and run your tests, especially for schema changes and edits that alter behavior. `--json` with `--yes` or `--all` records the applied hunks and outstanding findings.
|
|
108
107
|
|
|
109
|
-
|
|
108
|
+
Each applied fix in a JavaScript or TypeScript file gets a `// Loadwise <rule-id>: <why>` comment above the fixed statement, and the changed lines are formatted with the project's own Prettier, honouring its config and `.prettierignore`; the rest of the file stays byte-identical. Without Prettier the edits are written as generated, with a note. `--no-comments` and `--no-format` turn these off, also on the per-checker `--fix`. `fix` also takes repeatable `--rule <rule-id>` filtering and `--no-verify-types` (skip the post-edit TypeScript check).
|
|
110
109
|
|
|
111
|
-
|
|
112
|
-
npx loadwise fix --all maintainability --recipe ./loadwise-fixes.cjs
|
|
113
|
-
```
|
|
110
|
+
Some transformations always need individual review: making a locally used constant private can affect consumers outside the scan; sharing a private helper between sibling TypeScript modules changes the files included in the build; narrowing a whole-table Drizzle update to rows with differing values can affect locking, triggers and affected-row counts; an upload size limit (the 10 MiB example can reject valid uploads, so check existing gateway or Multer limits); and the Mongoose `.lean()` rewrite, because a lean result skips schema defaults, getters and virtuals. For private TypeScript applications that control their consumers, `npx loadwise fix --all --recipe verified-private-types` also makes locally used type declarations private, after checking the edits with the bundled TypeScript compiler; omit it when other repositories import your types.
|
|
114
111
|
|
|
115
|
-
|
|
112
|
+
A local CommonJS recipe encodes your own policy for a manual finding, run alongside the built-in fixes with `npx loadwise fix --all reliability --recipe ./loadwise-fixes.cjs`:
|
|
116
113
|
|
|
117
114
|
```js
|
|
118
115
|
module.exports = {
|
|
119
|
-
'
|
|
116
|
+
'rel/swallowed-error'({ finding, source }) {
|
|
120
117
|
if (finding.file !== 'scripts/refresh-cache.ts') return null;
|
|
121
118
|
const before = source.split(/\r?\n/)[finding.line - 1];
|
|
122
119
|
if (before?.trim() !== '} catch {}') return null;
|
|
@@ -129,26 +126,30 @@ module.exports = {
|
|
|
129
126
|
};
|
|
130
127
|
```
|
|
131
128
|
|
|
132
|
-
Keys
|
|
129
|
+
Keys are `perf`, `rel`, `maint`, `sec` or `a11y` followed by `/` and the rule ID. A handler receives the finding and the source file text and returns exact, whole-line replacements in that file, or `null` to leave the site manual. Recipes run only where there is no built-in fix, and their edits are validated together before writing. Recipe files execute as local JavaScript, so run only recipes you trust and keep handlers free of side effects.
|
|
133
130
|
|
|
134
|
-
|
|
131
|
+
### Per-checker fixes and dismissals
|
|
135
132
|
|
|
136
|
-
|
|
133
|
+
The source-check commands (`perf`, `rel`, `maint`, `sec` and `a11y` on a project or files, not subcommands such as `perf traces`, `rel migrations` or `sec deps`) take `--fix` (asks **y**es, **n**o, **a**ll remaining or **q**uit for each fix; needs a terminal), `--fix --yes` (applies eligible fixes without asking) and `--fix --only <id>[,<id>...]` (applies exactly those fixes, no prompt or terminal needed). With `--json`, `--only` prints `{ applied, alreadyApplied, failed }`: an id whose change an earlier id already made, such as a shared `Set`, is in `alreadyApplied`; an unknown id, a finding without a fix or a stale fix is in `failed` and the exit code is 2. `--fix` cannot be combined with `--watch` or `--graph`, or with `--json` except with `--only`, and `--yes` is valid only with `--fix`. A fix applies only where the original lines still exist and never overwrites an existing file. With `--json`, a fix is `fix = { changes: [{ file, line, before, after, create? }], note? }`, where `create` holds a whole new file such as a migration; findings also carry `fixable`. The id hashes the rule, the file and the flagged line's text, so it survives edits above the finding.
|
|
137
134
|
|
|
138
|
-
-
|
|
139
|
-
- `--format text|json|sarif|github` picks the output; `--json` is `--format json`. `sarif` prints SARIF 2.1.0 with one run per checker for GitHub code scanning, and `github` prints `::warning`/`::error`/`::notice` workflow annotations. `loadwise perf`, `loadwise rel`, `loadwise maint`, `loadwise sec` and `loadwise a11y` accept it too. Exit codes do not depend on the format.
|
|
140
|
-
- `--include-contextual` also shows lower-priority findings, each with its reason.
|
|
141
|
-
- `--staged` or `--changed-since <git-ref>` reports only findings on changed lines.
|
|
142
|
-
- `--fail-on contract|all` sets the exit threshold. By default, performance, reliability, security and accessibility fail on displayed findings, and a full maintainability scan fails on contract violations. Changed-line maintainability scans fail on any displayed finding. Configured rule levels can change these defaults.
|
|
143
|
-
- `--write-baseline [file]` records the current findings and `--baseline [file]` reports only findings not recorded. The default file is `loadwise-baseline.json` in the checked directory, with one section per checker; `loadwise perf`, `loadwise rel`, `loadwise maint`, `loadwise sec` and `loadwise a11y` take the same flags and read or write only their own section. Entries match on rule, file and flagged code (the finding id), never the line number, with a count per entry so N recorded copies allow N findings. Text output ends with `N baseline findings hidden.` and `--json` adds `baselineHidden`. A full comparison reports the number of unmatched entries in `baselineStale`. A partial comparison, such as a changed-line or single-file scan, reports `null` because unscanned findings may still exist. Refresh the baseline using its original scope and settings. Not combinable with `--fix`, and `--write-baseline` not with `--staged` or `--changed-since`. `loadwise rel migrations` keeps its own per-file baseline.
|
|
135
|
+
To keep an intentional site, put a comment on its own line immediately before the diagnostic line (line 1 for a whole-file finding such as `large-module`), naming one exact rule and a reason. The finding becomes contextual and stays visible with `--include-contextual`. Declared contracts (CI contract rules, `file-placement`, `folder-boundary`, `data-access-boundary`, `query-mutates-state`, configured row scopes) and Prisma transaction-client escapes and read-modify-write findings cannot be lowered this way.
|
|
144
136
|
|
|
145
|
-
|
|
137
|
+
```ts
|
|
138
|
+
// loadwise-reviewed pg-query-in-loop -- Each iteration measures a separate query-plan sample.
|
|
139
|
+
await client.query(statement);
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
### Changed lines
|
|
146
143
|
|
|
147
|
-
|
|
144
|
+
```sh
|
|
145
|
+
npx loadwise perf --staged # lines added or modified in the git index
|
|
146
|
+
npx loadwise perf --changed-since origin/main # lines changed in the working tree since a ref
|
|
147
|
+
npx loadwise maint --staged .
|
|
148
|
+
```
|
|
148
149
|
|
|
149
|
-
|
|
150
|
+
These report only findings on changed lines, each with its id, the exact `--fix --only <id>` command when an automatic fix exists, and the `loadwise-reviewed` comment that dismisses it. `--json` keeps the usual shape, filtered, and the exit code is 1 when findings remain. With no changed supported source files the command exits 0 before TypeScript loads. Only the changed files are analysed as roots while imports still resolve through the project; untracked files count as fully changed with `--changed-since`, and a file with unstaged edits can report lines that differ from the staged version. `schema.prisma` findings are not part of this mode. The flags cannot be combined with explicit files, `--watch` or `--fix`.
|
|
150
151
|
|
|
151
|
-
|
|
152
|
+
For maintainability, a JS/TS function-level finding (`high-branch-complexity`, `deep-control-flow`) is kept when a changed line falls anywhere inside its function, and `--fail-on` defaults to `all`. When at least 600 files changed, the full scan runs and is filtered to the changed lines; otherwise `duplicate-implementation` is skipped and `dependency-cycle` only sees cycles made of the changed files' imports.
|
|
152
153
|
|
|
153
154
|
## Configuration
|
|
154
155
|
|
|
@@ -177,13 +178,23 @@ One optional file, `loadwise.config.json`, sets the defaults for every checker.
|
|
|
177
178
|
|
|
178
179
|
- `checkers` is the default selection for `loadwise check`; `--only` and `--skip` override it.
|
|
179
180
|
- `ignore` lists globs, relative to the config file, that no checker scans or reports on; they leave the scan itself, so they cost no time and never count toward duplicates, cycles or architecture. `*` matches within a folder, `**` any depth, `?` one character and `{a,b}` alternatives; naming a folder covers everything below it.
|
|
180
|
-
- `rules` sets each rule to `"off"` (its findings are dropped), `"warn"` (reported, but never changes the exit code) or `"error"` (reported findings always count, even under `--fail-on contract`). A hidden contextual finding is not reported, so it never counts. The object form `{ "level": "warn" }`
|
|
181
|
+
- `rules` sets each rule to `"off"` (its findings are dropped), `"warn"` (reported, but never changes the exit code) or `"error"` (reported findings always count, even under `--fail-on contract`). A hidden contextual finding is not reported, so it never counts. The object form `{ "level": "warn", "options": { ... } }` sets thresholds for rules that take them, such as `maxDepth` or `maxComplexity`; the [config schema](schema/loadwise.config.schema.json) lists each rule's options, and an unknown option exits with code 2.
|
|
181
182
|
- `overrides` apply `rules` to the files matching `files`; a later override wins over an earlier one and over `rules`.
|
|
182
183
|
- `performance` holds the query policy (see [Project-defined access policy](#project-defined-access-policy)), and `maintainability` holds the maintainability policy (see [Project rules](#project-rules)). `--policy file.json` and `--config file.json` name a policy file for one run and beat the config sections.
|
|
183
|
-
- `--ignore <rule-id>` (repeatable, on `check
|
|
184
|
+
- `--ignore <rule-id>` (repeatable, on `check` and every checker) adds a rule to `"off"` for one run and beats the config.
|
|
185
|
+
- `--workspace <name|path>` (repeatable) limits every checker to some workspace packages.
|
|
184
186
|
|
|
185
187
|
An unknown key or rule id, a wrong level or a malformed section exits with code 2 and lists each problem. Rule ids come from the registered checkers, so a rule id that no checker has yet is rejected. The config applies to source checks and the `polyglot` commands; `rel migrations`, `rel contracts`, `perf db`, `perf traces` and `perf plan` do not read it.
|
|
186
188
|
|
|
189
|
+
## Impact levels
|
|
190
|
+
|
|
191
|
+
Every finding carries an impact level, shown after the rule in text output, where the most severe finding comes first within each file. JSON findings carry it as `impactLevel` (`impact` is the before/after estimate). `--min-impact <low|medium|high|critical>` reports only findings at that level or above, and the filtered ones do not count toward the exit code; an unknown level exits 2. The rule tables list each rule's default level, and dependency findings use the advisory severity.
|
|
192
|
+
|
|
193
|
+
- `critical`: data loss or corruption, an outage or a lock risk in production.
|
|
194
|
+
- `high`: a per-request scaling problem such as an N+1 or query in a loop, a deep offset, a missing foreign-key or filter index, an HTTP call without a timeout, or a dependency cycle with load-time effects.
|
|
195
|
+
- `medium`: a measurable but local cost, or significant maintainability debt.
|
|
196
|
+
- `low`: a micro-optimization or a readability issue.
|
|
197
|
+
|
|
187
198
|
## GitHub Action
|
|
188
199
|
|
|
189
200
|
The repository root is a composite action that runs `loadwise check`, prints annotations on the pull request and uploads SARIF to code scanning.
|
|
@@ -220,52 +231,32 @@ The action installs its locked runtime dependencies in a runner temporary direct
|
|
|
220
231
|
|
|
221
232
|
## Use with AI coding agents
|
|
222
233
|
|
|
223
|
-
Ask your coding agent to run Loadwise. On its first check or fix, the CLI gives a recognized agent the review workflow on stderr
|
|
234
|
+
Ask your coding agent to run Loadwise. On its first check or fix, the CLI gives a recognized agent the review workflow on stderr: a check lets the agent inspect every scoped finding, earlier edit, caller and test, and a fix request also lets it apply or adapt justified changes. The agent can read the full workflow with `loadwise agent instructions`. The first run works in a fresh checkout and leaves project instruction files and Git hooks alone.
|
|
224
235
|
|
|
225
236
|
Loadwise recognizes agent shell markers from Codex, Claude Code, Cursor, Gemini CLI and GitHub Copilot, as well as tools that identify themselves with `AI_AGENT`. An integration that supplies no marker can set `LOADWISE_AGENT=1` in its tool subprocess. Set `LOADWISE_AGENT=0` on a command to disable detection. Commands typed in plain Git Bash or an ordinary IDE terminal run normally. A shell opened inside an agent can inherit its markers.
|
|
226
237
|
|
|
227
|
-
|
|
238
|
+
For persistent project instructions, or to have a future agent review fixes you run manually in a terminal, run `npx loadwise agent init`. It updates the managed section of `AGENTS.md`, imports it from `CLAUDE.md` and enables history for manual CLI fixes too.
|
|
228
239
|
|
|
229
|
-
|
|
240
|
+
Agent-run CLI fixes save their actual edited hunks locally from the first fix. For earlier fixes and saved review decisions, run `loadwise agent history` from the checked project, optionally with a checker name such as `maintainability`. History stays under the user's local state directory and can include excerpts of project source. For unrecorded edits, including edits made on another machine, use an earlier report or a known diff.
|
|
230
241
|
|
|
231
|
-
|
|
232
|
-
npx loadwise agent init
|
|
233
|
-
```
|
|
234
|
-
|
|
235
|
-
Agents use the original scan, the relevant history and the rescan to check that every finding has a disposition. The outcomes file is an object with an `outcomes` array. Each entry supplies `checker`, `id`, `status` and specific `evidence`. Supported statuses are `fixed`, `verified`, `intentional`, `false-positive` and `deferred`. For a narrower request, provide only the authorized findings in those reports. With a local Loadwise installation, the commands below run from the project root; put report files in a local scratch directory.
|
|
242
|
+
Agents check that every finding has a disposition with the original scan, the relevant history and the rescan. The outcomes file is an object with an `outcomes` array whose entries supply `checker`, `id`, `status` (`fixed`, `verified`, `intentional`, `false-positive` or `deferred`) and specific `evidence`. For a narrower request, provide only the authorized findings in those reports; put report files in a local scratch directory.
|
|
236
243
|
|
|
237
244
|
```sh
|
|
238
245
|
npx loadwise agent verify --outcomes outcomes.json before.json history.json after.json
|
|
239
246
|
npx loadwise agent verify --save --outcomes outcomes.json before.json history.json after.json
|
|
240
247
|
```
|
|
241
248
|
|
|
242
|
-
The first command checks coverage.
|
|
243
|
-
|
|
244
|
-
For a standalone JSON scan, pass its checker name, for example `npx loadwise agent verify --checker maint --outcomes outcomes.json maint-scan.json`. Use `perf` for performance and database reports, `rel` for reliability, migration and contract reports, `maint` for maintainability, `sec` for security, and `a11y` for accessibility. Use one checker per invocation for unlabelled standalone reports. Combined scans and history keep their original checker selection.
|
|
249
|
+
The first command checks coverage. `--save` also retains successful review decisions for the next session in a recognized agent session or an explicitly initialized checkout. A missing decision or skipped checker is reported as incomplete; a reasoned deferral counts as reviewed and stays visible as deferred. Code review and relevant tests establish whether a change works. For a standalone JSON scan, pass its checker, for example `--checker maint`: `perf` for performance and database reports, `rel` for reliability, migration and contract reports, `maint`, `sec` or `a11y`, one checker per invocation. Combined scans and history keep their original checker selection.
|
|
245
250
|
|
|
246
|
-
To read or save the same brief yourself, use the
|
|
247
|
-
|
|
248
|
-
```sh
|
|
249
|
-
npx loadwise fix --handoff maintainability > loadwise-manual.md
|
|
250
|
-
```
|
|
251
|
+
To read or save the same brief yourself, use the checker names of the fix request: `npx loadwise fix --handoff maintainability > loadwise-manual.md`.
|
|
251
252
|
|
|
252
253
|
### Using Loadwise with an active coding agent
|
|
253
254
|
|
|
254
255
|
Ask the agent you are already working with to check the project with Loadwise. A shell-capable agent can run `npx loadwise check --json` and review the findings directly in the conversation. Ask it to verify findings against your code, suggest improvements, or implement the changes you choose. A check is read-only. A request to apply fixes can use `npx loadwise fix --yes --json` and review the actual edits and remaining findings in the same chat.
|
|
255
256
|
|
|
256
|
-
For an agent that uses Model Context Protocol (MCP), install Loadwise in the project,
|
|
257
|
-
|
|
258
|
-
```bash
|
|
259
|
-
npx loadwise agent mcp --print-config
|
|
260
|
-
```
|
|
261
|
-
|
|
262
|
-
Register the printed command and arguments as a local stdio server named `loadwise` in the agent. The agent can call `loadwise_check` to run a fresh offline scan and review the findings during the current turn. It can read larger reports in pages with `loadwise_read_report`. Loadwise does not start a chat or send findings to another session.
|
|
257
|
+
For an agent that uses Model Context Protocol (MCP), install Loadwise in the project, run `npx loadwise agent mcp --print-config`, and register the printed command and arguments as a local stdio server named `loadwise`. The agent can call `loadwise_check` to run a fresh offline scan and read larger reports in pages with `loadwise_read_report`. Loadwise does not start a chat or send findings to another session.
|
|
263
258
|
|
|
264
|
-
If you ran a terminal command yourself and want to share it later, use `npx loadwise check --review` or `npx loadwise fix --yes --review`. Paste the printed handoff into the chat you choose, or attach the report.
|
|
265
|
-
|
|
266
|
-
### Using Loadwise without AI
|
|
267
|
-
|
|
268
|
-
Run `npx loadwise check` to see findings or `npx loadwise fix --yes` to scan and apply automatic fixes. With the language server running in your editor, hover over a finding to see its recommendation. Findings that require judgment remain available for manual review. [Editor setup](#editor-language-server)
|
|
259
|
+
If you ran a terminal command yourself and want to share it later, use `npx loadwise check --review` or `npx loadwise fix --yes --review`. Paste the printed handoff into the chat you choose, or attach the report. `loadwise agent pending` and the MCP tool `loadwise_list_reports` list saved reports for that project.
|
|
269
260
|
|
|
270
261
|
### Claude Code plugin
|
|
271
262
|
|
|
@@ -276,9 +267,7 @@ Run `npx loadwise check` to see findings or `npx loadwise fix --yes` to scan and
|
|
|
276
267
|
/plugin install loadwise@loadwise
|
|
277
268
|
```
|
|
278
269
|
|
|
279
|
-
After every `Edit`, `Write` or `MultiEdit` on a `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs`, `.mts` or `.cts` file, or a `.html`, `.htm`, `.vue` or `.svelte` file, a hook runs the project's locally installed `loadwise` on that file (`perf`, `rel` and `sec` on the file, `maint` on the uncommitted changes, keeping that file's findings, and `a11y` on `.tsx`, `.jsx`, `.html`, `.htm`, `.vue` and `.svelte` files) with a 20 second limit. Findings go back to Claude with their ids and `--fix --only <id>` commands
|
|
280
|
-
|
|
281
|
-
To turn the hook off, run `/plugin disable loadwise` (or `/plugin uninstall loadwise`).
|
|
270
|
+
After every `Edit`, `Write` or `MultiEdit` on a `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs`, `.mts` or `.cts` file, or a `.html`, `.htm`, `.vue` or `.svelte` file, a hook runs the project's locally installed `loadwise` on that file (`perf`, `rel` and `sec` on the file, `maint` on the uncommitted changes, keeping that file's findings, and `a11y` on `.tsx`, `.jsx`, `.html`, `.htm`, `.vue` and `.svelte` files) with a 20 second limit. Findings go back to Claude with their ids and `--fix --only <id>` commands; a clean file prints nothing. The hook never downloads anything: without a local install, outside a project, on other file types, on a timeout or on any error it exits silently. The plugin also adds a `/loadwise [args]` command for read-only checks and a `/loadwise fix [checker names]` workflow for agent-reviewed remediation. To turn the hook off, run `/plugin disable loadwise` (or `/plugin uninstall loadwise`).
|
|
282
271
|
|
|
283
272
|
### Git pre-commit hook
|
|
284
273
|
|
|
@@ -292,15 +281,9 @@ The hook runs `loadwise check --staged` from the project folder, so every tool t
|
|
|
292
281
|
|
|
293
282
|
## Editor (language server)
|
|
294
283
|
|
|
295
|
-
`loadwise lsp` is a language server for any editor with a Language Server Protocol client. It shows findings from all five checkers
|
|
296
|
-
|
|
297
|
-
```sh
|
|
298
|
-
npx loadwise lsp --stdio
|
|
299
|
-
```
|
|
300
|
-
|
|
301
|
-
On Windows, use `npx.cmd` where the editor does not resolve `npx` itself. Choose the file types each editor attaches it to; the snippets below cover JavaScript, TypeScript and Python, and the checkers also read Go, Java, C#, Rust, HTML, Vue and Svelte.
|
|
284
|
+
`loadwise lsp` is a language server for any editor with a Language Server Protocol client. It shows findings from all five checkers as diagnostics, with hovers, fixes, dismissals and code lenses. It needs Node.js 22+ and this package in the project (`npm install --save-dev loadwise`) or on the PATH. Every editor starts it with `npx loadwise lsp --stdio` (`npx.cmd` on Windows where the editor does not resolve `npx` itself). The snippets below attach it to JavaScript, TypeScript and Python; the checkers also read Go, Java, C#, Rust, HTML, Vue and Svelte.
|
|
302
285
|
|
|
303
|
-
**Neovim 0.11+** (`init.lua`):
|
|
286
|
+
**Neovim 0.11+** (`init.lua`); with an older Neovim, register the same `cmd`, `filetypes` and root markers as a custom nvim-lspconfig server:
|
|
304
287
|
|
|
305
288
|
```lua
|
|
306
289
|
vim.lsp.config('loadwise', {
|
|
@@ -312,19 +295,6 @@ vim.lsp.config('loadwise', {
|
|
|
312
295
|
vim.lsp.enable('loadwise')
|
|
313
296
|
```
|
|
314
297
|
|
|
315
|
-
With an older Neovim and nvim-lspconfig, register the same settings as a custom server:
|
|
316
|
-
|
|
317
|
-
```lua
|
|
318
|
-
require('lspconfig.configs').loadwise = {
|
|
319
|
-
default_config = {
|
|
320
|
-
cmd = { 'npx', 'loadwise', 'lsp', '--stdio' },
|
|
321
|
-
filetypes = { 'javascript', 'javascriptreact', 'typescript', 'typescriptreact', 'python' },
|
|
322
|
-
root_dir = require('lspconfig.util').root_pattern('loadwise.config.json', 'tsconfig.json', 'package.json', '.git'),
|
|
323
|
-
},
|
|
324
|
-
}
|
|
325
|
-
require('lspconfig').loadwise.setup({})
|
|
326
|
-
```
|
|
327
|
-
|
|
328
298
|
**Helix** (`languages.toml`), added beside each language's own server:
|
|
329
299
|
|
|
330
300
|
```toml
|
|
@@ -335,28 +305,9 @@ args = ["loadwise", "lsp", "--stdio"]
|
|
|
335
305
|
[[language]]
|
|
336
306
|
name = "typescript"
|
|
337
307
|
language-servers = ["typescript-language-server", "loadwise"]
|
|
338
|
-
|
|
339
|
-
[[language]]
|
|
340
|
-
name = "python"
|
|
341
|
-
language-servers = ["pylsp", "loadwise"]
|
|
342
308
|
```
|
|
343
309
|
|
|
344
|
-
**Zed** (`settings.json`)
|
|
345
|
-
|
|
346
|
-
```json
|
|
347
|
-
{
|
|
348
|
-
"lsp": {
|
|
349
|
-
"loadwise": {
|
|
350
|
-
"binary": { "path": "npx", "arguments": ["loadwise", "lsp", "--stdio"] },
|
|
351
|
-
"initialization_options": { "loadwise": { "severity": "default" } }
|
|
352
|
-
}
|
|
353
|
-
},
|
|
354
|
-
"languages": {
|
|
355
|
-
"TypeScript": { "language_servers": ["...", "loadwise"] },
|
|
356
|
-
"Python": { "language_servers": ["...", "loadwise"] }
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
```
|
|
310
|
+
**Zed** (`settings.json`) starts only language servers that an extension registers; with one that registers `loadwise`, set `"lsp": { "loadwise": { "binary": { "path": "npx", "arguments": ["loadwise", "lsp", "--stdio"] } } }` and add `"loadwise"` to each language's `language_servers` after `"..."`.
|
|
360
311
|
|
|
361
312
|
**Sublime Text** with the LSP package (**Preferences > Package Settings > LSP > Settings**):
|
|
362
313
|
|
|
@@ -366,14 +317,13 @@ language-servers = ["pylsp", "loadwise"]
|
|
|
366
317
|
"loadwise": {
|
|
367
318
|
"enabled": true,
|
|
368
319
|
"command": ["npx", "loadwise", "lsp", "--stdio"],
|
|
369
|
-
"selector": "source.js | source.jsx | source.ts | source.tsx | source.python"
|
|
370
|
-
"initializationOptions": { "loadwise": { "severity": "default" } }
|
|
320
|
+
"selector": "source.js | source.jsx | source.ts | source.tsx | source.python"
|
|
371
321
|
}
|
|
372
322
|
}
|
|
373
323
|
}
|
|
374
324
|
```
|
|
375
325
|
|
|
376
|
-
**Emacs** with eglot
|
|
326
|
+
**Emacs** with eglot, which runs one server per buffer, so Loadwise takes the place of another server for these modes:
|
|
377
327
|
|
|
378
328
|
```elisp
|
|
379
329
|
(with-eval-after-load 'eglot
|
|
@@ -384,19 +334,9 @@ language-servers = ["pylsp", "loadwise"]
|
|
|
384
334
|
|
|
385
335
|
**VS Code and VSCodium**: install a generic Language Server Protocol client extension from Open VSX and set its server command to `npx loadwise lsp --stdio`. To apply eligible fixes on save, add `"editor.codeActionsOnSave": { "source.fixAll.loadwise": "explicit" }` to your settings.
|
|
386
336
|
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
- Each finding is a diagnostic with its checker as the source (`loadwise perf`, `loadwise maint`, `loadwise sec`) and its rule as the code, linked to the rule's documentation. Related locations, such as the other imports of a dependency cycle, are listed with it. Rule levels from `loadwise.config.json` decide the severity: by default declared contract violations are errors and other findings warnings. Live-database findings, which name a table rather than a file, appear on the first line of `package.json`.
|
|
390
|
-
- Hover over a finding to read the recommendation on the first line (a source-based rewrite, an illustrative example or a review action), then the original finding and the before and after code, highlighted for the file's language.
|
|
391
|
-
- The code actions on a flagged line are **Apply fix: <rule>** when the checker has a rewrite, **Dismiss this finding** and **Dismiss <rule> in this file**, and **Apply all Loadwise fixes in this file** when there are several. Fixes that span several files, or create a migration file, apply all-or-nothing. A fix never overwrites an existing file, and it refuses code that changed since the scan, comparing against the editor's unsaved text. The `source.fixAll.loadwise` action applies every eligible fix in the file as one undoable edit and leaves fixes that need individual review for **Apply fix**.
|
|
392
|
-
- Code lenses put **Apply fix** and **Dismiss** above each fixable line, and **Apply all** on the first line of a file with several fixes.
|
|
393
|
-
- A dismissed finding stays hidden until its flagged line changes; a rule dismissed for a file stays hidden in that file. Dismissals are saved in `.loadwise/dismissed.json` at the workspace folder root, never in your code, and you can commit the file to share them.
|
|
394
|
-
|
|
395
|
-
### What gets scanned
|
|
337
|
+
**What you see.** Each finding is a diagnostic with its checker as the source (`loadwise perf`, `loadwise maint`, `loadwise sec`) and its rule as the code, linked to the rule's page, with related locations such as the other imports of a dependency cycle. Rule levels from `loadwise.config.json` decide the severity: by default declared contract violations are errors and other findings warnings. Live-database findings appear on the first line of `package.json`. Hovers show the recommendation, the finding and the before and after code. Code actions are **Apply fix: <rule>**, **Dismiss this finding**, **Dismiss <rule> in this file** and **Apply all Loadwise fixes in this file**, and code lenses put **Apply fix**, **Dismiss** and **Apply all** above fixable lines. Multi-file fixes apply all-or-nothing, never overwrite an existing file and refuse code that changed since the scan, including unsaved editor text. `source.fixAll.loadwise` applies every eligible fix in the file as one undoable edit and leaves fixes that need individual review for **Apply fix**. A dismissed finding stays hidden until its flagged line changes; dismissals are saved in `.loadwise/dismissed.json` at the workspace folder root, which you can commit to share them.
|
|
396
338
|
|
|
397
|
-
Each workspace folder is scanned
|
|
398
|
-
|
|
399
|
-
### Commands and settings
|
|
339
|
+
**What gets scanned.** Each workspace folder is scanned on start and after every change to a source file, `schema.prisma`, a SQL migration, `package.json`, `tsconfig*.json`, `jsconfig*.json`, `loadwise.config.json` or `.loadwise/dismissed.json`, whether from the editor, git or another tool; a completed source scan in the project terminal refreshes it too. Performance, reliability and accessibility come from an incremental `loadwise perf --watch` process; maintainability and security rerun on each change, and the polyglot rules run when the folder has Python, Go, Java, C# or Rust files. The default project is a root `tsconfig.json` or `jsconfig.json`; in a monorepo, open packages as workspace folders or set `project`. Scan counts and errors go to the editor's language server log.
|
|
400
340
|
|
|
401
341
|
| Command | Action |
|
|
402
342
|
| --------------------------- | ---------------------------------------------------------- |
|
|
@@ -419,20 +359,9 @@ Settings go in the client's `initializationOptions` or its `loadwise` configurat
|
|
|
419
359
|
|
|
420
360
|
# Performance checker
|
|
421
361
|
|
|
422
|
-
`loadwise perf` finds repeated backend work
|
|
423
|
-
|
|
424
|
-
## What you get
|
|
425
|
-
|
|
426
|
-
| Capability | Command | Needs a database |
|
|
427
|
-
| ------------------------- | ---------------------------------------- | ---------------- |
|
|
428
|
-
| Source and ORM checks | `loadwise perf -p tsconfig.json` | No |
|
|
429
|
-
| Migration safety | `loadwise rel migrations` | No |
|
|
430
|
-
| API contract safety | `loadwise rel contracts` | No |
|
|
431
|
-
| Schema-aware index checks | `loadwise perf --schema snap.json` | No (snapshot) |
|
|
432
|
-
| Live database inspection | `loadwise perf db` | Yes, read-only |
|
|
433
|
-
| Traces and executed plans | `traces trace.json`, `plan explain.json` | No |
|
|
362
|
+
`loadwise perf` finds repeated backend work and avoidable React, Vue and Angular rendering work in source code, OpenTelemetry traces and executed database plans. Findings for loops and repeated spans carry an **Impact:** line that says which side is measured and which is estimated (`~`); a millisecond figure is never printed without a measurement behind it.
|
|
434
363
|
|
|
435
|
-
|
|
364
|
+
Sample text finding with its fix diff:
|
|
436
365
|
|
|
437
366
|
```text
|
|
438
367
|
examples/slow.ts:7:48 [array-repeated-find #9ab891a8b8f7] medium: Each item can rescan the lookup array with find(), so cost grows with items times rows. Build `const byKey = new Map()` once (first match wins) and call `byKey.get(key)`; keep the original key-equality semantics.
|
|
@@ -442,38 +371,20 @@ examples/slow.ts:7:48 [array-repeated-find #9ab891a8b8f7] medium: Each item can
|
|
|
442
371
|
+ const names = visible.map(order => customersById.get(order.customerId)?.name ?? 'Unknown');
|
|
443
372
|
```
|
|
444
373
|
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
Try the two included implementations of the same order lookup. The first reports three findings. The second preserves the result order, the first matching customer and the fallback for a missing customer.
|
|
455
|
-
|
|
456
|
-
```sh
|
|
457
|
-
npx loadwise perf node_modules/loadwise/examples/slow.ts
|
|
458
|
-
npx loadwise perf node_modules/loadwise/examples/indexed.ts
|
|
459
|
-
```
|
|
460
|
-
|
|
461
|
-
Use the same one-shot commands in CI. Exit **0** means no displayed finding met the fail threshold, **1** means at least one did and **2** means the check could not complete or skipped a file. Add `--json` for structured output.
|
|
462
|
-
|
|
463
|
-
Source checks summarize contextual findings separately. They include certain one-off blocking calls in CLI startup or unit tests and write advisories in test sources. Use `--include-contextual` to display every candidate and its reason. JSON includes `contextualFindingCount` when any remain after explicit rule exclusions. In the default view this count is additional to the displayed findings. In the expanded view these entries appear in `findings` with a `contextualReason`.
|
|
464
|
-
|
|
465
|
-
The default `--fail-on all` applies to the displayed findings. For a complete advisory report that only fails CI on a transaction-client or import contract violation, use `npx loadwise rel --include-contextual --fail-on contract`. Performance has no contract rules; `loadwise rel --fail-on contract` enforces `pg-transaction-on-pool`.
|
|
466
|
-
|
|
467
|
-
| Input | Command after `npx loadwise perf` | Coverage |
|
|
468
|
-
| --------------------------------------- | ------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |
|
|
469
|
-
| JavaScript or TypeScript | `-p tsconfig.json`, `--watch -p tsconfig.json` or `src/handler.ts` | Typed database calls, collection algorithms, connections and synchronous Node APIs. |
|
|
470
|
-
| Python, Go, Java, C#, Rust | `polyglot src` | Five narrowly scoped source patterns powered by a Rust binary. |
|
|
471
|
-
| OTLP/JSON from any application language | `traces request.otlp.json --threshold 5` | Repeated SQL or NoSQL operations, duplicate lookups and Redis/Valkey commands. |
|
|
472
|
-
| Executed PostgreSQL or MongoDB plan | `plan explain.json` | Inefficient scans, disk sorts and deep pagination at individual plan stages. |
|
|
374
|
+
| Input | Command after `npx loadwise perf` | Needs a database |
|
|
375
|
+
| --------------------------------------- | ------------------------------------------------------------------ | --------------------------------- |
|
|
376
|
+
| JavaScript or TypeScript | `-p tsconfig.json`, `--watch -p tsconfig.json` or `src/handler.ts` | No |
|
|
377
|
+
| Schema-aware index checks | `--schema snapshot.json` | No (snapshot) |
|
|
378
|
+
| Python, Go, Java, C#, Rust | `polyglot src` | No |
|
|
379
|
+
| OTLP/JSON from any application language | `traces request.otlp.json --threshold 5` | No |
|
|
380
|
+
| Executed PostgreSQL or MongoDB plan | `plan explain.json` | No |
|
|
381
|
+
| Live database inspection | `db` | Yes, read-only unless `--measure` |
|
|
473
382
|
|
|
474
383
|
## Source checks
|
|
475
384
|
|
|
476
|
-
Run in the directory containing `tsconfig.json` or `jsconfig.json`, pass `-p path/to/config.json`, or give explicit JS/TS files
|
|
385
|
+
Run in the directory containing `tsconfig.json` or `jsconfig.json`, pass `-p path/to/config.json`, or give explicit JS/TS files (checked with ES2022 and NodeNext defaults). A project check follows project references. JavaScript files that the found config leaves out because `allowJs` is off are still checked with the standalone defaults and named in a note; a config passed with `-p` is checked exactly as it lists its files. Install the application's driver declarations and generate its Prisma client first: unresolved types, wrappers and deferred callbacks can hide findings. Test, seed and operator-tooling sources (`scripts`, `seeds`, `prisma/seed.ts`, `*.seed.ts`, deployment, migrations) make per-item query, index, serial-await, Redis `KEYS`, pure-JavaScript hashing, Prisma dependent-write and Drizzle whole-table-write findings contextual. `prisma-count-for-existence` findings may carry `idField`, the model's single primary-key field that the fix selects.
|
|
386
|
+
|
|
387
|
+
Engines: one-shot checks use Microsoft's Go-based [TypeScript 7](https://github.com/microsoft/typescript-go) compiler on Node.js 22.13+ with the optional native package for your platform (same findings; 1.7–2.2 times faster on the 3,200-file benchmark in [PERFORMANCE.md](PERFORMANCE.md), and the gain depends on the project) and fall back to TypeScript 6.0.3 with a stderr note when TypeScript 7 rejects the configuration (for example `baseUrl` or `moduleResolution: "node10"`). `--engine native` (alias `--native`) requires TypeScript 7 and reports incompatible configuration as exit 2; `--engine js` always uses TypeScript 6.0.3. `perf --json` names the engine in `engine` (`"js"` or `"native"`). `--watch` uses TypeScript 6.0.3 on a single project; with `--watch --json` each completed scan writes one JSON line.
|
|
477
388
|
|
|
478
389
|
<!-- loadwise:rules:start checker=performance group=source-checks -->
|
|
479
390
|
|
|
@@ -547,36 +458,9 @@ Run in the directory containing `tsconfig.json` or `jsconfig.json`, pass `-p pat
|
|
|
547
458
|
|
|
548
459
|
<!-- loadwise:rules:end -->
|
|
549
460
|
|
|
550
|
-
Source diagnostics include a one-based line and column. Repeat `--ignore RULE` to omit specific JS/TS rules from a run. Keep your project's own type check in CI.
|
|
551
|
-
|
|
552
|
-
For an intentionally repeated operation, attach the review to that specific site. The comment must be on its own line immediately before the diagnostic line, name one exact rule and include a reason.
|
|
553
|
-
|
|
554
|
-
```ts
|
|
555
|
-
// loadwise-reviewed pg-query-in-loop -- Each iteration measures a separate query-plan sample.
|
|
556
|
-
await client.query(statement);
|
|
557
|
-
```
|
|
558
|
-
|
|
559
|
-
The site remains available with `--include-contextual`. Source comments cannot lower either CI contract, a configured row-scope check, a Prisma transaction-client escape or a Prisma read-modify-write finding. Test, seed and script context applies to Prisma dependent writes and Drizzle whole-table writes in test sources. It also applies to per-item query rules, index rules, serial awaits in literals, Redis `KEYS` and pure-JavaScript password hashing in test, seed and operator-tooling sources (`scripts`, `seeds`, `prisma/seed.ts`, `*.seed.ts`, deployment, migrations). Application code, tests and scripts still participate in source analysis.
|
|
560
|
-
|
|
561
|
-
Watch mode uses TypeScript 6.0.3. Watch a single project while editing. With `--watch --json`, each completed scan writes one JSON line. Ctrl+C stops the watcher. One-shot runs support project references.
|
|
562
|
-
|
|
563
|
-
One-shot checks pick the compiler automatically. On Node.js 22.13+ with the optional native package for your platform, they use Microsoft's Go-based TypeScript 7.1 beta compiler. It is 2-4 times faster on large projects and reports the same findings. If TypeScript 7 rejects the project configuration, for example `baseUrl` or `moduleResolution: "node10"`, the check uses TypeScript 6.0.3 and prints one note on stderr. `--engine native` (alias `--native`) requires TypeScript 7 and reports incompatible configuration as exit 2. `--engine js` always uses TypeScript 6.0.3. `perf --json` names the engine used in `engine` (`"js"` or `"native"`), and a silent fall-back from the native engine prints a note on stderr. [TypeScript native compiler](https://github.com/microsoft/typescript-go)
|
|
564
|
-
|
|
565
|
-
Install the application's driver declarations and generate its Prisma client before checking. Result-shape checks target simple literal PostgreSQL reads and supported Prisma model delegates. Unresolved types, wrappers and deferred callbacks can hide findings. Repeated calls can be intentional, for example retries and ordered writes.
|
|
566
|
-
|
|
567
461
|
## ORM and query integrity checks
|
|
568
462
|
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
| Library | Source patterns covered |
|
|
572
|
-
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
573
|
-
| Prisma | Executed per-item operations, fetching rows only to count, filter, sort or take the first, dependent creates, transaction client use and stale numeric overwrites. |
|
|
574
|
-
| Drizzle ORM | Executed fluent queries on the PostgreSQL, MySQL and SQLite core APIs, per-item prepared executions, and direct mutations with an absent or demonstrably ineffective predicate. |
|
|
575
|
-
| TypeORM | Repository reads inside repeated execution and simple `find` or `findBy` calls that load entities only for their count. |
|
|
576
|
-
| Sequelize | Model reads inside repeated execution and immediate counts of simple `findAll` results. |
|
|
577
|
-
| Mongoose | Consumed model queries including common `lean` and `exec` chains, plus immediate counts for simple equivalent filters. |
|
|
578
|
-
| Knex and Kysely | Consumed Knex builders and Kysely SELECT execution methods inside repeated work. Simple single-table queries materialized only to read their length. |
|
|
579
|
-
| node-postgres | Per-item queries, client-side result processing, pool handoff and transaction commands issued through a pool. |
|
|
463
|
+
Covered libraries: Prisma, Drizzle ORM (PostgreSQL, MySQL and SQLite core APIs), TypeORM, Sequelize, Mongoose, Knex, Kysely and node-postgres. Building an array of lazy Prisma queries alone is quiet, and same-tick `findUnique` calls that Prisma batches itself are left to runtime traces.
|
|
580
464
|
|
|
581
465
|
<!-- loadwise:rules:start checker=performance group=orm-and-query-integrity-checks -->
|
|
582
466
|
|
|
@@ -595,11 +479,9 @@ The JS/TS checker resolves declarations from installed drivers and generated cli
|
|
|
595
479
|
|
|
596
480
|
<!-- loadwise:rules:end -->
|
|
597
481
|
|
|
598
|
-
For Prisma, building an array of lazy queries alone is quiet. A sequential `await` inside a loop can trigger the rule. Same-tick `findUnique` callbacks can use Prisma's own batching, so these are left to runtime traces. [Prisma Client reference](https://www.prisma.io/docs/orm/reference/prisma-client-reference#prismapromise-behavior) · [Prisma transactions](https://www.prisma.io/docs/orm/prisma-client/queries/transactions) · [node-postgres transactions](https://node-postgres.com/features/transactions) · [Drizzle conditional filters](https://orm.drizzle.team/docs/guides/conditional-filters-in-query)
|
|
599
|
-
|
|
600
482
|
### Project-defined access policy
|
|
601
483
|
|
|
602
|
-
Put the policy in the `performance` section of `loadwise.config.json` beside the selected project config (in the working directory for explicit source files), or pass `--policy path/to/file.json`. A policy can use just the sections the project needs
|
|
484
|
+
Put the policy in the `performance` section of `loadwise.config.json` beside the selected project config (in the working directory for explicit source files), or pass `--policy path/to/file.json`. A policy can use just the sections the project needs: `parallelReads` (groups of exports that may start together, used by `known-reads-awaited-serially`), `fireAndForget` (helper names that `floating-promise` accepts without an await), and `prismaScopes` and `drizzleScopes` (see [Project-defined row scopes](#project-defined-row-scopes)). Duplicate JSON keys within the same object produce a configuration error. [Example policy](examples/query-policy.json)
|
|
603
485
|
|
|
604
486
|
### Async work and sorting
|
|
605
487
|
|
|
@@ -619,54 +501,9 @@ Put the policy in the `performance` section of `loadwise.config.json` beside the
|
|
|
619
501
|
|
|
620
502
|
<!-- loadwise:rules:end -->
|
|
621
503
|
|
|
622
|
-
The example policy declares that `fetchUser` and `fetchPosts` from `@app/reads` may start together. Only group operations whose ordering, shared connections, rate limits and failure effects your project has reviewed. With that declaration, the checker can flag the pair below. Ordinary adjacent calls such as `saveSettings()` followed by `reloadSettings()` carry no such contract.
|
|
623
|
-
|
|
624
|
-
```ts
|
|
625
|
-
import { fetchUser, fetchPosts } from '@app/reads';
|
|
626
|
-
|
|
627
|
-
async function load() {
|
|
628
|
-
const user = await fetchUser();
|
|
629
|
-
const posts = await fetchPosts();
|
|
630
|
-
return { user, posts };
|
|
631
|
-
}
|
|
632
|
-
```
|
|
633
|
-
|
|
634
|
-
The CLI reports review candidates and leaves source files untouched. The scheduling and sorting rules were implemented in this package. The lockfile test checks the full resolved graph for ESLint and the referenced plugins. Design references include the documented ordering limits of sequential-await analysis, ESLint's loop examples and Unicorn's numeric-sort and Promise rules. [Parallelize](https://github.com/braeden/eslint-plugin-parallelize) · [ESLint](https://eslint.org/docs/latest/rules/no-await-in-loop) · [Unicorn](https://github.com/sindresorhus/eslint-plugin-unicorn) · [Perf Fiscal](https://github.com/ruidosujeira/perf-fiscal)
|
|
635
|
-
|
|
636
|
-
## Inline fixes
|
|
637
|
-
|
|
638
|
-
Where a rule has a safe rewrite for the flagged code, the finding carries a concrete change. With `--json`, it is `fix = { changes: [{ file, line, before, after, create? }], note? }`. Text output prints the change as a diff. A change with `create` holds a whole new file, for example a migration that adds an index. Rules with no safe rewrite fall back to a generic example.
|
|
639
|
-
|
|
640
|
-
```sh
|
|
641
|
-
npx loadwise perf -p tsconfig.json --fix # asks y/n/a/q for each fix; needs a terminal
|
|
642
|
-
npx loadwise perf -p tsconfig.json --fix --yes # applies eligible fixes without asking
|
|
643
|
-
```
|
|
644
|
-
|
|
645
|
-
`--fix` answers are **y**es, **n**o, **a**ll remaining and **q**uit. Without a terminal it requires `--yes`. `--fix` cannot be combined with `--watch`, or with `--json` except with `--only`, and `--yes` is valid only with `--fix`. A fix applies only where the original lines still exist, so code that changed since the scan is refused and a change already in the file is reported as already applied. A fix never overwrites an existing file. Like `loadwise fix`, it adds a why-comment above each fixed statement and formats the changed lines with the project's Prettier; `--no-comments` and `--no-format` turn these off. Review the diff and run your tests afterwards. Rewrites that narrow a whole-table Drizzle update to rows with differing values require individual review because the change can affect locking, triggers and affected-row counts. Upload size limits also require individual review. So does the Mongoose `.lean()` rewrite, because a lean result skips schema defaults, getters and virtuals. The 10 MiB example can reject valid uploads, so check the endpoint's file requirements and any existing gateway or Multer limits before applying it.
|
|
646
|
-
|
|
647
|
-
## Apply fixes by id
|
|
648
|
-
|
|
649
|
-
Every finding has a stable `id`, shown as `[rule-id #id]` in text output. It hashes the rule, the file and the flagged line's text, so it survives edits above the finding. JSON findings also carry `fixable` and, when available, `fix`. `prisma-count-for-existence` findings may carry `idField`, the model's single primary-key field, which the fix uses for its `select`. To apply chosen fixes without a prompt:
|
|
650
|
-
|
|
651
|
-
```sh
|
|
652
|
-
npx loadwise perf --fix --only a1b2c3d4e5f6,0f9e8d7c6b5a --json # prints { applied, alreadyApplied, failed }
|
|
653
|
-
```
|
|
654
|
-
|
|
655
|
-
An unknown id, a finding with no fix, or a fix whose code changed since the scan is listed in `failed`, and the exit code is 2. An id whose change an earlier id in the same run already made, such as a shared `Set`, is listed in `alreadyApplied` and is not a failure. To dismiss a false positive, add the `// loadwise-reviewed <rule-id> -- <reason>` comment described under Source checks.
|
|
656
|
-
|
|
657
|
-
## Check only the lines you changed
|
|
658
|
-
|
|
659
|
-
```sh
|
|
660
|
-
npx loadwise perf --staged # lines added or modified in the git index
|
|
661
|
-
npx loadwise perf --changed-since origin/main # lines changed in the working tree since a ref
|
|
662
|
-
npx loadwise perf -p tsconfig.json --staged --json
|
|
663
|
-
```
|
|
664
|
-
|
|
665
|
-
Both flags report only findings on changed lines, each with its id, the exact `--fix --only <id>` command when an automatic fix exists, and the `// loadwise-reviewed <rule-id> -- <reason>` comment that dismisses it. `--json` keeps the usual shape, filtered. The exit code is 1 when findings remain. With no changed JavaScript or TypeScript files the command exits 0 before TypeScript loads. Only the changed files are analyzed as roots, and their imports still resolve through the tsconfig; `schema.prisma` findings are not part of this mode. Files that are untracked count as fully changed with `--changed-since`. Analysis reads the working tree, so a file with unstaged edits can report lines that differ from the staged version. The flags cannot be combined with explicit files, `--watch` or `--fix`.
|
|
666
|
-
|
|
667
504
|
## Schema-aware index checks
|
|
668
505
|
|
|
669
|
-
The source checker reads the project's ORM schema (Prisma, Drizzle, TypeORM, Sequelize, Mongoose) and compares declared indexes with the queries it finds.
|
|
506
|
+
The source checker reads the project's ORM schema (Prisma, Drizzle, TypeORM, Sequelize, Mongoose) and compares declared indexes with the queries it finds. Each suggested index carries one explicit name, used both in the ORM snippet and in the `CREATE INDEX CONCURRENTLY` statement, so building it by hand and then generating a migration does not create a duplicate. Pass `--schema snapshot.json` (written by `perf db --schema-snapshot`) to refine findings with real table sizes and the measured round trip, which also feeds the Impact line of `*-query-in-loop` findings.
|
|
670
507
|
|
|
671
508
|
<!-- loadwise:rules:start checker=performance group=schema-aware-index-checks -->
|
|
672
509
|
|
|
@@ -681,15 +518,9 @@ The source checker reads the project's ORM schema (Prisma, Drizzle, TypeORM, Seq
|
|
|
681
518
|
|
|
682
519
|
<!-- loadwise:rules:end -->
|
|
683
520
|
|
|
684
|
-
Each suggested index carries one explicit name, used both in the ORM snippet (`@@index([a, b], map: "<name>")`, `@Index('<name>', ['a', 'b'])`, `{ name: '<name>', fields: [...] }`, `index('<name>')`, `schema.index({ a: 1 }, { name: '<name>' })`) and in the `CREATE INDEX CONCURRENTLY` statement for a live database, so building it by hand and then generating a migration does not create a duplicate. A fix that adds an index to a Prisma, TypeORM or Drizzle model says to generate a migration for it.
|
|
685
|
-
|
|
686
|
-
Pass `--schema snapshot.json` (written by `db --schema-snapshot`) to refine them with real table sizes and the measured round trip, which also feeds the Impact line of `*-query-in-loop` findings. Without a snapshot, the checks run from the source schema alone.
|
|
687
|
-
|
|
688
521
|
## Polyglot source checks
|
|
689
522
|
|
|
690
|
-
`npx loadwise perf polyglot src` accepts directories or individual `.py`, `.go`, `.java`, `.cs` and `.rs` files
|
|
691
|
-
|
|
692
|
-
Performance and maintainability scans retry files when the bundled parser rejects a Java marker annotation before varargs or a C# 14 conditional member assignment (`=`) in a simple identifier chain. The retry uses a position-preserving copy in memory and still fails if the parser reports a syntax error.
|
|
523
|
+
`npx loadwise perf polyglot src` accepts directories or individual `.py`, `.go`, `.java`, `.cs` and `.rs` files and needs the optional [ast-grep](https://ast-grep.github.io/) native binary. `npx loadwise rel polyglot src` runs the reliability patterns on the same files. Language-specific aliases and wrappers can fall outside a pattern.
|
|
693
524
|
|
|
694
525
|
<!-- loadwise:rules:start checker=performance group=polyglot-source-checks -->
|
|
695
526
|
|
|
@@ -717,9 +548,7 @@ Performance and maintainability scans retry files when the bundled parser reject
|
|
|
717
548
|
|
|
718
549
|
## Trace checks in other languages and databases
|
|
719
550
|
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
Try `npx loadwise perf traces node_modules/loadwise/examples/repeated-db.otlp.json`. The example reports five similar MongoDB operations under one parent. The trace rules use current and legacy database attributes and deduplicate span IDs.
|
|
551
|
+
`npx loadwise perf traces <file>` reads one local OTLP/JSON trace export (`resourceSpans → scopeSpans → spans`), such as an OpenTelemetry Collector file export; for a collector output with multiple JSON lines, pass the export object for the request. `--threshold` sets how many similar sibling calls form a finding. Try `npx loadwise perf traces node_modules/loadwise/examples/repeated-db.otlp.json`. Reports contain span IDs and counts and omit raw SQL, parameters and keys; check `scannedSpans` and `eligibleDbSpans` when interpreting a clean result.
|
|
723
552
|
|
|
724
553
|
<!-- loadwise:rules:start checker=performance group=trace-checks-in-other-languages-and-databases -->
|
|
725
554
|
|
|
@@ -732,11 +561,9 @@ Try `npx loadwise perf traces node_modules/loadwise/examples/repeated-db.otlp.js
|
|
|
732
561
|
|
|
733
562
|
<!-- loadwise:rules:end -->
|
|
734
563
|
|
|
735
|
-
Matching keys in two reads are a reason to consider **request-local** reuse when authorization, freshness and ordering allow it. Keep existing telemetry redaction. A redacted key can still support a batching finding. Reports contain span IDs and counts and omit raw SQL, parameters and keys. Check `scannedSpans` and `eligibleDbSpans` when interpreting a clean result. Sampling, missing parents, different literal values and coarse summaries affect grouping. [OpenTelemetry database spans](https://opentelemetry.io/docs/specs/semconv/db/database-spans/) · [OTLP JSON encoding](https://opentelemetry.io/docs/specs/otlp/#json-protobuf-encoding)
|
|
736
|
-
|
|
737
564
|
## Executed query plans
|
|
738
565
|
|
|
739
|
-
|
|
566
|
+
`npx loadwise perf plan <file>` reads a JSON file from PostgreSQL `EXPLAIN (ANALYZE, FORMAT JSON)` or MongoDB `explain("executionStats")`, for example `node_modules/loadwise/examples/postgres-plan.json`, and reports the stage path and observed counts (MongoDB: classic stages and selected slot-based scan, filter and skip shapes). Planner estimates alone, and layouts where a scan cannot be attributed, exit 2. PostgreSQL's `ANALYZE` option executes the statement when you collect the plan.
|
|
740
567
|
|
|
741
568
|
<!-- loadwise:rules:start checker=performance group=executed-query-plans -->
|
|
742
569
|
|
|
@@ -751,8 +578,6 @@ Feed the CLI a JSON file from PostgreSQL `EXPLAIN (ANALYZE, FORMAT JSON)` or Mon
|
|
|
751
578
|
|
|
752
579
|
<!-- loadwise:rules:end -->
|
|
753
580
|
|
|
754
|
-
Results include the stage path and observed counts. PostgreSQL and MongoDB planner estimates alone return exit 2. MongoDB coverage includes classic executed query stages and selected slot-based scan/filter and skip shapes. Unsupported layouts return an input error where a scan cannot be attributed.
|
|
755
|
-
|
|
756
581
|
## Database inspection (optional)
|
|
757
582
|
|
|
758
583
|
`npx loadwise perf db` is the only command that connects to a database. Point it at a staging or read replica database, never a primary you cannot afford to touch. It uses the project's own `pg`, `mysql2` or `mongodb` package.
|
|
@@ -774,7 +599,7 @@ npx loadwise perf --schema snapshot.json
|
|
|
774
599
|
| `--measure --i-understand-this-locks-tables` | PostgreSQL staging only. Time each suggested index for `--queries` by building it in a rolled-back transaction. |
|
|
775
600
|
| `--runs N` | `EXPLAIN ANALYZE` runs per side for `--measure` (default 5). |
|
|
776
601
|
|
|
777
|
-
|
|
602
|
+
`--include-contextual`, `--ignore RULE` and `--json` work as in the other commands.
|
|
778
603
|
|
|
779
604
|
<!-- loadwise:rules:start checker=performance group=database-inspection-optional -->
|
|
780
605
|
|
|
@@ -790,83 +615,17 @@ Rules: `db-unindexed-foreign-key`, `db-unused-index`, `db-duplicate-index`, `db-
|
|
|
790
615
|
|
|
791
616
|
<!-- loadwise:rules:end -->
|
|
792
617
|
|
|
793
|
-
**Safety
|
|
794
|
-
|
|
795
|
-
**`--measure` warning.** Building an index blocks writes to that table while it runs. Use it on staging only. It refuses a connection variable or database name matching `/prod/i`, a replica, an unknown table size and any table over 5,000,000 estimated rows, and it needs the long confirmation flag. When the HypoPG extension is installed, suggested indexes are also checked hypothetically without building anything.
|
|
796
|
-
|
|
797
|
-
**Measured vs estimated.** Output labels every figure. A _measured_ number was timed on your database (a round-trip median, or an `EXPLAIN ANALYZE` before and after an index built by `--measure`). An _estimated_ number comes from planner statistics or a model, and a suggestion validated only by HypoPG still says it is an estimate. Treat estimates as a reason to test, not as a result.
|
|
798
|
-
|
|
799
|
-
## Interpreting findings
|
|
800
|
-
|
|
801
|
-
Start with the endpoint's query count, latency and a representative input size. A reusable index or lookup table costs memory and build time. An extra database index also costs writes and storage. For a proposed batch or cache, compare results as well as time, including empty inputs, duplicates, tenant boundaries and concurrent writes.
|
|
802
|
-
|
|
803
|
-
The rules cover query shape, caching candidates, pooling, selected blocking work and collection complexity. Response compression settings, CDN placement, load balancing, partitioning, service boundaries and capacity planning depend on traffic, topology and operational costs. Use workload measurements when making those deployment decisions. [10 Essential Tips for Backend Performance Optimization](https://medium.com/@rhgustmfrh/10-essential-tips-for-backend-performance-optimization-8b55fce0ca17) · [Backend Performance Best Practices roadmap](https://roadmap.sh/backend-performance-best-practices)
|
|
804
|
-
|
|
805
|
-
## Impact levels
|
|
806
|
-
|
|
807
|
-
Every finding carries an impact level. `--min-impact <low|medium|high|critical>` reports only findings at that level or above, and the filtered ones do not count toward the exit code; an unknown level exits 2. JSON findings carry it as `impactLevel` (`impact` is the before/after estimate). Text output shows the level after the rule and lists the most severe finding first within each file, keeping the current order for equal levels.
|
|
808
|
-
|
|
809
|
-
- `critical`: data loss or corruption, an outage or a lock risk in production.
|
|
810
|
-
- `high`: a per-request scaling problem such as an N+1 or query in a loop, a deep offset, a missing foreign-key or filter index, an HTTP call without a timeout, or a dependency cycle with load-time effects.
|
|
811
|
-
- `medium`: a measurable but local cost, or significant maintainability debt.
|
|
812
|
-
- `low`: a micro-optimization or a readability issue.
|
|
618
|
+
**Safety.** Sessions and transactions are read-only, with a 5 s statement timeout on PostgreSQL, and only SELECT, INSERT, UPDATE and DELETE can be explained. `EXPLAIN ANALYZE` runs only for a plain SELECT (a `WITH` that modifies data is refused). MongoDB uses a command allowlist. Error text replaces the connection URL, host, user, password and resolved IP addresses with `[redacted]`. Usage counters come from the node that answered, so an index unused here may still be used on a replica.
|
|
813
619
|
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
Integration checks used PostgreSQL 18.0 and MongoDB 8.2.3. Each engine examined 20,000 records for one match before an index was added. The corresponding indexed read passed. In both databases a deep page walked 15,010 entries to return ten, and the equivalent keyset query passed. Both engines also produced a disk-sort finding. MongoDB's live test used classic execution stages.
|
|
817
|
-
|
|
818
|
-
On Redis 7.2.16, the CLI flagged a real `KEYS` call and eight redacted `GET` calls. A test hook exposing only a synthetic key let it identify eight duplicate reads. A single request-local read returned the same eight values and passed. Python SQLite instrumentation separately verified nine statements versus one batched statement for the same eight result rows.
|
|
819
|
-
|
|
820
|
-
Use Node.js 22.13+ for the full development workflow, including the in-memory SQLite benchmark.
|
|
821
|
-
|
|
822
|
-
### Source conventions
|
|
823
|
-
|
|
824
|
-
The CLI and checkers are TypeScript (`.ts`) compiled in place to ES modules (`.js`, not committed) by `npm run build`, while the security example tables under `lib/security/examples/` are `.cts` compiled to CommonJS (`.cjs`); `npm test` builds first and `npm run typecheck` checks without emitting. Import with the runtime extension (`.js` or `.cjs`). The compiler runs in `strict` mode.
|
|
825
|
-
|
|
826
|
-
- Write ES `import`/`export`, with imports at the top of the file. Oxlint rejects `require()`. Where load order or startup cost forbids a top-level import (the compiler must be chosen before the rules load, and `maint --staged` must not load TypeScript), load lazily in an async function with `await import()`.
|
|
827
|
-
- No `any` and no `as` assertions (`as const` is fine) in new code. Narrow with type guards, give a function a precise type, or use overloads. A deliberate exception needs a lint-disable comment that says why.
|
|
828
|
-
- Types shared by two or more files live in the `types/` folder of their area (`lib/performance/types/`, `lib/security/types/`, `lib/maintainability/types/`, `lib/shared/types/`, `test/types/`), one topic per file. Cross-pillar types are in `lib/shared/types.ts`. A type used by one file stays in that file.
|
|
829
|
-
- Comments wrap at 100 columns, and Prettier formats everything. `.vscode/settings.json` formats on save, and the pre-commit hook in `hooks/` formats and lints staged files (`npm install` enables it).
|
|
830
|
-
|
|
831
|
-
```sh
|
|
832
|
-
npm ci
|
|
833
|
-
npm test
|
|
834
|
-
node bin/loadwise.js perf -p examples
|
|
835
|
-
npm run bench:patterns
|
|
836
|
-
npm run bench:scan
|
|
837
|
-
npm run bench:scan -- --large
|
|
838
|
-
npm run bench:traces
|
|
839
|
-
npm run bench:scorecard
|
|
840
|
-
npm run bench:corpus
|
|
841
|
-
npm run bench:recall
|
|
842
|
-
```
|
|
843
|
-
|
|
844
|
-
The benchmark commands verify their expected results. The pattern benchmark compares equal application outputs. The scan benchmarks measure the checker itself. Real request latency depends on the workload, instrumentation and database. `bench:scorecard` writes `bench/corpus/scorecard.md`, and `bench:corpus` fails when a default-level rule with at least 10 labels is under 80% precision, unless `bench/corpus/precision-floor-exceptions.json` lists it. `bench:recall` scans the known-vulnerable and known-slow snippets in `bench/recall/cases`, prints the recall, and exits 1 while any case in `bench/recall/manifest.json` is missed.
|
|
845
|
-
|
|
846
|
-
To repeat the optional six-package ORM declaration integration from the source checkout, run the commands below. The fixture typechecks the application, compares exact diagnostic locations and checks that clean controls stay quiet.
|
|
847
|
-
|
|
848
|
-
```sh
|
|
849
|
-
npm --prefix test/performance/integration/orms install --ignore-scripts --omit=optional --no-audit --no-fund
|
|
850
|
-
npm --prefix test/performance/integration/orms run verify -- --native
|
|
851
|
-
```
|
|
852
|
-
|
|
853
|
-
The large benchmark checks 3,200 generated source files and verifies expected diagnostics. The performance report also covers a 1,180-file NestJS checkout. [Measurements and methodology](PERFORMANCE.md)
|
|
854
|
-
|
|
855
|
-
## References
|
|
856
|
-
|
|
857
|
-
Prisma documents per-item queries and batching. Node documents the event-loop effects of synchronous file I/O. [Prisma query optimization](https://www.prisma.io/docs/orm/v6/prisma-client/queries/query-optimization-performance) · [Node event loop guidance](https://nodejs.org/learn/asynchronous-work/dont-block-the-event-loop)
|
|
858
|
-
|
|
859
|
-
Repeated lookups can benefit from a reusable membership index. Repeated growing copies can become quadratic. Biome already includes a lint rule for accumulating spread. [JavaScript Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) · [Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#when_to_not_use_reduce) · [Biome rule](https://biomejs.dev/linter/rules/no-accumulating-spread/javascript/)
|
|
860
|
-
|
|
861
|
-
Sentry also has an N+1 detector that considers sequential spans and their total duration. This package's local trace check groups similar sibling calls, including concurrent calls. [Sentry N+1 detection](https://docs.sentry.io/product/issues/issue-details/performance-issues/n-one-queries/)
|
|
620
|
+
**`--measure` blocks writes** to the table while each index builds. It refuses a connection variable or database name matching `/prod/i`, a replica, an unknown table size and any table over 5,000,000 estimated rows, and it needs the long confirmation flag. With the HypoPG extension, suggested indexes are also checked hypothetically. Output labels every figure as _measured_ (timed on your database) or _estimated_ (planner statistics, a model or HypoPG).
|
|
862
621
|
|
|
863
622
|
# Reliability checker
|
|
864
623
|
|
|
865
|
-
`loadwise rel` finds code that fails at runtime or under concurrency: unhandled rejections, swallowed errors, races, missing timeouts and idempotency, transactions that escape their client, unsafe migrations and breaking API changes. It shares the source check of `loadwise perf`, so project discovery, policy, config, engines, baselines and fix flags are the same, and `loadwise check` type-checks the project once for both. Run it with `npx loadwise rel -p tsconfig.json`; `npx loadwise rel --help` lists every flag.
|
|
624
|
+
`loadwise rel` finds code that fails at runtime or under concurrency: unhandled rejections, swallowed errors, races, missing timeouts and idempotency, transactions that escape their client, unsafe migrations and breaking API changes. It shares the source check of `loadwise perf`, so project discovery, policy, config, engines, baselines and fix flags are the same, and `loadwise check` type-checks the project once for both. Run it with `npx loadwise rel -p tsconfig.json`; `npx loadwise rel --help` lists every flag. `loadwise rel --fail-on contract` enforces only `pg-transaction-on-pool`.
|
|
866
625
|
|
|
867
626
|
## Source rules
|
|
868
627
|
|
|
869
|
-
|
|
628
|
+
Some rules moved here from the performance and maintainability checkers and kept their ids, so existing `// loadwise-reviewed` comments, `--ignore` flags and config `rules` entries keep working. `csharp-async-void` and the `python-`, `go-`, `java-`, `csharp-` and `rust-` rules come from `loadwise rel polyglot`, which needs the optional ast-grep executable.
|
|
870
629
|
|
|
871
630
|
<!-- loadwise:rules:start checker=reliability group=source-rules -->
|
|
872
631
|
|
|
@@ -960,32 +719,18 @@ The rules from `pg-transaction-on-pool` to `swallowed-error` moved from the perf
|
|
|
960
719
|
|
|
961
720
|
<!-- loadwise:rules:end -->
|
|
962
721
|
|
|
963
|
-
Only new migrations fail the run
|
|
964
|
-
|
|
965
|
-
**CI recipe.** Enforce only what the branch adds or changes (files modified since the merge base, plus untracked files). Use a full-history checkout (`fetch-depth: 0`) so the ref resolves.
|
|
966
|
-
|
|
967
|
-
```sh
|
|
968
|
-
npx loadwise rel migrations --changed-since origin/main
|
|
969
|
-
```
|
|
970
|
-
|
|
971
|
-
**Baseline workflow.** For a project with existing migrations, accept them once and enforce the rest.
|
|
722
|
+
Only new migrations fail the run; older ones are contextual (counted, listed with `--include-contextual`, never exit 1). In CI, `--changed-since origin/main` enforces only migrations the branch adds or changes (plus untracked files) and needs a full-history checkout (`fetch-depth: 0`). For a project with existing migrations, accept them once:
|
|
972
723
|
|
|
973
724
|
```sh
|
|
974
|
-
npx loadwise rel migrations --write-baseline # writes loadwise.migrations-baseline.json
|
|
725
|
+
npx loadwise rel migrations --write-baseline # writes loadwise.migrations-baseline.json; commit it
|
|
975
726
|
npx loadwise rel migrations # new migrations fail; baselined ones do not
|
|
976
727
|
```
|
|
977
728
|
|
|
978
|
-
|
|
729
|
+
`--baseline FILE` reads or writes another path. Exit codes: 0 passed, 1 findings in enforced migrations, 2 invalid input.
|
|
979
730
|
|
|
980
731
|
## API contract safety
|
|
981
732
|
|
|
982
|
-
`npx loadwise rel contracts [--changed-since REF] [--json]` compares the working tree with the merge base of `REF` (default `HEAD`) and flags changes that break API clients
|
|
983
|
-
|
|
984
|
-
It compares three kinds of source:
|
|
985
|
-
|
|
986
|
-
- **OpenAPI and Swagger JSON** (`openapi.json`, `swagger.json`). YAML documents are skipped with a note, because no YAML parser ships with loadwise; commit or check a JSON export instead.
|
|
987
|
-
- **GraphQL SDL** (`*.graphql`, `*.gql`, for example the `schema.gql` a code-first server emits). Query documents are skipped.
|
|
988
|
-
- **NestJS classes** used as `@Body()` types or as controller return types (also `@ApiResponse({ type })`), found in `*.controller.ts` and read from the file that declares them (relative imports only). Only property names, `?`, `@IsOptional()` and the written type text are compared.
|
|
733
|
+
`npx loadwise rel contracts [--changed-since REF] [--json]` compares the working tree with the merge base of `REF` (default `HEAD`) and flags changes that break API clients; `loadwise check --changed-since REF` includes the same findings in the reliability report. Both respect workspace selection, ignored paths and rules, configured rule levels and minimum impact, and need a full-history checkout so the ref resolves. It compares OpenAPI and Swagger JSON (`openapi.json`, `swagger.json`; YAML is skipped with a note), GraphQL SDL (`*.graphql`, `*.gql`; query documents are skipped) and NestJS classes used as `@Body()` types or controller return types (also `@ApiResponse({ type })`) in `*.controller.ts`, read through relative imports. Only property names, `?`, `@IsOptional()` and the written type text are compared, and properties inherited from a base class in a relative import count as the class's own. A removed request property is flagged only when the project builds a `ValidationPipe` with `forbidNonWhitelisted: true`. Removals point at the line in the old version; a new version next to the old one (`/v2/users` beside `/v1/users`) is not flagged.
|
|
989
734
|
|
|
990
735
|
<!-- loadwise:rules:start checker=reliability group=api-contract-safety -->
|
|
991
736
|
|
|
@@ -999,20 +744,9 @@ It compares three kinds of source:
|
|
|
999
744
|
|
|
1000
745
|
<!-- loadwise:rules:end -->
|
|
1001
746
|
|
|
1002
|
-
Removals point at the line in the old version (the message says so); every other finding points at the new line. A new version next to the old one (`/v2/users` added while `/v1/users` stays) breaks nothing and is not flagged. A removed request property is flagged only when the project builds a `ValidationPipe` with `forbidNonWhitelisted: true`, because only then do clients that still send it get a 400. Properties inherited from a base class in a relative import count as the class's own.
|
|
1003
|
-
|
|
1004
|
-
```sh
|
|
1005
|
-
npx loadwise rel contracts --changed-since origin/main
|
|
1006
|
-
npx loadwise check --changed-since origin/main
|
|
1007
|
-
```
|
|
1008
|
-
|
|
1009
|
-
## Impact levels
|
|
1010
|
-
|
|
1011
|
-
The levels and the `--min-impact` flag work as described under the performance checker's impact levels. `loadwise rel` and the reliability section of `loadwise check` use the impact levels in the rule index.
|
|
1012
|
-
|
|
1013
747
|
# Maintainability checker
|
|
1014
748
|
|
|
1015
|
-
`loadwise maint` finds code that would benefit from a design review and enforces the architectural decisions a team has already made. Run it on a project folder with `npx loadwise maint .`, or `npx loadwise maint . --json` for
|
|
749
|
+
`loadwise maint` finds code that would benefit from a design review and enforces the architectural decisions a team has already made. Run it on a project folder with `npx loadwise maint .`, or `npx loadwise maint . --json`. The default `--fail-on contract` exits 1 only for a declared folder, data-access or query contract violation; design advisories stay visible and exit 0 on their own. A non-JavaScript file a native parser cannot read and missing required parser binaries exit 2. Contextual findings include documented independent test oracles, before/after source snapshots with a live counterpart, marked generated code, certain flat data mappings and literal message lists, and a Nest module cycle whose internal eager edges are all explicit `forwardRef` callbacks (not available for graph input).
|
|
1016
750
|
|
|
1017
751
|
## What gets checked
|
|
1018
752
|
|
|
@@ -1044,9 +778,7 @@ The levels and the `--min-impact` flag work as described under the performance c
|
|
|
1044
778
|
|
|
1045
779
|
<!-- loadwise:rules:end -->
|
|
1046
780
|
|
|
1047
|
-
JS and TS
|
|
1048
|
-
|
|
1049
|
-
For any language, filename placement works directly on the inventory and module graphs can be supplied by a compiler, build system or dependency extractor. Direct import extraction is provided for JS/TS. It resolves project-local modules and TypeScript paths and ignores explicitly type-only imports. Unresolved aliases, compiler-specific metadata, runtime-generated imports, and some re-exports can change the actual runtime graph. JSON includes per-language parsed-file counts and the number of files eligible for automatic dependency analysis.
|
|
781
|
+
JS and TS use the TypeScript parser; the optional ast-grep executable supplies parsers for Python, Go, Java, C#, Rust, PHP, Ruby, Kotlin, C and C++ (a `.h` file uses the C grammar). Direct import extraction is provided for JS/TS: it resolves project-local modules and TypeScript paths and ignores type-only imports. Discovery uses tracked and nonignored untracked Git files where available and a directory walk elsewhere, skipping dependency directories and minified files; `build`, `dist`, `coverage`, `target` and `vendor` are skipped only at the scanned root or beside a project manifest such as `package.json`.
|
|
1050
782
|
|
|
1051
783
|
## Project rules
|
|
1052
784
|
|
|
@@ -1062,26 +794,7 @@ Save team decisions in the `maintainability` section of `loadwise.config.json` a
|
|
|
1062
794
|
}
|
|
1063
795
|
```
|
|
1064
796
|
|
|
1065
|
-
`limits` sets the thresholds of `large-module`, `large-class` and `long-parameter-list
|
|
1066
|
-
|
|
1067
|
-
`dataAccess` restricts runtime imports of named packages, their subpaths, module aliases (`#models`, `@/db`) or project-local entry points (entries starting with `./`) to the project-relative directories or files in `allowIn`. Local entries match the resolved file, so `./store` and `./store/index.ts` are different targets. `import type`, `export type` and, outside `verbatimModuleSyntax` projects, all-inline-`type` specifier lists are erased and not reported. Both `modules` and `allowIn` are required and nonempty. Findings are contract violations and fail the default `--fail-on contract`. Resolution is syntactic per file, with no type checker, so an ambient `declare module` does not count as a local file.
|
|
1068
|
-
|
|
1069
|
-
Paths use project-relative directory or file names. Directory boundaries match complete segments. The longest matching filename suffix wins. With no configuration, each project keeps its own folder conventions. Discovery uses tracked and nonignored untracked Git files where available and a directory walk elsewhere. Dependency directories and minified files are skipped. `build`, `dist`, `coverage`, `target` and `vendor` are skipped as build output only at the scanned root or beside a project manifest such as `package.json`; a source folder with one of those names, such as `src/build/`, is scanned. Use explicit exclusions for other checked-in vendor code.
|
|
1070
|
-
|
|
1071
|
-
## Inline fixes
|
|
1072
|
-
|
|
1073
|
-
Findings with a safe rewrite carry it as `fix = { changes: [{ file, line, before, after }], note? }` in `--json` output, and the text output prints it as a diff.
|
|
1074
|
-
|
|
1075
|
-
```sh
|
|
1076
|
-
npx loadwise maint . --fix # asks y/n/a/q for each fix; needs a terminal
|
|
1077
|
-
npx loadwise maint . --fix --yes # applies every fix without asking
|
|
1078
|
-
```
|
|
1079
|
-
|
|
1080
|
-
`--fix` is refused with `--json` or `--graph`, and `--yes` alone is refused. Without a terminal, `--fix` requires `--yes`. A fix applies only where the original lines still exist. One that an earlier fix made stale is skipped and reappears, rebuilt, on the next run. Review the diff and run your tests afterwards.
|
|
1081
|
-
|
|
1082
|
-
The rules with an automatic rewrite are `deep-control-flow`, `high-branch-complexity`, `duplicate-implementation` and `dependency-cycle`. Each rule page describes its rewrite.
|
|
1083
|
-
|
|
1084
|
-
Other rules have no automatic rewrite.
|
|
797
|
+
`limits` sets the thresholds of `large-module`, `large-class` and `long-parameter-list` (positive integers; the values shown are the defaults). `dataAccess` restricts runtime imports of named packages, their subpaths, module aliases (`#models`, `@/db`) or project-local entry points (starting with `./`, matched by resolved file) to the paths in `allowIn`; both lists are required and nonempty, type-only imports are not reported, and findings are contract violations. Paths are project-relative, directory boundaries match complete segments, and the longest matching filename suffix wins.
|
|
1085
798
|
|
|
1086
799
|
## A module graph in any language
|
|
1087
800
|
|
|
@@ -1098,50 +811,11 @@ Other rules have no automatic rewrite.
|
|
|
1098
811
|
npx loadwise maint . --graph modules.json --config policy.json
|
|
1099
812
|
```
|
|
1100
813
|
|
|
1101
|
-
List each project-relative module once. Edges use one-based source coordinates
|
|
1102
|
-
|
|
1103
|
-
## CI and design review
|
|
1104
|
-
|
|
1105
|
-
Source checks count lower-priority findings separately. Use `--include-contextual` to display them with a reason. The JSON field `contextualFindingCount` is the additional count in the default view and a subset of `findings` in the expanded view. `--fail-on all` applies to displayed findings. Explicit folder and query contracts always remain visible.
|
|
1106
|
-
|
|
1107
|
-
Context includes documented independent test oracles, before/after source snapshots with a corresponding live file, marked generated code, certain flat data mappings, and flat lists of optional literal messages selected by simple field checks. Two ordinary implementations still form a default duplicate finding even when an archive or test oracle also contains a copy. A Nest module cycle can receive context when every internal eager edge is used solely in an explicit module `forwardRef` callback. A cycle supplied through graph input has no such source evidence.
|
|
1108
|
-
|
|
1109
|
-
The default `--fail-on contract` exits 1 for a declared folder, data-access or query contract violation. Design advisories remain visible and exit 0 on their own. Use `--fail-on all` to fail on any finding. Invalid configurations, a non-JavaScript file a native parser cannot read and missing required parser binaries exit 2. A JavaScript or TypeScript file that does not parse is skipped, named in a stderr note and in `skippedFiles` in `--json` output, and the run exits 2.
|
|
1110
|
-
|
|
1111
|
-
DRY candidates can represent intentional copies between isolated modules. Deep nesting can accurately reflect a protocol. Use the reported locations to decide whether extracting a function, changing a dependency or retaining the current implementation makes the next change easier. YAGNI, Tell Don't Ask, the Law of Demeter and CUPID depend on domain knowledge. Fluent call chains and unused extension points alone do not establish a violation. [CUPID and the properties of good code](https://dannorth.net/cupid-for-joyful-coding/)
|
|
1112
|
-
|
|
1113
|
-
## Apply fixes by id
|
|
1114
|
-
|
|
1115
|
-
Every finding in `--json` output has a stable `id` (also shown as `#id` in text output), `fixable`, and `fix` when a rewrite exists. The id hashes the rule, the file and the flagged line's text, so it survives edits above the finding.
|
|
1116
|
-
|
|
1117
|
-
```sh
|
|
1118
|
-
npx loadwise maint . --fix --only <id>[,<id>...] [--json]
|
|
1119
|
-
```
|
|
1120
|
-
|
|
1121
|
-
`--only` applies exactly those fixes with no prompt and no terminal. `--json` prints `{ applied, alreadyApplied, failed }`. An id whose change an earlier id in the same run already made is reported in `alreadyApplied`; an unknown id, a finding without a fix or a stale fix is in `failed` and the exit code is 2.
|
|
1122
|
-
|
|
1123
|
-
To dismiss a false positive, put `// loadwise-reviewed <rule-id> -- <specific reason>` on the line above it (line 1 itself for a finding about a whole file, such as `large-module`). The finding becomes contextual with that reason. Only a real line comment counts, and declared contracts (`file-placement`, `folder-boundary`, `data-access-boundary`, `query-mutates-state`) cannot be dismissed this way.
|
|
1124
|
-
|
|
1125
|
-
## Changed lines
|
|
1126
|
-
|
|
1127
|
-
```sh
|
|
1128
|
-
npx loadwise maint --staged .
|
|
1129
|
-
npx loadwise maint --changed-since <git-ref> .
|
|
1130
|
-
```
|
|
1131
|
-
|
|
1132
|
-
`--staged` reports only findings on lines added or changed in `git diff --cached`; `--changed-since <git-ref>` does the same for the working tree against that ref. A JS/TS function-level finding (`high-branch-complexity`, `deep-control-flow`) is kept when a changed line falls anywhere inside its function. In other supported languages, deep nesting is reported when its flagged line changes. Text output is one block per finding (`path:line [rule-id #id] message`, then a `fix:` command when a rewrite exists and a `dismiss:` comment for a reviewable JS/TS finding), ending with `N new finding(s) in changed lines.`. `--json` works too, with the same shape filtered. Changed files in any supported source language are checked. With `--changed-since`, untracked source files count as entirely new. When no supported source changed, text output is empty and the checker exits 0 before loading TypeScript. In these modes `--fail-on` defaults to `all`, so the exit code is 1 whenever a finding remains.
|
|
1133
|
-
|
|
1134
|
-
Only the changed files are analysed, while imports still resolve through the whole project. When as many files changed as the full scan's parallel threshold (600), the full scan runs instead and its findings are filtered to the changed lines, so every rule applies. Otherwise rules that need every file are limited: `duplicate-implementation` is skipped and `dependency-cycle` only sees cycles made of changed files' imports. Boundary and placement rules still run. Analysis reads working-tree files, so a file with unstaged edits can report shifted lines.
|
|
1135
|
-
|
|
1136
|
-
## Impact levels
|
|
1137
|
-
|
|
1138
|
-
The levels and the `--min-impact` flag work as described under the performance checker's impact levels.
|
|
814
|
+
List each project-relative module once. Edges use one-based source coordinates; set `"kind": "deferred"` for an edge that loads lazily. Graph mode operates entirely on the supplied inventory and edges, for a graph from a compiler, build system or dependency extractor.
|
|
1139
815
|
|
|
1140
816
|
# Security checker
|
|
1141
817
|
|
|
1142
|
-
`loadwise sec` reports code paths where input or missing scope can expose data
|
|
1143
|
-
|
|
1144
|
-
## Run it
|
|
818
|
+
`loadwise sec` reports code paths where input or missing scope can expose data. Findings are review prompts with a location, a rule ID, an impact level, a generic fix example and, where it is safe, a source-based fix.
|
|
1145
819
|
|
|
1146
820
|
```sh
|
|
1147
821
|
npx loadwise sec # tsconfig.json or jsconfig.json in the current folder
|
|
@@ -1152,7 +826,7 @@ npx loadwise sec deps --online # known-vulnerable packages in the lockfil
|
|
|
1152
826
|
npx loadwise sec polyglot src/ # ast-grep rules for Python, Go, Java, C#, Rust
|
|
1153
827
|
```
|
|
1154
828
|
|
|
1155
|
-
It accepts the source-check flags of `loadwise perf`, including `--format`, `--min-impact`, `--baseline`, `--write-baseline`, `--loadwise-config`, `--workspace`, `--policy`, `--json`, `--include-contextual`, `--ignore`, `--fail-on`, `--fix` with `--yes` or `--only` and `--no-comments` or `--no-format`, `--staged` and `--changed-since`.
|
|
829
|
+
It accepts the source-check flags of `loadwise perf`, including `--format`, `--min-impact`, `--baseline`, `--write-baseline`, `--loadwise-config`, `--workspace`, `--policy`, `--json`, `--include-contextual`, `--ignore`, `--fail-on`, `--fix` with `--yes` or `--only` and `--no-comments` or `--no-format`, `--staged` and `--changed-since`. `--engine auto` (the default) and `--engine js` both run TypeScript 6, because the native engine finds less; `--engine native` (alias `--native`) prints a note that cross-file taint through JavaScript constructor functions and rate-limit detection are reduced. Rules that need a package's types stay silent until it is installed. Test, fixture, mock, example and story files are contextual (`Test or example source.`). `--fail-on contract` enforces no security rule by default. `--fix --yes` leaves ValidationPipe whitelisting for individual review because it can strip undecorated DTO properties.
|
|
1156
830
|
|
|
1157
831
|
## Rules
|
|
1158
832
|
|
|
@@ -1235,17 +909,11 @@ It accepts the source-check flags of `loadwise perf`, including `--format`, `--m
|
|
|
1235
909
|
|
|
1236
910
|
<!-- loadwise:rules:end -->
|
|
1237
911
|
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
The first six rules read project files rather than TypeScript: `loadwise sec -p <tsconfig>` scans the project folder (not explicit source files) with `git ls-files`, so ignored files are skipped; outside a git repository it walks the folder and never opens `.env*` files. `.env.example`, `.env.sample` and `.env.template` are checked for token formats only. Placeholder values (`changeme`, `example`, `your-...`, `${...}`, test or dummy values) and default credentials for a local service are not reported or are contextual. Dockerfile checks follow multi-stage builds: only the final stage matters for `dockerfile-runs-as-root`.
|
|
1241
|
-
|
|
1242
|
-
These rules moved from the performance checker with the same ids, so existing `// loadwise-reviewed` comments and `--ignore` flags keep working; `loadwise perf --ignore` still accepts them.
|
|
1243
|
-
|
|
1244
|
-
Example: `pool.query('SELECT * FROM orders ORDER BY ' + req.query.sort)` reports `pg-dynamic-query-text`; `pool.query('SELECT * FROM orders WHERE id = $1', [id])` does not.
|
|
912
|
+
`committed-secret`, `compose-hardcoded-secret` and the `dockerfile-` rules read project files rather than TypeScript: `loadwise sec -p <tsconfig>` scans the project folder (not explicit source files) with `git ls-files`, so ignored files are skipped; outside a git repository it walks the folder and never opens `.env*` files. `.env.example`, `.env.sample` and `.env.template` are checked for token formats only, and placeholder values (`changeme`, `example`, `your-...`, `${...}`, test or dummy values) and default credentials for a local service are not reported or are contextual. Rules that moved from the performance checker kept their ids, and `loadwise perf --ignore` still accepts them.
|
|
1245
913
|
|
|
1246
914
|
## Polyglot source checks
|
|
1247
915
|
|
|
1248
|
-
`npx loadwise sec polyglot src/` accepts directories or individual `.py`, `.go`, `.java`, `.cs` and `.rs` files
|
|
916
|
+
`npx loadwise sec polyglot src/` accepts directories or individual `.py`, `.go`, `.java`, `.cs` and `.rs` files and needs the optional ast-grep binary. These are syntactic patterns without taint tracking: confirm that untrusted input can reach the call. They are not `--ignore` rule ids of the TypeScript source checks.
|
|
1249
917
|
|
|
1250
918
|
<!-- loadwise:rules:start checker=security group=polyglot-source-checks -->
|
|
1251
919
|
|
|
@@ -1267,9 +935,7 @@ Example: `pool.query('SELECT * FROM orders ORDER BY ' + req.query.sort)` reports
|
|
|
1267
935
|
|
|
1268
936
|
## Dependency checks
|
|
1269
937
|
|
|
1270
|
-
`loadwise sec deps --online [directory]` reads `package-lock.json` (lockfile version 2 or 3), `pnpm-lock.yaml` or `yarn.lock` (version 1 or Berry) from the directory or the nearest parent that has one, and asks the [OSV database](https://osv.dev) (which includes the GitHub Advisory Database) about every pinned package version. It sends package names and versions and nothing else. Answers are cached for 24 hours in the `loadwise` folder of the OS cache directory. It takes `--format text|json` (or `--json`), `--include-contextual`, `--ignore` and `--fail-on`. A network failure exits 2 rather than passing.
|
|
1271
|
-
|
|
1272
|
-
The network is opt-in: `loadwise sec --online` and `loadwise check --online` add these findings to their security report, and without `--online` they print one note that dependency checks were skipped.
|
|
938
|
+
`loadwise sec deps --online [directory]` reads `package-lock.json` (lockfile version 2 or 3), `pnpm-lock.yaml` or `yarn.lock` (version 1 or Berry) from the directory or the nearest parent that has one, and asks the [OSV database](https://osv.dev) (which includes the GitHub Advisory Database) about every pinned package version. It sends package names and versions and nothing else. Answers are cached for 24 hours in the `loadwise` folder of the OS cache directory. It takes `--format text|json` (or `--json`), `--include-contextual`, `--ignore` and `--fail-on`. A network failure exits 2 rather than passing. The network is opt-in: `loadwise sec --online` and `loadwise check --online` add these findings to their security report, and without `--online` they print one note that dependency checks were skipped.
|
|
1273
939
|
|
|
1274
940
|
<!-- loadwise:rules:start checker=security group=dependency-checks -->
|
|
1275
941
|
|
|
@@ -1279,37 +945,20 @@ The network is opt-in: `loadwise sec --online` and `loadwise check --online` add
|
|
|
1279
945
|
|
|
1280
946
|
<!-- loadwise:rules:end -->
|
|
1281
947
|
|
|
1282
|
-
## Security impact levels
|
|
1283
|
-
|
|
1284
|
-
`--min-impact` sets the minimum level to report. Dependency findings use the advisory severity.
|
|
1285
|
-
|
|
1286
948
|
## Project-defined row scopes
|
|
1287
949
|
|
|
1288
|
-
Row-scope checks read `prismaScopes` and `drizzleScopes` from the `performance` section of `loadwise.config.json
|
|
1289
|
-
|
|
1290
|
-
Drizzle also supports configuring quoted properties such as `"org-id"` and accessing them with brackets. In Prisma's generated filters, `AND`, `OR` and `NOT` are logical operators. If a physical column uses one of these names, configure the Prisma property that maps to it.
|
|
1291
|
-
|
|
1292
|
-
`prismaScopes` maps each generated model to its own protected field and a named export from the project's trusted authorization module. With the supplied example, `db.invoice.findMany({ where: { organizationId: requireOrganization() } })` has the expected scope. Choose the names already used by the project. The scanner handles common reads, writes and upsert branches, and requires every alternative in an OR to preserve the scope. For dynamic or nested shapes it cannot establish, it emits `prisma-scope-unverified`. Proof requires strict null checks. With explicit source files and a policy, the CLI enables strict null checks for its analysis.
|
|
1293
|
-
|
|
1294
|
-
`drizzleScopes` names an exported table, its schema module, its scoped property and the trusted helper. For a direct executed query, `.where(eq(invoices.workspace_id, currentWorkspace()))` establishes the configured predicate in the example. Use the property exposed by the ORM. A project with `organizationId: text('org_id')` would configure `"field": "organizationId"`. Each table can use a different convention. A later `.where()` can replace the earlier condition. The rule checks the effective condition and can report `drizzle-scope-unverified` when a protected table appears in a recognized chain and scope, projection or write data needs review. Stored builders, prepared aliases, raw SQL and arbitrary helper-generated statements can fall outside this check.
|
|
1295
|
-
|
|
1296
|
-
The import boundary for database modules is a maintainability rule; configure it through the `dataAccess` field of the `maintainability` section in `loadwise.config.json`.
|
|
1297
|
-
|
|
1298
|
-
These checks assume the configured helper authenticates the caller and authorizes the returned scope. Middleware, injected or previously obtained clients, raw SQL, unrecognized query shapes and database row-level policies require separate verification. A clean run only describes the covered operations.
|
|
950
|
+
Row-scope checks read `prismaScopes` and `drizzleScopes` from the `performance` section of `loadwise.config.json` (see [Project-defined access policy](#project-defined-access-policy)) and start only when the project names the model or table, its scoped property and the trusted helper that supplies an authorized scalar; column names such as `tenantId` mean nothing on their own. `prismaScopes` maps each generated model to its protected field and a named export of the project's authorization module, so `db.invoice.findMany({ where: { organizationId: requireOrganization() } })` is scoped; proof requires strict null checks, which the CLI enables for explicit source files with a policy. `drizzleScopes` names an exported table, its schema module, its scoped property (the ORM property, not the column name) and the trusted helper. A later `.where()` replaces the earlier condition, and every OR alternative must keep the scope. If a physical column is named `AND`, `OR` or `NOT`, configure the Prisma property that maps to it; quoted Drizzle properties such as `"org-id"` work with bracket access. Shapes the scanner cannot establish are reported as `prisma-scope-unverified` or `drizzle-scope-unverified`. These checks assume the helper authenticates the caller; middleware, injected clients, raw SQL and database row-level policies need separate verification. The import boundary for database modules is the maintainability `dataAccess` setting.
|
|
1299
951
|
|
|
1300
952
|
# Accessibility checker
|
|
1301
953
|
|
|
1302
|
-
`loadwise a11y` finds markup that people using screen readers, keyboards or zoom cannot use
|
|
954
|
+
`loadwise a11y` finds markup that people using screen readers, keyboards or zoom cannot use. It reads JSX and inline Angular templates from the TypeScript program, and `.html`, `.htm`, `.vue` and `.svelte` files from the project folders, leaving out ignored folders, build output, minified and vendored files and the config's `ignore` paths. It shares the source check of `loadwise perf`. A project with no frontend sources (no JSX, HTML, Vue or Svelte files and no frontend package in any `package.json`) is skipped by `loadwise check` with a note; `loadwise a11y` on it reports 0 findings.
|
|
1303
955
|
|
|
1304
956
|
```sh
|
|
1305
957
|
npx loadwise a11y -p tsconfig.json # JSX, Angular templates and the project's markup files
|
|
1306
958
|
npx loadwise a11y src/index.html # explicit markup files
|
|
1307
|
-
npx loadwise a11y --staged # only findings on staged lines
|
|
1308
959
|
npx loadwise a11y --fix --only <id> # apply one generated fix
|
|
1309
960
|
```
|
|
1310
961
|
|
|
1311
|
-
`npx loadwise a11y --help` lists every flag. A `loadwise.config.json` `rules` or `overrides` entry for an accessibility rule applies here, and findings live in the `accessibility` section of the baseline file.
|
|
1312
|
-
|
|
1313
962
|
## Rules
|
|
1314
963
|
|
|
1315
964
|
<!-- loadwise:rules:start checker=accessibility group=rules -->
|
|
@@ -1328,17 +977,9 @@ npx loadwise a11y --fix --only <id> # apply one generated fix
|
|
|
1328
977
|
|
|
1329
978
|
<!-- loadwise:rules:end -->
|
|
1330
979
|
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
The levels and the `--min-impact` flag work as described under the performance checker's impact levels. `loadwise a11y` and the accessibility section of `loadwise check` use the impact levels in the rule index.
|
|
1334
|
-
|
|
1335
|
-
# Developing locally
|
|
1336
|
-
|
|
1337
|
-
Use Node.js 22.13+ for the development tools and run `npm ci --include=optional`. Open this repository folder as a trusted workspace in VS Code or Cursor and enable the recommended Prettier extension. Saving a supported file formats it with the repository settings.
|
|
1338
|
-
|
|
1339
|
-
Run `npm run format` to format files, `npm run lint` for correctness checks, or `npm run check` to verify formatting, lint and tests together.
|
|
980
|
+
# Verification and development
|
|
1340
981
|
|
|
1341
|
-
|
|
982
|
+
[PERFORMANCE.md](PERFORMANCE.md) has the scan-time and memory measurements, and the [corpus rule scorecard](bench/corpus/scorecard.md) the measured precision and recall per rule. To develop Loadwise itself, see [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
1342
983
|
|
|
1343
984
|
# License
|
|
1344
985
|
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "loadwise",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "
|
|
5
|
+
"description": "Pre-ship checks for TypeScript and JavaScript: N+1 queries and missing indexes, unsafe migrations, unhandled errors, React, Vue and Angular render bugs, security and accessibility, with reviewable fixes.",
|
|
6
6
|
"license": "Apache-2.0",
|
|
7
7
|
"author": "Ibrahim Hafez",
|
|
8
8
|
"repository": {
|
|
@@ -37,7 +37,22 @@
|
|
|
37
37
|
"security",
|
|
38
38
|
"cli",
|
|
39
39
|
"language-server",
|
|
40
|
-
"lsp"
|
|
40
|
+
"lsp",
|
|
41
|
+
"mongoose",
|
|
42
|
+
"sequelize",
|
|
43
|
+
"knex",
|
|
44
|
+
"kysely",
|
|
45
|
+
"mongodb",
|
|
46
|
+
"mysql",
|
|
47
|
+
"react",
|
|
48
|
+
"nextjs",
|
|
49
|
+
"vue",
|
|
50
|
+
"angular",
|
|
51
|
+
"migrations",
|
|
52
|
+
"sarif",
|
|
53
|
+
"mcp",
|
|
54
|
+
"github-action",
|
|
55
|
+
"eslint-alternative"
|
|
41
56
|
],
|
|
42
57
|
"bin": {
|
|
43
58
|
"loadwise": "bin/loadwise.js"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "loadwise",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"description": "Runs the project's local loadwise checkers on each file Claude edits and sends findings back with their fix commands.",
|
|
5
5
|
"author": { "name": "Ibrahim Hafez" },
|
|
6
6
|
"homepage": "https://github.com/IbrahimHafez1/loadwise#readme",
|