loadwise 0.5.1 → 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.
Files changed (132) hide show
  1. package/PERFORMANCE.md +31 -6
  2. package/README.md +580 -1024
  3. package/bin/loadwise.js +4 -0
  4. package/lib/accessibility/frontend-detect.js +2 -1
  5. package/lib/accessibility/rule-ids.js +12 -9
  6. package/{editor/accessibility-examples.cjs → lib/editor/accessibility-examples.js} +20 -21
  7. package/lib/editor/actions.js +117 -0
  8. package/{editor/apply-fix.cjs → lib/editor/apply-fix.js} +1 -6
  9. package/{editor/control-flow-comparison.cjs → lib/editor/control-flow-comparison.js} +1 -3
  10. package/lib/editor/diagnostics.js +365 -0
  11. package/lib/editor/dismissals.js +111 -0
  12. package/lib/editor/editor-document.js +99 -0
  13. package/{editor/finding-comparison.cjs → lib/editor/finding-comparison.js} +4 -7
  14. package/lib/editor/fix-edits.js +200 -0
  15. package/lib/editor/language-server.js +437 -0
  16. package/{editor/maintainability-examples.cjs → lib/editor/maintainability-examples.js} +1 -3
  17. package/{editor/perf-site-comparison.cjs → lib/editor/perf-site-comparison.js} +1 -3
  18. package/lib/editor/perf-watch.js +78 -0
  19. package/{editor/performance-examples.cjs → lib/editor/performance-examples.js} +129 -128
  20. package/{editor/reliability-examples.cjs → lib/editor/reliability-examples.js} +100 -41
  21. package/lib/editor/scan-session.js +334 -0
  22. package/{editor/security-examples.cjs → lib/editor/security-examples.js} +28 -32
  23. package/lib/editor/server-commands.js +232 -0
  24. package/{editor/source-example.cjs → lib/editor/source-example.js} +3 -5
  25. package/{editor/standalone-performance-examples.cjs → lib/editor/standalone-performance-examples.js} +349 -333
  26. package/lib/editor/types/dismissal.js +1 -0
  27. package/lib/editor/types/fix-example.js +1 -0
  28. package/lib/editor/types/source-document.js +1 -0
  29. package/lib/editor/workspace-files.js +78 -0
  30. package/lib/editor/workspace-paths.js +22 -0
  31. package/lib/maintainability/analyze-source.js +2 -0
  32. package/lib/maintainability/apply-fix.js +1 -1
  33. package/lib/maintainability/cli.js +1 -1
  34. package/lib/maintainability/examples.js +58 -41
  35. package/lib/maintainability/rule-ids.js +29 -14
  36. package/lib/maintainability/scan-changed.js +3 -0
  37. package/lib/maintainability/scan.js +13 -9
  38. package/lib/maintainability/tsconfig-strict.js +69 -0
  39. package/lib/maintainability/type-safety-hygiene.js +204 -0
  40. package/lib/performance/analyze.js +2 -0
  41. package/lib/performance/cli-arguments.js +0 -2
  42. package/lib/performance/cli-policy.js +17 -9
  43. package/lib/performance/cli-scan.js +10 -8
  44. package/lib/performance/cli.js +4 -23
  45. package/lib/performance/editor-signal.js +1 -1
  46. package/lib/performance/finding-text.js +3 -3
  47. package/lib/performance/fix-cli.js +1 -1
  48. package/lib/performance/frontend-perf.js +7 -0
  49. package/lib/performance/frontend-render-perf.js +200 -0
  50. package/lib/performance/llm-max-tokens.js +56 -0
  51. package/lib/performance/native.js +46 -26
  52. package/lib/performance/polyglot.js +22 -1
  53. package/lib/performance/pooling.js +38 -23
  54. package/lib/performance/projects.js +42 -21
  55. package/lib/performance/rule-ids.js +236 -222
  56. package/lib/performance/site-fixes/database.js +3 -1
  57. package/lib/performance/site-fixes/integrity.js +15 -1
  58. package/lib/performance/source-inputs.js +18 -6
  59. package/lib/performance/unscanned-javascript.js +66 -19
  60. package/lib/reliability/analyze.js +12 -0
  61. package/lib/reliability/child-process.js +106 -0
  62. package/lib/reliability/error-values.js +177 -0
  63. package/lib/reliability/pool-timeout.js +79 -0
  64. package/lib/reliability/react-bugs.js +602 -0
  65. package/lib/reliability/resource-leaks.js +3 -6
  66. package/lib/reliability/rule-ids.js +169 -127
  67. package/lib/reliability/switch-exhaustive.js +284 -0
  68. package/lib/reliability/uncaught-exception.js +223 -0
  69. package/lib/security/auth-crypto/rule-ids.js +3 -2
  70. package/lib/security/cli.js +6 -5
  71. package/lib/security/deps/rule-ids.js +1 -0
  72. package/lib/security/examples/auth-crypto.cjs +5 -4
  73. package/lib/security/examples/deps.cjs +1 -0
  74. package/lib/security/examples/exposure.cjs +55 -42
  75. package/lib/security/examples/files.cjs +1 -0
  76. package/lib/security/examples/injection.cjs +1 -0
  77. package/lib/security/examples/moved.cjs +5 -4
  78. package/lib/security/examples/request-forgery.cjs +1 -0
  79. package/lib/security/exposure/client-env.js +113 -0
  80. package/lib/security/exposure/frontend-security.js +12 -10
  81. package/lib/security/exposure/index.js +14 -3
  82. package/lib/security/exposure/jsx-url.js +267 -0
  83. package/lib/security/exposure/next-image-config.js +34 -0
  84. package/lib/security/exposure/package-manifest.js +45 -0
  85. package/lib/security/exposure/react-version.js +45 -0
  86. package/lib/security/exposure/rule-ids.js +16 -12
  87. package/lib/security/files/index.js +1 -1
  88. package/lib/security/files/rule-ids.js +1 -0
  89. package/lib/security/injection/code.js +24 -10
  90. package/lib/security/injection/command.js +81 -28
  91. package/lib/security/injection/nosql.js +109 -22
  92. package/lib/security/injection/redos.js +152 -308
  93. package/lib/security/injection/regex-pattern.js +290 -0
  94. package/lib/security/injection/regex.js +30 -11
  95. package/lib/security/injection/rule-ids.js +2 -1
  96. package/lib/security/injection/shared.js +19 -1
  97. package/lib/security/injection/sql.js +83 -2
  98. package/lib/security/request-forgery/rule-ids.js +1 -0
  99. package/lib/security/rule-descriptions.js +36 -32
  100. package/lib/security/rule-ids.js +74 -67
  101. package/lib/security/taint/filename-guard.js +3 -1
  102. package/lib/security/taint/guards.js +84 -10
  103. package/lib/security/taint/index.js +124 -13
  104. package/lib/security/taint/propagate.js +10 -7
  105. package/lib/security/taint/sanitizers.js +7 -3
  106. package/lib/security/taint/sources.js +6 -3
  107. package/lib/security/taint/summaries.js +13 -1
  108. package/lib/security/taint/url-parts.js +14 -5
  109. package/lib/shared/agent-session.js +2 -2
  110. package/lib/shared/check.js +9 -6
  111. package/lib/shared/explain.js +5 -5
  112. package/lib/shared/fix-convergence.js +1 -1
  113. package/lib/shared/formats/finding-location.js +6 -2
  114. package/lib/shared/formats/sarif.js +3 -3
  115. package/lib/shared/heap-limit.js +6 -0
  116. package/lib/shared/pillars.js +7 -7
  117. package/lib/shared/rule-docs.js +12 -0
  118. package/lib/shared/scan-cache.js +0 -1
  119. package/lib/shared/workspaces.js +31 -9
  120. package/package.json +25 -17
  121. package/plugin/.claude-plugin/plugin.json +1 -1
  122. package/schema/loadwise.config.schema.json +44 -0
  123. package/editor/README.md +0 -47
  124. package/examples/redis-keys.otlp.json +0 -22
  125. package/lib/maintainability/notify-editor.js +0 -1
  126. package/lib/performance/editor-report.js +0 -191
  127. package/lib/performance/editor-setup.js +0 -189
  128. package/lib/performance/editor-watch-supervisor.js +0 -104
  129. package/lib/performance/editor-watch.js +0 -193
  130. package/lib/performance/notify-editor.js +0 -1
  131. package/lib/performance/recursive-watch.js +0 -181
  132. /package/lib/{performance/types/editor-report.js → editor/types/comparison.js} +0 -0
package/README.md CHANGED
@@ -2,15 +2,15 @@
2
2
 
3
3
  [![npm](https://img.shields.io/npm/v/loadwise)](https://www.npmjs.com/package/loadwise) [![check](https://github.com/IbrahimHafez1/loadwise/actions/workflows/check.yml/badge.svg)](https://github.com/IbrahimHafez1/loadwise/actions/workflows/check.yml) [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/IbrahimHafez1/loadwise/badge)](https://scorecard.dev/viewer/?uri=github.com/IbrahimHafez1/loadwise) [![license](https://img.shields.io/npm/l/loadwise?cacheSeconds=3600)](LICENSE)
4
4
 
5
- Loadwise checks a backend project before it ships. One CLI runs five checkers:
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` reports actionable findings across Performance, Reliability, Maintainability, Security, and Accessibility; see the [corpus rule scorecard](bench/corpus/scorecard.md) for measured precision and recall across real-world open-source backends.
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
 
@@ -38,11 +38,11 @@ By default `loadwise check` reports actionable findings across Performance, Reli
38
38
 
39
39
  **With an AI coding agent**, say **“Run Loadwise”** in your project chat. The agent can run the installed CLI directly. It should check the findings against the code, explain what it would fix or leave alone and why, and let you choose before making edits. [Active-agent workflow and optional MCP setup](#using-loadwise-with-an-active-coding-agent)
40
40
 
41
- **Working manually**, run `npx loadwise check` to see recommendations or `npx loadwise fix --yes` to apply eligible fixes. In VS Code or Cursor, editor diagnostics show findings on hover. [Editor setup](#editor)
41
+ **Working manually**, run `npx loadwise check` to see recommendations or `npx loadwise fix --yes` to apply eligible fixes. In any editor with a language server client, `loadwise lsp` shows findings as diagnostics with hovers and fixes. [Editor setup](#editor-language-server)
42
42
 
43
43
  ### Try a finding and a fix
44
44
 
45
- From the directory where you installed Loadwise, copy the bundled example to a disposable file and scan it. The copy command refuses to overwrite an existing file.
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
- `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.
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
- Manual findings have no generated edit. With `--all`, inspect the resulting diff and run the project's tests, especially for schema changes and edits that alter application behavior.
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
- 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 in the project the edits are written as generated, with a note. `--no-comments` and `--no-format` turn these off; the per-checker `--fix` takes the same flags. `loadwise fix` also supports `--dry-run` (preview unified diffs without writing), repeatable `--rule <rule-id>` filtering, and `--no-verify-types` (skip Layer-2 semantic type checking on TypeScript projects).
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
- ### Project-specific fixes
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
- The default `fix --yes` can simplify nested conditions that choose the same status string. It preserves evaluation order and short-circuiting. Two other transformations need individual review: making a locally used constant private can affect consumers outside the scan, and sharing a private helper between sibling TypeScript modules changes the files included in the build. Inspect those diffs before applying them by finding ID.
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
- The unused-module check considers literal Node commands in operator documentation and corroborated container entry points. Running a script establishes that the file is used; its unused exports can still be reported. The performance checker also recognizes supported Drizzle helpers that already receive a batch of keys.
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
- For private TypeScript applications that control their consumers, Loadwise includes a compiler-backed recipe for unused type exports:
97
+ ### Fixes
102
98
 
103
99
  ```bash
104
- npx loadwise fix --all --recipe verified-private-types
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
- This applies the usual generated fixes and also considers making locally used type declarations private. It checks the proposed type edits against the application with the bundled TypeScript compiler before offering them. The extra compilation takes time, and can verify only consumers included in the project. Omit this recipe when other repositories import your types.
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
- If your project has a policy for a manual finding, you can encode it once in a local CommonJS recipe and share the file with your team. Run it alongside the built-in fixes for the selected checkers:
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
- ```bash
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
- For example, suppose a failed cache refresh in one maintenance script must fail the job. This recipe handles an empty catch at that specific site:
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
- 'maint/swallowed-error'({ finding, source }) {
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 use `perf`, `rel`, `maint`, `sec`, or `a11y` followed by the rule ID from the report. A handler receives the finding and the source file text. Return exact, whole-line replacements in that file or return `null` to leave the site manual. Loadwise tries recipes only where it has no built-in fix. It validates the proposed edits together before writing. Recipe files execute as local JavaScript, so run only recipes you trust and keep handlers free of side effects.
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
- To apply automatic fixes across your project, run `npx loadwise fix --yes` from its root. Performance and security share a type-check when both are selected. The command lists manual changes and findings that need individual review by location and ID. A fix that touches lines reserved for review also requires individual review. Loadwise checks the remaining edits together before writing and exits 2 if a selected checker fails or is skipped, source lines have changed, or automatic fixes conflict. A successful application exits 0 even when manual findings remain. Review the diff, run your tests, and use `npx loadwise check` to see what remains.
131
+ ### Per-checker fixes and dismissals
135
132
 
136
- `check` accepts these flags and passes them to every selected checker:
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
- - `--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`.
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.
136
+
137
+ ```ts
138
+ // loadwise-reviewed pg-query-in-loop -- Each iteration measures a separate query-plan sample.
139
+ await client.query(statement);
140
+ ```
144
141
 
145
- The performance, reliability, security and accessibility 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; `--workspace <name|path>` (repeatable) limits every checker to some packages. For a standalone package with a `package.json` and JavaScript sources only, `check` and `fix` infer source files using the project inventory without writing a config. A mixed JavaScript/TypeScript project still needs a source config. For a JavaScript file without a project config, use `npx loadwise perf path/to/file.js` and `npx loadwise sec path/to/file.js`. For Python, Go, Java, C# or Rust performance checks, run `npx loadwise perf polyglot src` explicitly, and `npx loadwise rel polyglot src` for the reliability patterns. The security checker can still scan Dockerfiles, Compose files and tracked environment files. 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>`, that applies its fixes.
142
+ ### Changed lines
146
143
 
147
- Exit codes: **0** passed, **1** a checker met its exit threshold, **2** invalid input or configuration in any checker, or a scan that skipped a file (see below).
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
- A scan skips a JavaScript or TypeScript file that does not parse, or whose analysis fails, and still reports the findings of every other file. Each skipped file is named in a note on stderr and in a `skippedFiles` array of `{ file, reason }` in `--json` output, and the run exits 2, also with `--fix` and `--write-baseline`. 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.
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
- 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` prints one line naming it and the limit it had, tells you to raise it with `NODE_OPTIONS=--max-old-space-size=<megabytes>`, and exits 2. When a checker exits 2 because it skipped files, `check` keeps its findings and `skippedFiles` in `--json` output, marks its SARIF run as not successful and emits a GitHub warning for each skipped file. A checker that produced no result is named on stderr and `check` exits 2. The native engine (`--engine native`) uses much less memory on most projects; [PERFORMANCE.md](PERFORMANCE.md) has the measurements.
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" }` is accepted for future rule options; no rule has options yet.
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`, `perf`, `rel` and `maint`) adds a rule to `"off"` for one run and beats the config.
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. A check lets the agent inspect every scoped finding, earlier edit, caller and test. 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.
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
- 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` or `reliability`. 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.
228
-
229
- For persistent project instructions, or to have a future agent review fixes you run manually in a terminal, use the optional setup command. It updates the managed section of `AGENTS.md`, imports it from `CLAUDE.md` and enables history for manual CLI fixes too.
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.
230
239
 
231
- ```sh
232
- npx loadwise agent init
233
- ```
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.
234
241
 
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. The second 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.
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 same checker names as the fix request:
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, then run:
257
-
258
- ```bash
259
- npx loadwise agent mcp --print-config
260
- ```
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.
261
258
 
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.
263
-
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. The optional `loadwise agent pending` command and MCP tool `loadwise_list_reports` list saved reports for that project.
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 editor diagnostics enabled, hover over a finding to see its recommendation. Findings that require judgment remain available for manual review. [Editor setup](#editor)
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 for the corresponding checker; 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.
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
 
@@ -290,311 +279,304 @@ npx loadwise agent init --hook off # removes only this block
290
279
 
291
280
  The hook runs `loadwise check --staged` from the project folder, so every tool that commits through git sees findings from the selected checkers on the staged lines. It writes a marked block into the hooks folder (honouring `core.hooksPath`) or into `.husky/pre-commit` when `.husky/` exists, appends to a hook you already have, and rerunning it replaces only its own block, including blocks written by earlier releases. With lefthook it edits nothing and prints the command to add. `git commit --no-verify` skips the hook.
292
281
 
293
- ## Editor
294
-
295
- Set up the editor task once from the project root.
282
+ ## Editor (language server)
296
283
 
297
- ```sh
298
- npx loadwise perf editor init
299
- ```
300
-
301
- Commit the generated `.vscode/tasks.json`. Open the trusted folder in VS Code or Cursor and allow automatic tasks once; the watcher then starts on every folder open (reopen the folder if it was already open during setup). **Tasks: Manage Automatic Tasks** controls the workspace's choice. Findings from the performance, reliability, maintainability and accessibility checkers appear in **View > Problems**. This works across supported source languages, including mixed-language projects, and needs Node.js 22+ on PATH and this package under `node_modules`.
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
- Saving a file or completing a source scan from the project terminal refreshes the running watcher. The editor uses its configured project and rules even when the terminal command uses different flags, and a running watcher picks up package reinstalls. The default scan uses a root `tsconfig.json` or `jsconfig.json`, or explicit JS/TS files discovered by the watcher; append `-p` and a relative path to the task's arguments (it runs `perf editor watch [-p tsconfig.json]`) to use another config.
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
- Hover over an underline to read the finding. The first line shows a source-based rewrite, an illustrative example or a review action. The hover retains the original finding and, where applicable, the code comparison.
306
-
307
- The [editor extension](editor/README.md) is not published yet; a language server for every editor is planned. Built from source (`python editor/package-vsix.py`), it adds syntax-highlighted hover examples, related-location links and fix actions in VS Code or Cursor:
308
-
309
- - Each fixable line shows **Apply fix** and **Dismiss** CodeLens buttons, the hover has the same two links, and the Quick Fix menu offers the same actions.
310
- - The shortcuts are the same on every OS: **Ctrl+Alt+.** applies the fix on the cursor line, **Ctrl+Alt+Shift+.** applies all fixes in the file, and **Ctrl+Alt+,** dismisses the finding on the cursor line.
311
- - **Loadwise: Apply all fixes in this file** (also on save as `source.fixAll.loadwise`) applies every fix in one undoable edit.
312
- - A finding, or a rule in one file, can be dismissed and restored with **Show dismissed findings**. `loadwise.severity` shows all findings at one level.
288
+ ```lua
289
+ vim.lsp.config('loadwise', {
290
+ cmd = { 'npx', 'loadwise', 'lsp', '--stdio' },
291
+ filetypes = { 'javascript', 'javascriptreact', 'typescript', 'typescriptreact', 'python' },
292
+ root_markers = { 'loadwise.config.json', 'tsconfig.json', 'jsconfig.json', 'package.json', '.git' },
293
+ init_options = { loadwise = { severity = 'default' } },
294
+ })
295
+ vim.lsp.enable('loadwise')
296
+ ```
313
297
 
314
- # Performance checker
298
+ **Helix** (`languages.toml`), added beside each language's own server:
315
299
 
316
- `loadwise perf` finds repeated backend work before deployment or in a recorded request. It checks source code, OpenTelemetry traces and executed database plans. Findings include a location or trace identifier, a rule ID, and a suggested change to evaluate.
300
+ ```toml
301
+ [language-server.loadwise]
302
+ command = "npx"
303
+ args = ["loadwise", "lsp", "--stdio"]
317
304
 
318
- ## What you get
305
+ [[language]]
306
+ name = "typescript"
307
+ language-servers = ["typescript-language-server", "loadwise"]
308
+ ```
319
309
 
320
- | Capability | Command | Needs a database |
321
- | ------------------------- | ---------------------------------------- | ---------------- |
322
- | Source and ORM checks | `loadwise perf -p tsconfig.json` | No |
323
- | Migration safety | `loadwise rel migrations` | No |
324
- | API contract safety | `loadwise rel contracts` | No |
325
- | Schema-aware index checks | `loadwise perf --schema snap.json` | No (snapshot) |
326
- | Live database inspection | `loadwise perf db` | Yes, read-only |
327
- | Traces and executed plans | `traces trace.json`, `plan explain.json` | No |
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 `"..."`.
328
311
 
329
- Text findings carry a stable `#id`, a **Fix** diff where one applies and, for loops and repeated spans, an **Impact:** line. Impact always says which side is measured and which is estimated.
312
+ **Sublime Text** with the LSP package (**Preferences > Package Settings > LSP > Settings**):
330
313
 
331
- ```text
332
- 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.
333
- Fix (examples/slow.ts:7):
334
- - const names = visible.map(order => customers.find(customer => customer.id === order.customerId)?.name ?? 'Unknown');
335
- + const customersById = new Map(customers.map((customer) => [customer.id, customer] as const).reverse());
336
- + const names = visible.map(order => customersById.get(order.customerId)?.name ?? 'Unknown');
314
+ ```json
315
+ {
316
+ "clients": {
317
+ "loadwise": {
318
+ "enabled": true,
319
+ "command": ["npx", "loadwise", "lsp", "--stdio"],
320
+ "selector": "source.js | source.jsx | source.ts | source.tsx | source.python"
321
+ }
322
+ }
323
+ }
337
324
  ```
338
325
 
339
- ```text
340
- 00000000000000000000000000000001 parent 0000000000000010 [repeated-db-span] 5 sibling database calls share one operation signature, one round trip each. Batch them into one statement such as WHERE id = ANY($1), or reuse a shared result, if behavior allows it.
341
- Impact: 40 ms measured -> ~8 ms estimated; method: OTLP start/end times; after assumes one batched operation costs as much as the slowest span.
326
+ **Emacs** with eglot, which runs one server per buffer, so Loadwise takes the place of another server for these modes:
327
+
328
+ ```elisp
329
+ (with-eval-after-load 'eglot
330
+ (add-to-list 'eglot-server-programs
331
+ '((js-mode js-ts-mode typescript-ts-mode tsx-ts-mode python-mode python-ts-mode)
332
+ . ("npx" "loadwise" "lsp" "--stdio"))))
342
333
  ```
343
334
 
344
- The second sample is `examples/repeated-db.otlp.json` with span timings added. A `~` marks an estimate. Loop findings (`*-query-in-loop`) show a round-trip model, and a measured figure only when `--schema` supplies a snapshot with a measured round trip. An Impact line in milliseconds is never printed without a measurement behind it.
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.
345
336
 
346
- ## Start here
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.
347
338
 
348
- 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.
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.
349
340
 
350
- ```sh
351
- npx loadwise perf node_modules/loadwise/examples/slow.ts
352
- npx loadwise perf node_modules/loadwise/examples/indexed.ts
353
- ```
341
+ | Command | Action |
342
+ | --------------------------- | ---------------------------------------------------------- |
343
+ | `loadwise.scan` | Rescan every workspace folder now |
344
+ | `loadwise.applyFix` | Apply one fix (from a code action or code lens) |
345
+ | `loadwise.applyAllFixes` | Apply every eligible fix in a file (its URI as argument) |
346
+ | `loadwise.dismiss` | Dismiss a finding or a rule in a file |
347
+ | `loadwise.showDismissed` | List dismissed findings, with Restore and Restore all |
348
+ | `loadwise.restoreDismissed` | Restore the given dismissal, or every one without argument |
354
349
 
355
- 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.
350
+ Settings go in the client's `initializationOptions` or its `loadwise` configuration section (per workspace folder when the editor supports it):
356
351
 
357
- 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`.
352
+ | Setting | Default | Effect |
353
+ | ---------- | ----------- | ----------------------------------------------------------------------------- |
354
+ | `enabled` | `true` | Show diagnostics for the folder |
355
+ | `project` | `""` | TypeScript or JavaScript project config, relative to the folder |
356
+ | `cli` | `""` | Absolute path to another `bin/loadwise.js`, such as a development build |
357
+ | `severity` | `"default"` | `error`, `warning`, `information` or `hint` shows every finding at that level |
358
+ | `codeLens` | `true` | Show the Apply fix and Dismiss code lenses |
358
359
 
359
- 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`.
360
+ # Performance checker
360
361
 
361
- | Input | Command after `npx loadwise perf` | Coverage |
362
- | --------------------------------------- | ------------------------------------------------------------------ | ----------------------------------------------------------------------------------- |
363
- | JavaScript or TypeScript | `-p tsconfig.json`, `--watch -p tsconfig.json` or `src/handler.ts` | Typed database calls, collection algorithms, connections and synchronous Node APIs. |
364
- | Python, Go, Java, C#, Rust | `polyglot src` | Five narrowly scoped source patterns powered by a Rust binary. |
365
- | OTLP/JSON from any application language | `traces request.otlp.json --threshold 5` | Repeated SQL or NoSQL operations, duplicate lookups and Redis/Valkey commands. |
366
- | Executed PostgreSQL or MongoDB plan | `plan explain.json` | Inefficient scans, disk sorts and deep pagination at individual plan stages. |
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.
367
363
 
368
- ## Source checks
364
+ Sample text finding with its fix diff:
369
365
 
370
- Run in the directory containing `tsconfig.json` or `jsconfig.json`, pass `-p path/to/config.json`, or give explicit JS/TS files. A project check scans the config's input files and follows project references. Declaration files supply types. A standalone file check uses ES2022 and NodeNext compiler defaults. Use a project config for aliases, custom libraries and JS projects with `allowJs`. When a config leaves JavaScript files in its folder out because `allowJs` is off, a note names them.
371
-
372
- | JS/TS rule | Trigger and review |
373
- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
374
- | <a id="pg-query-in-loop"></a><a id="prisma-query-in-loop"></a>`pg-query-in-loop`, `prisma-query-in-loop` | Per-item queries. Consider a parameterized set query, relation load or bulk write if ordering and transaction behavior permit it. Prisma can already batch compatible `findUnique` calls. |
375
- | <a id="pg-count-materialization"></a><a id="prisma-count-materialization"></a>`pg-count-materialization`, `prisma-count-materialization` | Counting an immediately loaded result. Use a database count with equivalent predicates and handle its return type. |
376
- | <a id="pg-first-materialization"></a><a id="prisma-first-materialization"></a>`pg-first-materialization`, `prisma-first-materialization` | Reading only index zero from an unbounded result. Preserve ordering and empty-result behavior when limiting the query. |
377
- | <a id="pg-filter-materialization"></a><a id="prisma-filter-materialization"></a>`pg-filter-materialization`, `prisma-filter-materialization` | Applying a literal equality filter in JS after loading an unbounded result. Check database collation and null semantics before moving the predicate. |
378
- | <a id="pg-top-k-materialization"></a><a id="prisma-top-k-materialization"></a>`pg-top-k-materialization`, `prisma-top-k-materialization` | Sorting an unbounded result with a numeric comparator to keep the top rows. Use database ordering and a limit with a stable tie-breaker. |
379
- | <a id="rebuild-lookup-in-loop"></a><a id="array-repeated-membership"></a><a id="array-repeated-find"></a>`array-repeated-membership`, `array-repeated-find`, `rebuild-lookup-in-loop` | Repeated linear lookups or rebuilt indexes. Reuse a Set or Map if inputs are stable and enough lookups justify construction. Preserve first-match semantics with duplicate keys. |
380
- | <a id="reduce-copy-accumulator"></a><a id="loop-copy-accumulator"></a><a id="filter-for-existence"></a>`reduce-copy-accumulator`, `loop-copy-accumulator`, `filter-for-existence` | Copying a growing result or allocating a filtered array for a boolean test. Consider a private accumulator or a short-circuiting predicate. |
381
- | <a id="pg-unreleased-checkout"></a><a id="pool-created-per-request-or-item"></a>`pool-created-per-request-or-item`, `pg-unreleased-checkout` | A recognized pg, Prisma, MongoDB or Redis client/pool is created on a repeated path, or a chained pg checkout loses the client reference. Scope reuse to the right credentials and release checked-out clients. |
382
- | <a id="node-sync-crypto-in-async"></a><a id="node-sync-process-in-async"></a><a id="node-sync-fs-in-async"></a><a id="node-sync-compression-in-async"></a>`node-sync-fs-in-async`, `node-sync-compression-in-async`, `node-sync-crypto-in-async`, `node-sync-process-in-async` | A recognized synchronous API blocks an async function. Examples include `readFileSync`, `gzipSync`, `scryptSync` and `execFileSync`. |
383
- | <a id="redis-command-in-loop"></a>`redis-command-in-loop` | A per-key Redis or Valkey command on a repeated path. Use a multi-key command or a bounded pipeline if cluster slots, ordering and error handling permit it. SCAN cursor loops are skipped. |
384
- | <a id="password-hash-sync-in-async"></a>`password-hash-sync-in-async` | `hashSync`, `compareSync` or `genSaltSync` from bcrypt or bcryptjs in an async function blocks the event loop for the whole hash. Use the promise form. |
385
- | <a id="serial-awaits-in-literal"></a>`serial-awaits-in-literal` | An array or object awaits multiple values in order. The `Promise.all` edit requires review for shared resources, concurrency limits and failure ordering. |
386
- | <a id="queue-add-in-loop"></a>`queue-add-in-loop` | `queue.add` on a recognized job queue runs once per item, one Redis round trip each. Collect the jobs and call `addBulk`, unless a later job needs the earlier job's result or id. |
387
- | <a id="redis-keys-command"></a>`redis-keys-command` | `keys()` on a recognized ioredis or node-redis client blocks Redis while it scans the keyspace. Iterate with `SCAN` (`scanStream` or `scanIterator`) after reviewing duplicate keys, iteration order and concurrent writes. |
388
- | <a id="service-query-in-loop"></a>`service-query-in-loop` | A call in a loop reaches several database operations through a project function, so the loop pays round trips for every item. Add a batch variant. Test, seed, benchmark and script sources get a softer note. |
389
- | <a id="password-hash-pure-js"></a>`password-hash-pure-js` | `bcryptjs` hashes in pure JavaScript and costs tens to hundreds of milliseconds of main-thread CPU per call. Use native `bcrypt`, `@node-rs/bcrypt` or `argon2`. Reported once per file; test files are skipped. |
390
- | <a id="external-call-in-transaction"></a>`external-call-in-transaction` | An external call is awaited inside a database transaction callback, holding the connection and locks until it returns. Move it before the transaction or after commit; side effects cannot roll back. |
391
- | <a id="unbounded-list-query"></a>`unbounded-list-query` | A Prisma, TypeORM, Drizzle or pg list query has no `take` or `limit` and its rows are returned from a request handler. Unique-key lookups are skipped; one-hop service findings require contextual mode. A page size taken straight from request input with no upper cap is reported too. |
392
- | <a id="unbounded-module-cache"></a>`unbounded-module-cache` | A module-level or singleton-service `Map`, `Set` or object is filled by dynamic key inside functions and never deleted from, cleared or size-checked. The key space may still be small. |
393
- | <a id="whole-payload-in-memory"></a>`whole-payload-in-memory` | A handler reads a request-chosen path with `fs.readFile`, or a download or stream is buffered whole only to be written out. Stream it with `pipeline`. The `Response` check needs fetch types. |
394
- | <a id="list-query-overfetch"></a>`list-query-overfetch` | A Prisma `findMany` or TypeORM `find` without `select` loads `Json`, `Bytes` or text columns, or relations two levels deep. Column checks need a parseable schema; pages up to 100 rows skip them. |
395
- | <a id="orm-deep-offset"></a>`orm-deep-offset` | A Prisma `skip`, TypeORM, Sequelize, Mongoose, Drizzle or Knex offset, or a pg `OFFSET $n`, takes request input with no upper bound, or is a literal above 10000. The database reads and discards every skipped row; use keyset (cursor) pagination. One-hop service calls and schemas whose limit cannot be read are contextual. |
396
- | <a id="list-count-per-request"></a>`list-count-per-request` | A request handler that pages rows also runs a full count (`count`, `findAndCount`, `countDocuments`, `select count(...)`) and returns the total. Cached and first-page-only counts are skipped; counts filtered by an id column, and counts with the same `where` as a list limited to one page (`take`/`limit`), are contextual. A serial count then page is `count-then-page-serial` instead. |
397
- | <a id="notification-send-in-loop"></a>`notification-send-in-loop` | A firebase-admin, SendGrid, Expo, OneSignal or SNS send runs once per loop item where the provider has a batch API. nodemailer, web-push, Twilio and SES sends are contextual because their batch shape depends on the content. Providers are recognised from their types. |
398
- | <a id="session-memory-store"></a>`session-memory-store` | `express-session` or `@fastify/session` is set up without a `store`, so sessions live in process memory: they leak, are lost on restart and are not shared across instances. Pass a shared store such as connect-redis or connect-pg-simple. |
399
- | <a id="orm-cartesian-include"></a>`orm-cartesian-include` | One TypeORM or Sequelize query joins two or more collection relations (`leftJoinAndSelect`, `relations`, `include`), so the rows multiply as the product of their sizes. Load the second collection in its own query (`relationLoadStrategy: 'query'`, Sequelize `separate: true`). |
400
- | <a id="json-roundtrip-clone"></a>`json-roundtrip-clone` | A value is deep-copied with `JSON.parse(JSON.stringify(...))` in a request handler or loop. Use `structuredClone`, or copy only the fields you change. |
401
- | <a id="mongoose-hydrate-for-to-object"></a>`mongoose-hydrate-for-to-object` | A Mongoose `find`, `findOne` or `findById` result is only null-checked and converted with `.toObject()` or `.toJSON()`. Append `.lean()` to skip hydration. Skipped when a schema customizes `toObject` or `toJSON`. |
402
- | <a id="express-missing-compression"></a>`express-missing-compression` | An Express app calls `listen` and no project file imports `compression`. Reported as contextual: a reverse proxy may already compress responses. Test files are skipped. |
403
- | <a id="heavy-media-in-request-handler"></a>`heavy-media-in-request-handler` | `sharp` image processing, Puppeteer `page.pdf()` or `html-pdf` rendering runs inside a request handler. Move it to a job queue or worker thread. Contextual, because offloading changes the API. |
404
- | <a id="react-missing-cleanup"></a>`react-missing-cleanup` | An effect starts a global listener, interval, socket or endless subscription and returns no cleanup, so it leaks on every remount. |
405
- | <a id="react-index-as-key"></a>`react-index-as-key` | A list item uses the map index as its React key, which breaks reconciliation when items are inserted or reordered. |
406
- | <a id="react-fetch-in-effect-no-abort"></a>`react-fetch-in-effect-no-abort` | A fetch in an effect has no AbortController or cleanup, so dependency changes can race and apply stale results. |
407
- | <a id="react-inline-object-in-jsx-prop"></a>`react-inline-object-in-jsx-prop` | An inline object literal is passed to a memo() component, creating a new reference each render and defeating the memo. |
408
- | <a id="angular-subscribe-without-cleanup"></a>`angular-subscribe-without-cleanup` | An RxJS subscription in a component has no completing operator or ngOnDestroy unsubscribe and keeps running after destruction. |
409
- | <a id="angular-default-change-detection"></a>`angular-default-change-detection` | An Angular component uses default change detection instead of OnPush, so its subtree is re-checked on every event. |
410
- | <a id="vue-watch-missing-cleanup"></a>`vue-watch-missing-cleanup` | onMounted registers a global listener, timer or observer with no unmount cleanup. |
411
- | <a id="vue-v-for-missing-key"></a>`vue-v-for-missing-key` | A list rendered with h() has no key prop, forcing inefficient patching. |
412
- | <a id="dom-layout-thrashing"></a>`dom-layout-thrashing` | A loop reads layout metrics and mutates DOM styles or classes, forcing a reflow on each iteration. |
413
- | <a id="dom-listener-without-cleanup"></a>`dom-listener-without-cleanup` | A window or document listener uses an inline function with no AbortSignal or once, so it can never be removed. |
414
- | <a id="dom-unthrottled-scroll-resize"></a>`dom-unthrottled-scroll-resize` | A scroll, resize, mousemove, wheel or touch listener runs unthrottled work (or is non-passive) on the main thread. |
415
- | <a id="frontend-barrel-heavy-import"></a>`frontend-barrel-heavy-import` | A client module imports the whole of lodash or moment instead of subpaths or a lighter library. |
416
- | <a id="sql-select-star-in-query"></a>`sql-select-star-in-query` | A raw SQL query selects every column with SELECT * instead of the columns it needs. |
417
- | <a id="sequential-http-in-loop"></a>`sequential-http-in-loop` | Independent HTTP requests are awaited one at a time inside a loop. |
418
- | <a id="mongoose-missing-lean"></a>`mongoose-missing-lean` | A Mongoose `.find()`, `.findOne()`, or `.findById()` read query is returned or JSON-serialized without `.lean()`. |
419
- | <a id="graphql-n-plus-one-resolver"></a>`graphql-n-plus-one-resolver` | A GraphQL field resolver executes a database or HTTP query per parent item without `DataLoader` `.load()` batching. |
420
- | <a id="react-context-value-recreated"></a>`react-context-value-recreated` | An inline object or array literal in `<*.Provider value={...}>` creates a new reference on every render without `useMemo`. |
421
- | <a id="node-event-listener-leak"></a>`node-event-listener-leak` | `.on()`, `.addListener()`, or `.addEventListener()` is registered in a request handler, loop, or lifecycle hook without cleanup. |
422
- | <a id="json-stringify-in-loop"></a>`json-stringify-in-loop` | `JSON.stringify()` is called inside a `for`, `while`, `do`, `.forEach`, `.map`, or `.reduce` loop. |
423
-
424
- 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.
425
-
426
- 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.
427
-
428
- ```ts
429
- // loadwise-reviewed pg-query-in-loop -- Each iteration measures a separate query-plan sample.
430
- await client.query(statement);
366
+ ```text
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.
368
+ Fix (examples/slow.ts:7):
369
+ - const names = visible.map(order => customers.find(customer => customer.id === order.customerId)?.name ?? 'Unknown');
370
+ + const customersById = new Map(customers.map((customer) => [customer.id, customer] as const).reverse());
371
+ + const names = visible.map(order => customersById.get(order.customerId)?.name ?? 'Unknown');
431
372
  ```
432
373
 
433
- 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.
434
-
435
- 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.
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` |
436
382
 
437
- 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)
383
+ ## Source checks
438
384
 
439
- 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.
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.
388
+
389
+ <!-- loadwise:rules:start checker=performance group=source-checks -->
390
+
391
+ | Rule | Impact | What it flags |
392
+ | --------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
393
+ | <a id="angular-default-change-detection"></a>[`angular-default-change-detection`](docs/rules/angular-default-change-detection.md) | low | An Angular component uses default change detection instead of OnPush, so its subtree is re-checked on every event. |
394
+ | <a id="angular-ngfor-missing-trackby"></a>[`angular-ngfor-missing-trackby`](docs/rules/angular-ngfor-missing-trackby.md) | low | An *ngFor has no trackBy, so a list replaced with new objects recreates the DOM of every item. |
395
+ | <a id="angular-subscribe-without-cleanup"></a>[`angular-subscribe-without-cleanup`](docs/rules/angular-subscribe-without-cleanup.md) | medium | An RxJS subscription in a component has no completing operator or ngOnDestroy unsubscribe and keeps running after destruction. |
396
+ | <a id="array-repeated-find"></a>[`array-repeated-find`](docs/rules/array-repeated-find.md) | medium | An array is searched with find or findIndex repeatedly where a Map lookup would do. |
397
+ | <a id="array-repeated-membership"></a>[`array-repeated-membership`](docs/rules/array-repeated-membership.md) | medium | An array is tested with includes or indexOf repeatedly where a Set would do. |
398
+ | <a id="dom-layout-thrashing"></a>[`dom-layout-thrashing`](docs/rules/dom-layout-thrashing.md) | medium | A loop reads layout metrics and mutates DOM styles or classes, forcing a reflow on each iteration. |
399
+ | <a id="dom-listener-without-cleanup"></a>[`dom-listener-without-cleanup`](docs/rules/dom-listener-without-cleanup.md) | low | A window or document listener uses an inline function with no AbortSignal or once, so it can never be removed. |
400
+ | <a id="dom-unthrottled-scroll-resize"></a>[`dom-unthrottled-scroll-resize`](docs/rules/dom-unthrottled-scroll-resize.md) | low | A scroll, resize, mousemove, wheel or touch listener runs unthrottled work (or is non-passive) on the main thread. |
401
+ | <a id="express-missing-compression"></a>[`express-missing-compression`](docs/rules/express-missing-compression.md) | low | An Express server registers no response compression middleware. |
402
+ | <a id="external-call-in-transaction"></a>[`external-call-in-transaction`](docs/rules/external-call-in-transaction.md) | high | An external call is awaited inside a database transaction, holding its connection and locks. |
403
+ | <a id="filter-for-existence"></a>[`filter-for-existence`](docs/rules/filter-for-existence.md) | low | filter(...).length is used only to test whether any element matches. |
404
+ | <a id="frontend-barrel-heavy-import"></a>[`frontend-barrel-heavy-import`](docs/rules/frontend-barrel-heavy-import.md) | low | A client module imports the whole of lodash or moment instead of subpaths or a lighter library. |
405
+ | <a id="graphql-n-plus-one-resolver"></a>[`graphql-n-plus-one-resolver`](docs/rules/graphql-n-plus-one-resolver.md) | high | A GraphQL field resolver executes a database or HTTP query per parent item without DataLoader batching. |
406
+ | <a id="heavy-media-in-request-handler"></a>[`heavy-media-in-request-handler`](docs/rules/heavy-media-in-request-handler.md) | medium | Heavy image (sharp) or PDF rendering runs directly inside an HTTP request handler. |
407
+ | <a id="json-roundtrip-clone"></a>[`json-roundtrip-clone`](docs/rules/json-roundtrip-clone.md) | low | A value is deep-cloned with JSON.parse(JSON.stringify(...)) on a request path. |
408
+ | <a id="json-stringify-in-loop"></a>[`json-stringify-in-loop`](docs/rules/json-stringify-in-loop.md) | medium | JSON.stringify runs inside a loop instead of serializing once or streaming. |
409
+ | <a id="list-count-per-request"></a>[`list-count-per-request`](docs/rules/list-count-per-request.md) | medium | A list endpoint runs a full count query on every request. |
410
+ | <a id="list-query-overfetch"></a>[`list-query-overfetch`](docs/rules/list-query-overfetch.md) | medium | A list query loads large columns or nested relations without a narrow projection. |
411
+ | <a id="llm-call-without-max-tokens"></a>[`llm-call-without-max-tokens`](docs/rules/llm-call-without-max-tokens.md) | medium | An OpenAI chat or responses call sets no output token limit. |
412
+ | <a id="loop-copy-accumulator"></a>[`loop-copy-accumulator`](docs/rules/loop-copy-accumulator.md) | medium | A loop copies its growing result on every iteration. |
413
+ | <a id="mongoose-hydrate-for-to-object"></a>[`mongoose-hydrate-for-to-object`](docs/rules/mongoose-hydrate-for-to-object.md) | medium | A Mongoose query hydrates full Documents only to convert them immediately via .toObject() or .toJSON(). |
414
+ | <a id="mongoose-missing-lean"></a>[`mongoose-missing-lean`](docs/rules/mongoose-missing-lean.md) | medium | A Mongoose read query is returned or serialized without .lean(), paying full Document hydration overhead. |
415
+ | <a id="node-event-listener-leak"></a>[`node-event-listener-leak`](docs/rules/node-event-listener-leak.md) | high | An event listener is registered inside a repeated or per-request context without matching cleanup. |
416
+ | <a id="node-sync-compression-in-async"></a>[`node-sync-compression-in-async`](docs/rules/node-sync-compression-in-async.md) | medium | A synchronous zlib call blocks the event loop inside an async function. |
417
+ | <a id="node-sync-crypto-in-async"></a>[`node-sync-crypto-in-async`](docs/rules/node-sync-crypto-in-async.md) | high | A synchronous crypto call blocks the event loop inside an async function. |
418
+ | <a id="node-sync-fs-in-async"></a>[`node-sync-fs-in-async`](docs/rules/node-sync-fs-in-async.md) | medium | A synchronous fs call blocks the event loop inside an async function. |
419
+ | <a id="node-sync-process-in-async"></a>[`node-sync-process-in-async`](docs/rules/node-sync-process-in-async.md) | high | A synchronous child_process call blocks the event loop inside an async function. |
420
+ | <a id="notification-send-in-loop"></a>[`notification-send-in-loop`](docs/rules/notification-send-in-loop.md) | high | A push, email or Firebase message is sent once per loop iteration instead of in one batch. |
421
+ | <a id="orm-cartesian-include"></a>[`orm-cartesian-include`](docs/rules/orm-cartesian-include.md) | high | One query joins two or more one-to-many relations, so the returned rows multiply. |
422
+ | <a id="orm-deep-offset"></a>[`orm-deep-offset`](docs/rules/orm-deep-offset.md) | high | A list query pages with a large or unbounded offset, so the database reads and discards every skipped row. |
423
+ | <a id="password-hash-pure-js"></a>[`password-hash-pure-js`](docs/rules/password-hash-pure-js.md) | medium | bcryptjs hashes passwords in pure JavaScript on the main thread. |
424
+ | <a id="password-hash-sync-in-async"></a>[`password-hash-sync-in-async`](docs/rules/password-hash-sync-in-async.md) | high | A synchronous bcrypt call blocks the event loop inside an async function. |
425
+ | <a id="pg-count-materialization"></a>[`pg-count-materialization`](docs/rules/pg-count-materialization.md) | medium | A pg query loads rows only to count them. |
426
+ | <a id="pg-filter-materialization"></a>[`pg-filter-materialization`](docs/rules/pg-filter-materialization.md) | medium | A pg query loads an unbounded result that JavaScript then filters by equality. |
427
+ | <a id="pg-first-materialization"></a>[`pg-first-materialization`](docs/rules/pg-first-materialization.md) | medium | A pg query loads an unbounded result to read only its first row. |
428
+ | <a id="pg-query-in-loop"></a>[`pg-query-in-loop`](docs/rules/pg-query-in-loop.md) | high | A pg query runs once per loop iteration. |
429
+ | <a id="pg-top-k-materialization"></a>[`pg-top-k-materialization`](docs/rules/pg-top-k-materialization.md) | medium | A pg query loads an unbounded result that JavaScript sorts to keep the top rows. |
430
+ | <a id="pg-unreleased-checkout"></a>[`pg-unreleased-checkout`](docs/rules/pg-unreleased-checkout.md) | critical | A chained pool checkout loses the client, so it is never released. |
431
+ | <a id="pool-created-per-request-or-item"></a>[`pool-created-per-request-or-item`](docs/rules/pool-created-per-request-or-item.md) | critical | A database, Redis, S3, OpenAI, Anthropic or Stripe client or pool is created on a per-request or per-item path. |
432
+ | <a id="prisma-count-materialization"></a>[`prisma-count-materialization`](docs/rules/prisma-count-materialization.md) | medium | A Prisma query loads rows only to count them. |
433
+ | <a id="prisma-filter-materialization"></a>[`prisma-filter-materialization`](docs/rules/prisma-filter-materialization.md) | medium | A Prisma query loads an unbounded result that JavaScript then filters by equality. |
434
+ | <a id="prisma-first-materialization"></a>[`prisma-first-materialization`](docs/rules/prisma-first-materialization.md) | medium | A Prisma query loads an unbounded result to read only its first row. |
435
+ | <a id="prisma-query-in-loop"></a>[`prisma-query-in-loop`](docs/rules/prisma-query-in-loop.md) | high | A Prisma query runs once per loop iteration. |
436
+ | <a id="prisma-top-k-materialization"></a>[`prisma-top-k-materialization`](docs/rules/prisma-top-k-materialization.md) | medium | A Prisma query loads an unbounded result that JavaScript sorts to keep the top rows. |
437
+ | <a id="queue-add-in-loop"></a>[`queue-add-in-loop`](docs/rules/queue-add-in-loop.md) | high | A job queue add runs once per item instead of one addBulk. |
438
+ | <a id="react-component-defined-in-component"></a>[`react-component-defined-in-component`](docs/rules/react-component-defined-in-component.md) | medium | A component is declared inside another component and rendered as an element, so it remounts on every render and loses its state and DOM. |
439
+ | <a id="react-context-value-recreated"></a>[`react-context-value-recreated`](docs/rules/react-context-value-recreated.md) | low | An inline object or array literal in Context.Provider value creates a new reference on every render. |
440
+ | <a id="react-fetch-in-effect-no-abort"></a>[`react-fetch-in-effect-no-abort`](docs/rules/react-fetch-in-effect-no-abort.md) | low | A fetch in an effect has no AbortController or cleanup, so dependency changes can race and apply stale results. |
441
+ | <a id="react-index-as-key"></a>[`react-index-as-key`](docs/rules/react-index-as-key.md) | low | A list item uses the map index as its React key, which breaks reconciliation when items are inserted or reordered. |
442
+ | <a id="react-inline-object-in-jsx-prop"></a>[`react-inline-object-in-jsx-prop`](docs/rules/react-inline-object-in-jsx-prop.md) | low | An inline object literal is passed to a memo() component, creating a new reference each render and defeating the memo. |
443
+ | <a id="react-missing-cleanup"></a>[`react-missing-cleanup`](docs/rules/react-missing-cleanup.md) | medium | An effect starts a global listener, interval, socket or endless subscription and returns no cleanup, so it leaks on every remount. |
444
+ | <a id="rebuild-lookup-in-loop"></a>[`rebuild-lookup-in-loop`](docs/rules/rebuild-lookup-in-loop.md) | high | A Set or Map is rebuilt from the same data on every loop iteration. |
445
+ | <a id="redis-command-in-loop"></a>[`redis-command-in-loop`](docs/rules/redis-command-in-loop.md) | high | A per-key Redis command runs once per loop iteration. |
446
+ | <a id="redis-keys-command"></a>[`redis-keys-command`](docs/rules/redis-keys-command.md) | high | A Redis KEYS call blocks the server while it scans the keyspace. |
447
+ | <a id="reduce-copy-accumulator"></a>[`reduce-copy-accumulator`](docs/rules/reduce-copy-accumulator.md) | medium | A reduce callback copies its growing accumulator on every step. |
448
+ | <a id="sequential-http-in-loop"></a>[`sequential-http-in-loop`](docs/rules/sequential-http-in-loop.md) | high | Independent HTTP requests are awaited one at a time inside a loop. |
449
+ | <a id="serial-awaits-in-literal"></a>[`serial-awaits-in-literal`](docs/rules/serial-awaits-in-literal.md) | medium | An array or object literal awaits two or more independent values one after another. |
450
+ | <a id="service-query-in-loop"></a>[`service-query-in-loop`](docs/rules/service-query-in-loop.md) | high | A loop calls a project function that runs several database operations per item. |
451
+ | <a id="session-memory-store"></a>[`session-memory-store`](docs/rules/session-memory-store.md) | high | An express-session middleware has no store, so sessions live in process memory. |
452
+ | <a id="sql-select-star-in-query"></a>[`sql-select-star-in-query`](docs/rules/sql-select-star-in-query.md) | low | A raw SQL query selects every column with SELECT * instead of the columns it needs. |
453
+ | <a id="unbounded-list-query"></a>[`unbounded-list-query`](docs/rules/unbounded-list-query.md) | high | A request handler returns query results without an apparent row limit. |
454
+ | <a id="unbounded-module-cache"></a>[`unbounded-module-cache`](docs/rules/unbounded-module-cache.md) | medium | A long-lived cache accepts dynamic keys without an apparent bound or eviction. |
455
+ | <a id="vue-v-for-missing-key"></a>[`vue-v-for-missing-key`](docs/rules/vue-v-for-missing-key.md) | low | A list rendered with h() has no key prop, forcing inefficient patching. |
456
+ | <a id="vue-watch-missing-cleanup"></a>[`vue-watch-missing-cleanup`](docs/rules/vue-watch-missing-cleanup.md) | medium | onMounted registers a global listener, timer or observer with no unmount cleanup. |
457
+ | <a id="whole-payload-in-memory"></a>[`whole-payload-in-memory`](docs/rules/whole-payload-in-memory.md) | medium | An operation loads an entire file, stream, or response into memory. |
458
+
459
+ <!-- loadwise:rules:end -->
440
460
 
441
461
  ## ORM and query integrity checks
442
462
 
443
- The JS/TS checker resolves declarations from installed drivers and generated clients. Install the dependencies used by the project, including type declarations. When resolution is incomplete, some calls will be missed. The rules run locally against source and recorded evidence.
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.
444
464
 
445
- | Library | Source patterns covered |
446
- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
447
- | 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. |
448
- | 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. |
449
- | TypeORM | Repository reads inside repeated execution and simple `find` or `findBy` calls that load entities only for their count. |
450
- | Sequelize | Model reads inside repeated execution and immediate counts of simple `findAll` results. |
451
- | Mongoose | Consumed model queries including common `lean` and `exec` chains, plus immediate counts for simple equivalent filters. |
452
- | Knex and Kysely | Consumed Knex builders and Kysely SELECT execution methods inside repeated work. Simple single-table queries materialized only to read their length. |
453
- | node-postgres | Per-item queries, client-side result processing, pool handoff and transaction commands issued through a pool. |
465
+ <!-- loadwise:rules:start checker=performance group=orm-and-query-integrity-checks -->
454
466
 
455
- <a id="drizzle-query-in-loop"></a><a id="orm-query-in-loop"></a><a id="typeorm-transaction-in-loop"></a><a id="orm-count-materialization"></a><a id="typeorm-existence-materialization"></a><a id="typeorm-wide-projection"></a>`orm-query-in-loop`, `drizzle-query-in-loop` and `orm-count-materialization` preserve the distinction between building a lazy statement and executing it. Counts with pagination, grouping, joins, hooks or scopes need particular care. TypeORM checks also identify entity reads used only for existence (`typeorm-existence-materialization`), unused wide columns in a direct DTO projection (`typeorm-wide-projection`), and a loop calling a local private helper that starts a transaction (`typeorm-transaction-in-loop`). Before changing a projection or an existence check, verify entity-load side effects. For per-row transactions, check rollback, ordering and error reporting before batching. The adapters recognize specific typed APIs. Custom methods with the same name, raw queries and wrappers often have different semantics.
467
+ | Rule | Impact | What it flags |
468
+ | ------------------------------------------------------------------------------------------------------------------------------------ | ------ | ---------------------------------------------------------------------------------------- |
469
+ | <a id="drizzle-query-in-loop"></a>[`drizzle-query-in-loop`](docs/rules/drizzle-query-in-loop.md) | high | A Drizzle statement executes once per loop iteration. |
470
+ | <a id="guard-query-per-request"></a>[`guard-query-per-request`](docs/rules/guard-query-per-request.md) | medium | A guard or per-request hook runs a database query before every handler. |
471
+ | <a id="orm-count-materialization"></a>[`orm-count-materialization`](docs/rules/orm-count-materialization.md) | medium | A TypeORM, Sequelize, Mongoose, Knex or Kysely query loads rows only to count them. |
472
+ | <a id="orm-query-in-loop"></a>[`orm-query-in-loop`](docs/rules/orm-query-in-loop.md) | high | A TypeORM, Sequelize, Mongoose, Knex or Kysely operation runs once per loop iteration. |
473
+ | <a id="prisma-distinct-in-memory"></a>[`prisma-distinct-in-memory`](docs/rules/prisma-distinct-in-memory.md) | medium | Prisma findMany with distinct reads every matching row and de-duplicates in memory. |
474
+ | <a id="prisma-relation-count-in-list"></a>[`prisma-relation-count-in-list`](docs/rules/prisma-relation-count-in-list.md) | medium | A paged Prisma findMany selects a relation _count computed over the whole related table. |
475
+ | <a id="typeorm-existence-materialization"></a>[`typeorm-existence-materialization`](docs/rules/typeorm-existence-materialization.md) | medium | A TypeORM entity is loaded only to check whether it exists. |
476
+ | <a id="typeorm-load-then-save"></a>[`typeorm-load-then-save`](docs/rules/typeorm-load-then-save.md) | high | A TypeORM entity is loaded only to change a few fields and save it back. |
477
+ | <a id="typeorm-transaction-in-loop"></a>[`typeorm-transaction-in-loop`](docs/rules/typeorm-transaction-in-loop.md) | high | A loop calls a helper that starts one TypeORM transaction per item. |
478
+ | <a id="typeorm-wide-projection"></a>[`typeorm-wide-projection`](docs/rules/typeorm-wide-projection.md) | low | A TypeORM DTO projection loads wide columns it never uses. |
456
479
 
457
- | Integrity rule | What to review |
458
- | ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
459
- | <a id="prisma-distinct-in-memory"></a>`prisma-distinct-in-memory` | `findMany({ distinct })` reads every matching row and de-duplicates in Prisma's query engine, not with SQL `DISTINCT`. Use `groupBy` or a raw `SELECT DISTINCT`. Quiet when the `nativeDistinct` preview feature is enabled. |
460
- | <a id="prisma-relation-count-in-list"></a>`prisma-relation-count-in-list` | A paged `findMany` selects `_count` of a relation, which Prisma computes over the whole related table. Fetch the page, then `groupBy` for the page ids and merge the counts. |
461
- | <a id="typeorm-load-then-save"></a>`typeorm-load-then-save` | A repository entity is loaded only to change a few fields and then `save()`d, costing a SELECT, an UPDATE and a transaction. Use `update()` or `increment()`; entity listeners and subscribers for update will not run. |
462
- | <a id="guard-query-per-request"></a>`guard-query-per-request` | A guard or similar per-request hook runs a database query before every handler. Cache the lookup with a short TTL and explicit invalidation, or carry the claims in the token. |
463
-
464
- 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)
480
+ <!-- loadwise:rules:end -->
465
481
 
466
482
  ### Project-defined access policy
467
483
 
468
- 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 (`prismaScopes`, `drizzleScopes`, `parallelReads`, and `fireAndForget`, a list of helper names that `floating-promise` accepts without an await). Duplicate JSON keys within the same object produce a configuration error. [Example policy](examples/query-policy.json)
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)
469
485
 
470
486
  ### Async work and sorting
471
487
 
472
- | Rule | When it reports |
473
- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
474
- | <a id="promise-combinator-serial-await"></a>`promise-combinator-serial-await` | A built-in `Promise.all` or `Promise.allSettled` receives an array of two or more already-awaited calls with known promise types. Starting them together changes which calls run after a failure. With `allSettled`, it also changes how rejections are returned. |
475
- | <a id="known-reads-awaited-serially"></a>`known-reads-awaited-serially` | Two adjacent awaited reads come from a project-configured `parallelReads` group and the second call is independent of the first result in a supported straight-line shape. |
476
- | <a id="numeric-sort-for-extreme"></a>`numeric-sort-for-extreme` | A numeric comparison sort on a private copy, or a nonmutating numeric sort, is used only to retrieve its first or last value. A single-pass extreme can use constant extra space. Preserve empty input, NaN, sparse inputs and signed-zero semantics when applicable. |
477
- | <a id="count-then-page-serial"></a>`count-then-page-serial` | A `count()` and a page query with the same filter run one after the other (TypeORM query builder or repository, Prisma). Use `getManyAndCount()` or `findAndCount()`, or start both Prisma calls together with `Promise.all` outside an interactive transaction. |
478
- | <a id="typeorm-unused-count"></a>`typeorm-unused-count` | A typed TypeORM `findAndCount()`, `findAndCountBy()` or `getManyAndCount()` call returns rows and a count but the awaited destructuring only keeps the rows. Use `find()`, `findBy()` or `getMany()` with the same filters and paging when the count is unnecessary. |
479
- | <a id="prisma-count-for-existence"></a>`prisma-count-for-existence` | An awaited numeric Prisma `count()` with no options or only `where` is used solely as a zero-or-nonzero test. Read one row with the same filter and a small projection when only existence matters. |
480
- | <a id="await-before-early-exit"></a>`await-before-early-exit` | An awaited ORM or HTTP read is followed directly by an `if` that returns or throws without using the result, so a request the guard rejects still pays the round trip. Writes, `OrThrow` reads and POSTs are left alone. The fix moves the guard above the await only when it has no calls and reads only parameters and earlier constants. |
481
- | <a id="drizzle-last-insert-id"></a>`drizzle-last-insert-id` | A MySQL insert is followed by a separate query for the last generated ID. Review using the insert result directly, especially when the database handle uses a connection pool. |
482
- | <a id="repeated-workbook-decode"></a>`repeated-workbook-decode` | Sibling awaits pass the same input to ExcelJS workbook decoding directly or through same-file private methods or functions. Share a parsed workbook when its readers can safely use the same state. |
483
-
484
- 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.
485
-
486
- ```ts
487
- import { fetchUser, fetchPosts } from '@app/reads';
488
-
489
- async function load() {
490
- const user = await fetchUser();
491
- const posts = await fetchPosts();
492
- return { user, posts };
493
- }
494
- ```
495
-
496
- 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)
497
-
498
- ## Inline fixes
499
-
500
- 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.
501
-
502
- ```sh
503
- npx loadwise perf -p tsconfig.json --fix # asks y/n/a/q for each fix; needs a terminal
504
- npx loadwise perf -p tsconfig.json --fix --yes # applies eligible fixes without asking
505
- ```
506
-
507
- `--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. 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.
508
-
509
- ## Apply fixes by id
510
-
511
- 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:
512
-
513
- ```sh
514
- npx loadwise perf --fix --only a1b2c3d4e5f6,0f9e8d7c6b5a --json # prints { applied, alreadyApplied, failed }
515
- ```
516
-
517
- 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.
488
+ <!-- loadwise:rules:start checker=performance group=async-work-and-sorting -->
518
489
 
519
- ## Check only the lines you changed
520
-
521
- ```sh
522
- npx loadwise perf --staged # lines added or modified in the git index
523
- npx loadwise perf --changed-since origin/main # lines changed in the working tree since a ref
524
- npx loadwise perf -p tsconfig.json --staged --json
525
- ```
490
+ | Rule | Impact | What it flags |
491
+ | ------------------------------------------------------------------------------------------------------------------------------ | ------ | -------------------------------------------------------------------------------------------- |
492
+ | <a id="await-before-early-exit"></a>[`await-before-early-exit`](docs/rules/await-before-early-exit.md) | medium | An awaited read runs before a guard that returns or throws without using its result. |
493
+ | <a id="count-then-page-serial"></a>[`count-then-page-serial`](docs/rules/count-then-page-serial.md) | low | A count and a page query with the same filter run one after the other. |
494
+ | <a id="drizzle-last-insert-id"></a>[`drizzle-last-insert-id`](docs/rules/drizzle-last-insert-id.md) | medium | A MySQL insert is followed by an extra query for its generated ID. |
495
+ | <a id="known-reads-awaited-serially"></a>[`known-reads-awaited-serially`](docs/rules/known-reads-awaited-serially.md) | medium | Two independent reads from a configured parallelReads group are awaited one after the other. |
496
+ | <a id="numeric-sort-for-extreme"></a>[`numeric-sort-for-extreme`](docs/rules/numeric-sort-for-extreme.md) | low | A numeric sort is used only to read the smallest or largest value. |
497
+ | <a id="prisma-count-for-existence"></a>[`prisma-count-for-existence`](docs/rules/prisma-count-for-existence.md) | medium | A Prisma query counts all matches only to check whether any row exists. |
498
+ | <a id="promise-combinator-serial-await"></a>[`promise-combinator-serial-await`](docs/rules/promise-combinator-serial-await.md) | medium | Promise.all receives calls that were already awaited one by one. |
499
+ | <a id="repeated-workbook-decode"></a>[`repeated-workbook-decode`](docs/rules/repeated-workbook-decode.md) | medium | A workflow decodes the same input with ExcelJS more than once. |
500
+ | <a id="typeorm-unused-count"></a>[`typeorm-unused-count`](docs/rules/typeorm-unused-count.md) | medium | A TypeORM count-and-list query discards its total in immediate tuple destructuring. |
526
501
 
527
- 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`.
502
+ <!-- loadwise:rules:end -->
528
503
 
529
504
  ## Schema-aware index checks
530
505
 
531
- 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.
532
507
 
533
- | Rule | What it flags |
534
- | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
535
- | <a id="index-missing-filter"></a>`index-missing-filter` | A query filters on a column that no index leads with. |
536
- | <a id="index-missing-order"></a>`index-missing-order` | A query orders by columns no index can serve in that order. |
537
- | <a id="index-missing-foreign-key"></a>`index-missing-foreign-key` | A foreign key column has no index. |
538
- | <a id="index-unusable-pattern"></a>`index-unusable-pattern` | A predicate such as a leading-wildcard `LIKE` cannot use an ordinary index. |
539
- | <a id="index-unusable-expression"></a>`index-unusable-expression` | A function or expression on an indexed column prevents the index from being used. |
540
- | <a id="index-redundant-prefix"></a>`index-redundant-prefix` | An index repeats the leading columns of a longer index on the same table (or duplicates it), adding write and memory cost while serving no read the longer one cannot; drop the shorter one (for Sequelize, remove it from the model too, since `sync({ alter: true })` recreates it). An index inherited from a base entity is reported once, at the base class. |
508
+ <!-- loadwise:rules:start checker=performance group=schema-aware-index-checks -->
541
509
 
542
- 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.
510
+ | Rule | Impact | What it flags |
511
+ | ------------------------------------------------------------------------------------------------------------ | ------ | ---------------------------------------------------------------------------------------------------------------- |
512
+ | <a id="index-missing-filter"></a>[`index-missing-filter`](docs/rules/index-missing-filter.md) | high | A query filters on a column that no index leads with. |
513
+ | <a id="index-missing-foreign-key"></a>[`index-missing-foreign-key`](docs/rules/index-missing-foreign-key.md) | high | A foreign key column in the schema has no index. |
514
+ | <a id="index-missing-order"></a>[`index-missing-order`](docs/rules/index-missing-order.md) | medium | A query orders by columns that no index serves in that order. |
515
+ | <a id="index-redundant-prefix"></a>[`index-redundant-prefix`](docs/rules/index-redundant-prefix.md) | low | An index repeats the leading columns of a longer index on the same table, adding write cost for no read benefit. |
516
+ | <a id="index-unusable-expression"></a>[`index-unusable-expression`](docs/rules/index-unusable-expression.md) | high | A function or expression on an indexed column keeps the index from being used. |
517
+ | <a id="index-unusable-pattern"></a>[`index-unusable-pattern`](docs/rules/index-unusable-pattern.md) | high | A predicate such as a leading-wildcard LIKE cannot use an ordinary index. |
543
518
 
544
- 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.
519
+ <!-- loadwise:rules:end -->
545
520
 
546
521
  ## Polyglot source checks
547
522
 
548
- `npx loadwise perf polyglot src` accepts directories or individual `.py`, `.go`, `.java`, `.cs` and `.rs` files. It uses the optional ast-grep native binary and its syntax-tree patterns. `npx loadwise rel polyglot src` runs the reliability patterns, listed under [Reliability checker](#reliability-checker), on the same files. Language-specific aliases and wrappers can fall outside a pattern. [ast-grep](https://ast-grep.github.io/)
549
-
550
- 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.
551
-
552
- | Rule | Example in a loop |
553
- | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
554
- | <a id="python-copy-growing-list"></a>`python-copy-growing-list` | A list initialized to `[]` is repeatedly assigned `items = items + [value]` in a simple loop. |
555
- | <a id="python-sync-requests-in-async"></a>`python-sync-requests-in-async` | A `requests.get`, `post`, `put`, `patch`, `delete` or `request` call inside an `async def` function blocks the event loop. |
556
- | <a id="python-blocking-sleep-in-async"></a>`python-blocking-sleep-in-async` | `time.sleep(...)` inside an `async def` function, in a module that imports `time`. |
557
- | <a id="python-fixed-regex-in-loop"></a>`python-fixed-regex-in-loop` | `re.compile("pattern")` with a string literal, in a module that imports `re`. |
558
- | <a id="go-fixed-regexp-in-loop"></a>`go-fixed-regexp-in-loop` | `regexp.Compile("pattern")` or `regexp.MustCompile("pattern")` |
559
- | <a id="java-fixed-regex-in-loop"></a>`java-fixed-regex-in-loop` | `Pattern.compile("pattern")` |
560
- | <a id="csharp-fixed-regex-in-loop"></a>`csharp-fixed-regex-in-loop` | `new Regex("pattern")` |
561
- | <a id="rust-fixed-regex-in-loop"></a>`rust-fixed-regex-in-loop` | `Regex::new("pattern")` |
562
- | <a id="python-n-plus-one-orm-loop"></a>`python-n-plus-one-orm-loop` | An ORM query executes inside a Python `for` loop instead of eager loading or batching. |
563
- | <a id="python-unbounded-comprehension"></a>`python-unbounded-comprehension` | A Python list comprehension materializes an unbounded collection in memory. |
564
- | <a id="go-sql-query-in-loop"></a>`go-sql-query-in-loop` | A Go `sql.DB` or ORM query executes inside a `for` loop instead of batching. |
565
- | <a id="go-string-concat-in-loop"></a>`go-string-concat-in-loop` | Repeated `+=` string concatenation inside a Go `for` loop instead of `strings.Builder`. |
566
- | <a id="java-string-concat-in-loop"></a>`java-string-concat-in-loop` | Repeated `+=` string concatenation inside a Java loop instead of `StringBuilder`. |
567
- | <a id="java-jdbc-query-in-loop"></a>`java-jdbc-query-in-loop` | A JDBC query executes inside a Java loop instead of batching. |
568
- | <a id="csharp-string-concat-in-loop"></a>`csharp-string-concat-in-loop` | Repeated `+=` string concatenation inside a C# loop instead of `StringBuilder`. |
569
- | <a id="rust-clone-in-loop"></a>`rust-clone-in-loop` | Calling `.clone()` inside a Rust loop adds avoidable heap allocations. |
570
- | <a id="rust-format-in-loop"></a>`rust-format-in-loop` | Calling `format!` inside a Rust loop allocates a new `String` on every iteration. |
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.
524
+
525
+ <!-- loadwise:rules:start checker=performance group=polyglot-source-checks -->
526
+
527
+ | Rule | Impact | What it flags |
528
+ | --------------------------------------------------------------------------------------------------------------------------- | ------ | -------------------------------------------------------------------------------------- |
529
+ | <a id="csharp-fixed-regex-in-loop"></a>[`csharp-fixed-regex-in-loop`](docs/rules/csharp-fixed-regex-in-loop.md) | medium | A C# Regex with a fixed pattern is constructed inside a loop. |
530
+ | <a id="csharp-string-concat-in-loop"></a>[`csharp-string-concat-in-loop`](docs/rules/csharp-string-concat-in-loop.md) | medium | String concatenation in a C# loop allocates repeatedly; use StringBuilder. |
531
+ | <a id="go-fixed-regexp-in-loop"></a>[`go-fixed-regexp-in-loop`](docs/rules/go-fixed-regexp-in-loop.md) | medium | A Go regexp with a fixed pattern is compiled inside a loop. |
532
+ | <a id="go-sql-query-in-loop"></a>[`go-sql-query-in-loop`](docs/rules/go-sql-query-in-loop.md) | high | A Go database query executes inside a loop instead of batching. |
533
+ | <a id="go-string-concat-in-loop"></a>[`go-string-concat-in-loop`](docs/rules/go-string-concat-in-loop.md) | medium | String concatenation in a Go loop allocates repeatedly; use strings.Builder. |
534
+ | <a id="java-fixed-regex-in-loop"></a>[`java-fixed-regex-in-loop`](docs/rules/java-fixed-regex-in-loop.md) | medium | A Java Pattern with a fixed pattern is compiled inside a loop. |
535
+ | <a id="java-jdbc-query-in-loop"></a>[`java-jdbc-query-in-loop`](docs/rules/java-jdbc-query-in-loop.md) | high | A JDBC query executes inside a Java loop instead of batching. |
536
+ | <a id="java-string-concat-in-loop"></a>[`java-string-concat-in-loop`](docs/rules/java-string-concat-in-loop.md) | medium | String concatenation in a Java loop allocates repeatedly; use StringBuilder. |
537
+ | <a id="python-blocking-sleep-in-async"></a>[`python-blocking-sleep-in-async`](docs/rules/python-blocking-sleep-in-async.md) | high | A blocking time.sleep call runs inside a Python async def function. |
538
+ | <a id="python-copy-growing-list"></a>[`python-copy-growing-list`](docs/rules/python-copy-growing-list.md) | medium | A Python loop rebuilds a growing list with items = items + [value]. |
539
+ | <a id="python-fixed-regex-in-loop"></a>[`python-fixed-regex-in-loop`](docs/rules/python-fixed-regex-in-loop.md) | low | A Python loop compiles a fixed pattern with re.compile on every iteration. |
540
+ | <a id="python-n-plus-one-orm-loop"></a>[`python-n-plus-one-orm-loop`](docs/rules/python-n-plus-one-orm-loop.md) | high | An ORM query executes inside a Python loop instead of using eager loading or batching. |
541
+ | <a id="python-sync-requests-in-async"></a>[`python-sync-requests-in-async`](docs/rules/python-sync-requests-in-async.md) | high | A blocking requests HTTP call runs inside a Python async def function. |
542
+ | <a id="python-unbounded-comprehension"></a>[`python-unbounded-comprehension`](docs/rules/python-unbounded-comprehension.md) | medium | A Python list comprehension materializes an unbounded collection in memory. |
543
+ | <a id="rust-clone-in-loop"></a>[`rust-clone-in-loop`](docs/rules/rust-clone-in-loop.md) | low | Cloning values inside a Rust loop adds avoidable heap allocations. |
544
+ | <a id="rust-fixed-regex-in-loop"></a>[`rust-fixed-regex-in-loop`](docs/rules/rust-fixed-regex-in-loop.md) | medium | A Rust Regex with a fixed pattern is compiled inside a loop. |
545
+ | <a id="rust-format-in-loop"></a>[`rust-format-in-loop`](docs/rules/rust-format-in-loop.md) | low | Calling format! inside a Rust loop allocates a new String on every iteration. |
546
+
547
+ <!-- loadwise:rules:end -->
571
548
 
572
549
  ## Trace checks in other languages and databases
573
550
 
574
- Supply a local **OTLP/JSON trace export** with `resourceSpans → scopeSpans → spans`. An OpenTelemetry Collector with a file export can produce this format. The CLI accepts one export object per invocation. For a collector output containing multiple JSON lines, pass the relevant export object for the request. Spans split across separate invocations count independently.
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.
575
552
 
576
- 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.
553
+ <!-- loadwise:rules:start checker=performance group=trace-checks-in-other-languages-and-databases -->
577
554
 
578
- | Rule | Evidence and interpretation |
579
- | ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
580
- | <a id="repeated-db-span"></a>`repeated-db-span` | Five similar sibling DB calls by default, grouped by resource, trace, parent and recorded database target. SQL statements, query summaries, operation/collection pairs and recognized DynamoDB `GetItem` events can provide signatures. Namespace-only MongoDB or DynamoDB groups call for inspection of the actual predicates. |
581
- | <a id="redis-keys-scan"></a>`redis-keys-scan` | One Redis or Valkey `KEYS` command can scan the keyspace. For incremental iteration, account for duplicates and keys changing between `SCAN` calls. |
582
- | <a id="redis-repeated-read"></a>`redis-repeated-read` | Repeated sibling `GET` or `HGET` calls. Consider compatible multi-key reads or bounded pipelining with appropriate cluster slots, ordering and error handling. Recognized pipeline children are excluded. |
583
- | <a id="duplicate-key-read"></a>`duplicate-key-read` | Two or more reads with the same observable lookup, database target and recorded scalar context under one parent. The comparison accepts application-defined context keys. Supported evidence includes a concrete Redis `GET` key or a narrow SQL equality lookup with its bound parameter. Masked targets, ambiguous context, observed writes, transactions or failed calls suppress the suggestion where identity or freshness is uncertain. |
555
+ | Rule | Impact | What it flags |
556
+ | ------------------------------------------------------------------------------------------ | ------ | ------------------------------------------------------------------- |
557
+ | <a id="duplicate-key-read"></a>[`duplicate-key-read`](docs/rules/duplicate-key-read.md) | medium | A trace repeats the same key or row read under one parent span. |
558
+ | <a id="redis-keys-scan"></a>[`redis-keys-scan`](docs/rules/redis-keys-scan.md) | high | A trace shows a Redis KEYS command scanning the keyspace. |
559
+ | <a id="redis-repeated-read"></a>[`redis-repeated-read`](docs/rules/redis-repeated-read.md) | medium | A trace shows repeated sibling Redis GET or HGET calls. |
560
+ | <a id="repeated-db-span"></a>[`repeated-db-span`](docs/rules/repeated-db-span.md) | high | A trace shows many similar sibling database calls under one parent. |
584
561
 
585
- 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)
562
+ <!-- loadwise:rules:end -->
586
563
 
587
564
  ## Executed query plans
588
565
 
589
- Feed the CLI a JSON file from PostgreSQL `EXPLAIN (ANALYZE, FORMAT JSON)` or MongoDB `explain("executionStats")`. For example, run `npx loadwise perf plan node_modules/loadwise/examples/postgres-plan.json`. The checker reads the file locally. PostgreSQL's `ANALYZE` option executes the statement when you collect the plan. [PostgreSQL EXPLAIN](https://www.postgresql.org/docs/current/using-explain.html) · [MongoDB explain results](https://www.mongodb.com/docs/manual/reference/explain-results/)
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.
567
+
568
+ <!-- loadwise:rules:start checker=performance group=executed-query-plans -->
590
569
 
591
- | Observed work | Threshold and review |
592
- | -------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
593
- | <a id="pg-sequential-scan"></a><a id="mongo-collection-scan"></a>`pg-sequential-scan`, `mongo-collection-scan` | At least 1,000 examined and at least 100 examined per returned record, treating zero returns as one for this ratio. Review selectivity and available indexes. PostgreSQL totals use the reported per-loop averages. |
594
- | <a id="pg-disk-sort"></a><a id="mongo-disk-sort"></a>`pg-disk-sort`, `mongo-disk-sort` | At least 1,024 KiB of disk use by a PostgreSQL sort participant, including a reported incremental-sort group peak, or at least 1 MiB of spill or eight spills on a MongoDB sort. Check whether earlier filtering or an index can reduce sorting work. |
595
- | <a id="pg-deep-offset"></a><a id="mongo-deep-skip"></a>`pg-deep-offset`, `mongo-deep-skip` | At least ten times as many entries walked as returned and at least 10,000 skipped per execution. For sequential pages, keyset pagination needs a stable ordering with a unique tie-breaker. |
570
+ | Rule | Impact | What it flags |
571
+ | ------------------------------------------------------------------------------------------------ | ------ | -------------------------------------------------------------------- |
572
+ | <a id="mongo-collection-scan"></a>[`mongo-collection-scan`](docs/rules/mongo-collection-scan.md) | high | A MongoDB plan scans many documents for each one it returns. |
573
+ | <a id="mongo-deep-skip"></a>[`mongo-deep-skip`](docs/rules/mongo-deep-skip.md) | high | A MongoDB query skips past many documents to return a page. |
574
+ | <a id="mongo-disk-sort"></a>[`mongo-disk-sort`](docs/rules/mongo-disk-sort.md) | medium | A MongoDB sort spilled to disk. |
575
+ | <a id="pg-deep-offset"></a>[`pg-deep-offset`](docs/rules/pg-deep-offset.md) | high | A PostgreSQL plan walks past many rows with OFFSET to return a page. |
576
+ | <a id="pg-disk-sort"></a>[`pg-disk-sort`](docs/rules/pg-disk-sort.md) | medium | A PostgreSQL sort spilled to disk. |
577
+ | <a id="pg-sequential-scan"></a>[`pg-sequential-scan`](docs/rules/pg-sequential-scan.md) | high | A PostgreSQL plan scans many rows for each one it returns. |
596
578
 
597
- 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.
579
+ <!-- loadwise:rules:end -->
598
580
 
599
581
  ## Database inspection (optional)
600
582
 
@@ -617,418 +599,186 @@ npx loadwise perf --schema snapshot.json
617
599
  | `--measure --i-understand-this-locks-tables` | PostgreSQL staging only. Time each suggested index for `--queries` by building it in a rolled-back transaction. |
618
600
  | `--runs N` | `EXPLAIN ANALYZE` runs per side for `--measure` (default 5). |
619
601
 
620
- <a id="db-unindexed-foreign-key"></a><a id="db-seq-scan-heavy-table"></a><a id="db-slow-query-plan"></a><a id="db-missing-index"></a><a id="mongo-collection-scan-observed"></a><a id="db-unused-index"></a><a id="db-duplicate-index"></a>Rules: `db-unindexed-foreign-key`, `db-unused-index`, `db-duplicate-index`, `db-seq-scan-heavy-table`, `db-slow-query-plan`, `db-missing-index` and, for MongoDB, `mongo-collection-scan-observed`. `--include-contextual`, `--ignore RULE` and `--json` work as in the other commands.
621
-
622
- **Safety guarantees.** Statements go through a read-only gateway: 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 is redacted: the connection URL, host, user, password and resolved IP addresses are replaced with `[redacted]`. Usage counters come from the node that answered, so an index unused here may still be used on a replica.
623
-
624
- **`--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.
625
-
626
- **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.
602
+ `--include-contextual`, `--ignore RULE` and `--json` work as in the other commands.
627
603
 
628
- ## Interpreting findings
604
+ <!-- loadwise:rules:start checker=performance group=database-inspection-optional -->
629
605
 
630
- 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.
606
+ | Rule | Impact | What it flags |
607
+ | --------------------------------------------------------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------- |
608
+ | <a id="db-duplicate-index"></a>[`db-duplicate-index`](docs/rules/db-duplicate-index.md) | low | A database index is covered by another index on the same table. |
609
+ | <a id="db-missing-index"></a>[`db-missing-index`](docs/rules/db-missing-index.md) | high | A query plan scans a table that a suggested index would let it seek. |
610
+ | <a id="db-seq-scan-heavy-table"></a>[`db-seq-scan-heavy-table`](docs/rules/db-seq-scan-heavy-table.md) | high | A large table is read by many sequential scans on the live database. |
611
+ | <a id="db-slow-query-plan"></a>[`db-slow-query-plan`](docs/rules/db-slow-query-plan.md) | high | One of the slowest statements reads a table with a full table scan. |
612
+ | <a id="db-unindexed-foreign-key"></a>[`db-unindexed-foreign-key`](docs/rules/db-unindexed-foreign-key.md) | high | A foreign key on the live database has no index that leads with its columns. |
613
+ | <a id="db-unused-index"></a>[`db-unused-index`](docs/rules/db-unused-index.md) | low | A database index has not been scanned since statistics were last reset. |
614
+ | <a id="mongo-collection-scan-observed"></a>[`mongo-collection-scan-observed`](docs/rules/mongo-collection-scan-observed.md) | high | Profiled MongoDB operations scanned a whole collection. |
631
615
 
632
- 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)
616
+ <!-- loadwise:rules:end -->
633
617
 
634
- ## Impact levels
635
-
636
- 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.
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.
637
619
 
638
- - `critical`: data loss or corruption, an outage or a lock risk in production.
639
- - `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.
640
- - `medium`: a measurable but local cost, or significant maintainability debt.
641
- - `low`: a micro-optimization or a readability issue.
642
-
643
- | Rule | Impact |
644
- | ----------------------------------- | -------- |
645
- | `pg-unreleased-checkout` | critical |
646
- | `pool-created-per-request-or-item` | critical |
647
- | `db-missing-index` | high |
648
- | `db-seq-scan-heavy-table` | high |
649
- | `db-slow-query-plan` | high |
650
- | `db-unindexed-foreign-key` | high |
651
- | `drizzle-query-in-loop` | high |
652
- | `external-call-in-transaction` | high |
653
- | `unbounded-list-query` | high |
654
- | `unbounded-module-cache` | medium |
655
- | `whole-payload-in-memory` | medium |
656
- | `list-query-overfetch` | medium |
657
- | `orm-deep-offset` | high |
658
- | `list-count-per-request` | medium |
659
- | `notification-send-in-loop` | high |
660
- | `session-memory-store` | high |
661
- | `orm-cartesian-include` | high |
662
- | `json-roundtrip-clone` | low |
663
- | `mongoose-hydrate-for-to-object` | medium |
664
- | `express-missing-compression` | low |
665
- | `heavy-media-in-request-handler` | medium |
666
- | `react-index-as-key` | low |
667
- | `react-fetch-in-effect-no-abort` | low |
668
- | `react-inline-object-in-jsx-prop` | low |
669
- | `angular-default-change-detection` | low |
670
- | `vue-v-for-missing-key` | low |
671
- | `dom-listener-without-cleanup` | low |
672
- | `dom-unthrottled-scroll-resize` | low |
673
- | `frontend-barrel-heavy-import` | low |
674
- | `sql-select-star-in-query` | low |
675
- | `react-missing-cleanup` | medium |
676
- | `angular-subscribe-without-cleanup` | medium |
677
- | `vue-watch-missing-cleanup` | medium |
678
- | `dom-layout-thrashing` | medium |
679
- | `mongoose-missing-lean` | medium |
680
- | `graphql-n-plus-one-resolver` | high |
681
- | `react-context-value-recreated` | low |
682
- | `node-event-listener-leak` | high |
683
- | `json-stringify-in-loop` | medium |
684
- | `sequential-http-in-loop` | high |
685
- | `index-redundant-prefix` | low |
686
- | `drizzle-last-insert-id` | medium |
687
- | `repeated-workbook-decode` | medium |
688
- | `index-missing-filter` | high |
689
- | `index-missing-foreign-key` | high |
690
- | `index-unusable-expression` | high |
691
- | `index-unusable-pattern` | high |
692
- | `mongo-collection-scan` | high |
693
- | `mongo-collection-scan-observed` | high |
694
- | `mongo-deep-skip` | high |
695
- | `node-sync-crypto-in-async` | high |
696
- | `node-sync-process-in-async` | high |
697
- | `orm-query-in-loop` | high |
698
- | `password-hash-sync-in-async` | high |
699
- | `pg-deep-offset` | high |
700
- | `pg-query-in-loop` | high |
701
- | `pg-sequential-scan` | high |
702
- | `prisma-query-in-loop` | high |
703
- | `queue-add-in-loop` | high |
704
- | `rebuild-lookup-in-loop` | high |
705
- | `redis-command-in-loop` | high |
706
- | `redis-keys-command` | high |
707
- | `redis-keys-scan` | high |
708
- | `repeated-db-span` | high |
709
- | `service-query-in-loop` | high |
710
- | `typeorm-load-then-save` | high |
711
- | `typeorm-transaction-in-loop` | high |
712
- | `array-repeated-find` | medium |
713
- | `array-repeated-membership` | medium |
714
- | `await-before-early-exit` | medium |
715
- | `csharp-fixed-regex-in-loop` | medium |
716
- | `duplicate-key-read` | medium |
717
- | `go-fixed-regexp-in-loop` | medium |
718
- | `guard-query-per-request` | medium |
719
- | `index-missing-order` | medium |
720
- | `java-fixed-regex-in-loop` | medium |
721
- | `known-reads-awaited-serially` | medium |
722
- | `loop-copy-accumulator` | medium |
723
- | `mongo-disk-sort` | medium |
724
- | `node-sync-compression-in-async` | medium |
725
- | `node-sync-fs-in-async` | medium |
726
- | `orm-count-materialization` | medium |
727
- | `password-hash-pure-js` | medium |
728
- | `pg-count-materialization` | medium |
729
- | `pg-disk-sort` | medium |
730
- | `pg-filter-materialization` | medium |
731
- | `pg-first-materialization` | medium |
732
- | `pg-top-k-materialization` | medium |
733
- | `prisma-count-materialization` | medium |
734
- | `prisma-distinct-in-memory` | medium |
735
- | `prisma-filter-materialization` | medium |
736
- | `prisma-first-materialization` | medium |
737
- | `prisma-relation-count-in-list` | medium |
738
- | `prisma-top-k-materialization` | medium |
739
- | `promise-combinator-serial-await` | medium |
740
- | `python-copy-growing-list` | medium |
741
- | `python-sync-requests-in-async` | high |
742
- | `python-blocking-sleep-in-async` | high |
743
- | `python-fixed-regex-in-loop` | low |
744
- | `python-n-plus-one-orm-loop` | high |
745
- | `python-unbounded-comprehension` | medium |
746
- | `go-sql-query-in-loop` | high |
747
- | `go-string-concat-in-loop` | medium |
748
- | `java-string-concat-in-loop` | medium |
749
- | `java-jdbc-query-in-loop` | high |
750
- | `csharp-string-concat-in-loop` | medium |
751
- | `rust-clone-in-loop` | low |
752
- | `rust-format-in-loop` | low |
753
- | `redis-repeated-read` | medium |
754
- | `reduce-copy-accumulator` | medium |
755
- | `rust-fixed-regex-in-loop` | medium |
756
- | `serial-awaits-in-literal` | medium |
757
- | `typeorm-existence-materialization` | medium |
758
- | `count-then-page-serial` | low |
759
- | `typeorm-unused-count` | medium |
760
- | `prisma-count-for-existence` | medium |
761
- | `db-duplicate-index` | low |
762
- | `db-unused-index` | low |
763
- | `filter-for-existence` | low |
764
- | `numeric-sort-for-extreme` | low |
765
- | `typeorm-wide-projection` | low |
766
-
767
- ## Verification and benchmarks
768
-
769
- 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.
770
-
771
- 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.
772
-
773
- Use Node.js 22.13+ for the full development workflow, including the in-memory SQLite benchmark.
774
-
775
- ### Source conventions
776
-
777
- The CLI and checkers are TypeScript (`.ts`) compiled in place to ES modules (`.js`, not committed) by `npm run build`, while shared VS Code modules under `editor/` 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.
778
-
779
- - Write ES `import`/`export`, with imports at the top of the file. `require()` is limited to the files listed under `overrides` in `.oxlintrc.json`, 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). Lazy loads in an async function use `await import()`. Do not add files to that list.
780
- - 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.
781
- - 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.
782
- - 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).
783
-
784
- ```sh
785
- npm ci
786
- npm test
787
- node bin/loadwise.js perf -p examples
788
- npm run bench:patterns
789
- npm run bench:scan
790
- npm run bench:scan -- --large
791
- npm run bench:traces
792
- npm run bench:scorecard
793
- npm run bench:corpus
794
- npm run bench:recall
795
- ```
796
-
797
- 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.
798
-
799
- 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.
800
-
801
- ```sh
802
- npm --prefix test/performance/integration/orms install --ignore-scripts --omit=optional --no-audit --no-fund
803
- npm --prefix test/performance/integration/orms run verify -- --native
804
- ```
805
-
806
- 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)
807
-
808
- ## References
809
-
810
- 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)
811
-
812
- 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/)
813
-
814
- 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).
815
621
 
816
622
  # Reliability checker
817
623
 
818
- `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`.
819
625
 
820
626
  ## Source rules
821
627
 
822
- The rules from `pg-transaction-on-pool` to `swallowed-error` moved from the performance and maintainability checkers with the same ids, so existing `// loadwise-reviewed` comments, `--ignore` flags and config `rules` entries keep working. Migration and API contract rules are described in [Migration safety](#migration-safety) and [API contract safety](#api-contract-safety). `csharp-async-void` and the `python-`, `go-`, `java-`, `csharp-` and `rust-` rules come from `loadwise rel polyglot`, which needs the optional ast-grep executable.
823
-
824
- | Rule | What to review |
825
- | ----------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
826
- | <a id="pg-transaction-on-pool"></a>`pg-transaction-on-pool` | A standalone transaction-control statement is sent to a typed pool. Use the same checked-out client for the whole transaction and release it in `finally`. |
827
- | <a id="prisma-transaction-client-escape"></a>`prisma-transaction-client-escape` | A direct model operation uses the same outer client that opened an interactive transaction. Verify that the operation belongs inside that transaction. |
828
- | <a id="typeorm-transaction-client-escape"></a>`typeorm-transaction-client-escape` | An awaited write inside a TypeORM transaction goes through a repository or manager that is not bound to it, so it autocommits on another pooled connection, is not rolled back with the transaction and can block on its locks. Use the transaction's manager (`manager.getRepository(Entity)`). |
829
- | <a id="prisma-read-modify-write"></a>`prisma-read-modify-write` | A direct read of one row feeds a numeric update of the same field and key. Review atomic arithmetic, an optimistic version check or serializable execution with retries. |
830
- | <a id="drizzle-unfiltered-write"></a>`drizzle-unfiltered-write` | An executed update/delete has no effective predicate in a recognized direct chain. An intentional whole-table maintenance operation can legitimately match. |
831
- | <a id="prisma-dependent-writes"></a>`prisma-dependent-writes` | Adjacent creates pass a value from the first record into the next write. Explicit single-key nested `connect` can use a custom unique field when generated types confirm a relation. Direct scalar assignments currently recognize `parent.id` going into a field ending in `Id` or `_id`. Other scalar foreign-key conventions can be missed. If both writes must succeed together, consider a nested write or an appropriate transaction. |
832
- | <a id="find-then-create-race"></a>`find-then-create-race` | A Prisma or TypeORM lookup by one key is followed in the same function by an insert with the same key, and the schema shows no unique constraint on it. Add the constraint and catch the violation (Prisma P2002, Postgres 23505) or use `upsert` / `ON CONFLICT`. Without a readable schema the finding is contextual; serializable transactions, locks and handled duplicates are skipped. |
833
- | <a id="floating-promise"></a>`floating-promise` | A promise-returning call is a bare statement in an async function or request handler, or `array.forEach(async ...)` runs awaits nobody waits for. Returning, awaiting, using `void`, or attaching a rejection callback suppresses the bare-call warning. Omitted or nullish callbacks do not handle rejections. Test files and helpers listed under `fireAndForget` in the policy are skipped. |
834
- | <a id="discarded-error-result"></a>`discarded-error-result` | A call discards a typed `fp-ts` `Either` or `neverthrow` `Result`. This includes async calls, standalone `await` and explicit `void`. Check the failure branch or return the result to a caller that handles it. |
835
- | <a id="promise-return-escapes-catch"></a>`promise-return-escapes-catch` | An async function returns a typed promise directly from the `try` block of a `try`/`catch`. A rejection can bypass that catch. Use `return await` when the catch owns the failure. |
836
- | <a id="return-in-finally"></a>`return-in-finally` | A return in `finally` can replace an earlier return value or suppress a thrown error. Keep cleanup in `finally` and return from `try`, `catch`, or after the statement. |
837
- | <a id="return-newline"></a>`return-newline` | A line break immediately after `return` ends the statement before an apparent object or parenthesized return value. Start the expression on the same line as `return`. |
838
- | <a id="drizzle-write-preflight"></a>`drizzle-write-preflight` | An existence check immediately precedes a write on the same key. Review the database constraint or affected-row count alongside the intended error response when requests race. |
839
- | <a id="http-call-without-timeout"></a>`http-call-without-timeout` | A `fetch` or axios call has no `signal` or `timeout`, so a hung upstream holds the request. Set a timeout or an abort signal. |
840
- | <a id="upload-without-size-limit"></a>`upload-without-size-limit` | A multer or Nest upload interceptor has no `limits.fileSize`, so one large upload can exhaust memory. A global `MulterModule.register({ limits })` set elsewhere is not visible to the check. |
841
- | <a id="mongoose-aggregate-uncast-id"></a>`mongoose-aggregate-uncast-id` | A Mongoose `aggregate()` `$match` compares `_id` to a plain string. Aggregation does not cast, so the stage matches nothing; wrap the value in `new Types.ObjectId(id)`. Skipped when a schema declares a String `_id`. |
842
- | <a id="check-then-update-race"></a>`check-then-update-race` | A Mongoose or Sequelize document's numeric field is read, changed in JavaScript and saved without a transaction, losing concurrent updates. |
843
- | <a id="payment-missing-idempotency-key"></a>`payment-missing-idempotency-key` | A Stripe call that moves money has no idempotency key, so a retry can charge or pay out twice. |
844
- | <a id="webhook-missing-idempotency-check"></a>`webhook-missing-idempotency-check` | A webhook route inserts rows without first checking whether the event was already processed. |
845
- | <a id="redis-incr-then-expire"></a>`redis-incr-then-expire` | An `incr`, `incrby` or `hincrby` followed by `expire` or `pexpire` on the same key and client takes two round trips and is not atomic: a crash between them leaves the counter without a TTL. Send both in one `multi()` (with `NX` on Redis 7+) or a Lua script. |
846
- | <a id="retry-without-backoff"></a>`retry-without-backoff` | A network call is retried in a loop, or axios-retry is set up, with no wait between attempts. Add exponential backoff with jitter. axios-retry without `retryDelay` is contextual. |
847
- | <a id="async-route-unhandled-rejection"></a>`async-route-unhandled-rejection` | An async Express 4 route handler awaits outside a try/catch and takes no `next`, so a rejection skips the error middleware and the request hangs. Silent on Express 5 and with express-async-errors, express-async-handler or a wrapping call; an unknown Express version is contextual. Fix (review): wrap the body in try/catch and pass the error to `next`. |
848
- | <a id="async-callback-unhandled-rejection"></a>`async-callback-unhandled-rejection` | An async callback given to `.on`/`.once`, a timer, `process.nextTick` or `cron.schedule` awaits outside a try/catch; nothing handles its promise, so a rejection crashes Node 15+. Fix (review): wrap the body in try/catch that logs the error. |
849
- | <a id="stream-pipe-unhandled-error"></a>`stream-pipe-unhandled-error` | `.pipe()` on a Node stream with no `error` listener and no `pipeline`/`finished` in the function, so a stream error crashes the process or leaks the file and socket. RxJS pipes are skipped; a stream known only by its name is contextual. Fix (review): `await pipeline(...)` from `node:stream/promises`. |
850
- | <a id="json-parse-unguarded"></a>`json-parse-unguarded` | `JSON.parse` of request, queue-message, file, fetch, storage or environment input outside a try/catch. Framework handlers that turn a throw into a 500, and startup parses, are contextual. |
851
- | <a id="request-number-unvalidated"></a>`request-number-unvalidated` | `Number`, `parseInt`, `parseFloat` or unary `+` of raw request input reaches a query, `slice`/`limit`/`skip`/`take`, an index or kept arithmetic with no NaN or range check. Schema-validated values, Nest DTOs and pipes are skipped. Fix (review): a 400 guard after the declaration. |
852
- | <a id="unbounded-promise-all"></a>`unbounded-promise-all` | `Promise.all` runs over an unbounded collection without a concurrency limit (`p-limit`, `pMap`, `PromisePool`, or chunking). |
853
- | <a id="csharp-async-void"></a>`csharp-async-void` | An `async void` method cannot be awaited and can crash the process on unhandled exceptions. Event handlers (`object sender, …EventArgs e`) and `override` methods, which cannot change their return type, are accepted. |
854
- | <a id="sql-insert-truncated-at-semicolon"></a>`sql-insert-truncated-at-semicolon` | An INSERT dump parser ends its captured values at the next semicolon, which can occur inside quoted data. Use a parser for the dump dialect and test a quoted semicolon. |
855
- | <a id="swallowed-error"></a>`swallowed-error` | A JS/TS `catch` block in non-test code is empty, or only calls `console.*`, `logger.*` or `this.logger.*` while the code after the `try` carries on as if it had succeeded. A comment inside the block, an optional `require()` or `import()` probe, a cleanup in a `finally` or `catch` block, and a `try` made only of `close`, `destroy`, `release`-style calls are accepted. A catch that rethrows, returns or records a failure is not reported. |
856
- | <a id="unguarded-boundary-access"></a>`unguarded-boundary-access` | A nested read such as `req.body.user.email`, `JSON.parse(text).a.b` or `response.data.x.y` on untyped input, or on a `find()` / `Map#get` result in files without `strictNullChecks`, throws a TypeError when the value is missing. Reads under optional chaining, a guard (including `map.has(key)` before `map.get(key)`), an early return, an `assert`/`invariant` call or a `try` are accepted; typed values are left to the compiler. The fix adds optional chaining and is marked for review: add a default or answer with a 400, or validate the input first. |
857
- | <a id="assignment-in-condition"></a>`assignment-in-condition` | A condition uses `=` where `===` was probably meant, so it overwrites the variable and tests the assigned value. Doubled parentheses `if ((match = re.exec(text)))`, ternary conditions, calls and loops that read and assign are accepted. |
858
- | <a id="nan-comparison"></a>`nan-comparison` | A value is compared to `NaN` with `==` or `===`, which is never true. Reported only in JavaScript the compiler does not check, since TypeScript reports it otherwise. The fix uses `Number.isNaN` and is marked for review, since the branch starts to run. |
859
- | <a id="invalid-typeof-comparison"></a>`invalid-typeof-comparison` | A `typeof` result is compared to a name it never returns, such as `'strnig'`, so the branch never runs. Reported only in JavaScript the compiler does not check; the fix corrects a close misspelling and is marked for review, since the branch starts to run. |
860
- | <a id="unreachable-code"></a>`unreachable-code` | Statements after `return`, `throw`, `break` or `continue` in the same block never run. Hoisted function declarations and type declarations are accepted, and the rule stays silent when `allowUnreachableCode` is `false` because the compiler reports it. |
861
- | <a id="loop-index-past-length"></a>`loop-index-past-length` | A `for` loop starts at `0`, runs `i <= items.length` and reads `items[i]`, so the last pass reads past the end. Loops starting at `1` are accepted. The fix changes `<=` to `<` and is marked for review. |
862
- | <a id="file-handle-not-closed"></a>`file-handle-not-closed` | A `FileHandle` from `fs/promises` `open()` is not closed in `finally`, so an error before `close()` leaks the file descriptor. Handles that are returned, stored, passed on or turned into a stream are accepted. Confirm nothing else closes it, then close it in `finally` or use `await using`. |
863
- | <a id="query-runner-not-released"></a>`query-runner-not-released` | A TypeORM `createQueryRunner()` is not released in `finally`, so an early return or failed transaction keeps the pooled connection. Confirm no caller releases it, then call `release()` in `finally`. |
864
- | <a id="browser-not-closed"></a>`browser-not-closed` | A Playwright or Puppeteer browser is launched without a `close()` (or `disconnect()` for `puppeteer.connect`) in `finally`, so a failed run leaves the browser process running. Playwright test files, whose fixtures close the browser, are skipped. |
865
- | <a id="interval-not-cleared"></a>`interval-not-cleared` | A `setInterval` in a function outside any frontend lifecycle keeps no handle, or its handle never reaches `clearInterval`, so the timer outlives its owner. Startup code, `unref()` timers and React, Vue, Svelte and Angular files (covered by the frontend cleanup rules) are skipped. Decide who owns the timer and clear it when that owner stops. |
866
- | <a id="python-bare-except"></a>`python-bare-except` | `except:` with no exception type also catches `SystemExit` and `KeyboardInterrupt`. Name the exceptions the block handles. A block that ends in a bare `raise` is accepted. Reported by `loadwise rel polyglot`. |
867
- | <a id="python-swallowed-exception"></a>`python-swallowed-exception` | `except Exception` or `except BaseException` (alone or in a tuple) whose body is only `pass` or `...` makes every failure disappear. Narrow types such as `FileNotFoundError` or `KeyError` with `pass` are accepted as deliberate. |
868
- | <a id="go-error-discarded"></a>`go-error-discarded` | An error result is dropped with `_`: `value, _ := f()` for calls known to return `(T, error)` (the `os`, `io`, `strconv`, `json`, `sql` and `net` packages, `http.Get`, `url.Parse`, `time.Parse`, and methods such as `Marshal`, `ReadAll`, `Atoi`, `Query`, `Decode`), or `_ = w.Write(...)` and similar write, flush, sync, encode, exec and commit calls. Calls whose second result is a bool, such as `os.LookupEnv`, `cache.Get` or `q.Pop()`, and explicit `_ = x.Close()` or `_ = tx.Rollback()` are accepted. |
869
- | <a id="go-defer-before-error-check"></a>`go-defer-before-error-check` | `defer resp.Body.Close()`, or `defer rows.Close()` after `Query`/`QueryContext`, runs before `err` is checked, so a failed call defers `Close` on a nil value and panics. `os.Open` files are accepted, since `Close` on a nil `*os.File` returns an error instead. |
870
- | <a id="java-resource-without-try"></a>`java-resource-without-try` | A stream, reader, writer or JDBC connection is opened outside try-with-resources and not closed by a later `try`/`finally`, returned or stored, so an exception leaks it. |
871
- | <a id="csharp-disposable-without-using"></a>`csharp-disposable-without-using` | A stream or database connection is created without `using`, so an exception skips `Dispose()`. Variables that are returned, stored, handed to another object or disposed in a later `finally` are accepted. |
872
- | <a id="rust-unwrap-in-production"></a>`rust-unwrap-in-production` | `.unwrap()` in non-test code panics on `None` or `Err`. Test modules, `static`/`const` items and lock guards are accepted. Handle the case or use `expect` with the invariant that makes it safe. |
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.
629
+
630
+ <!-- loadwise:rules:start checker=reliability group=source-rules -->
631
+
632
+ | Rule | Impact | What it flags |
633
+ | --------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
634
+ | <a id="assignment-in-condition"></a>[`assignment-in-condition`](docs/rules/assignment-in-condition.md) | high | A condition assigns with = where a comparison was probably meant. |
635
+ | <a id="async-callback-unhandled-rejection"></a>[`async-callback-unhandled-rejection`](docs/rules/async-callback-unhandled-rejection.md) | high | An async callback given to an event emitter, timer or scheduler has no error handling, so a rejection is unhandled. |
636
+ | <a id="async-route-unhandled-rejection"></a>[`async-route-unhandled-rejection`](docs/rules/async-route-unhandled-rejection.md) | high | An Express 4 async route handler has no error handling, so a rejection never reaches the error middleware. |
637
+ | <a id="browser-not-closed"></a>[`browser-not-closed`](docs/rules/browser-not-closed.md) | high | A Playwright or Puppeteer browser is not closed in a finally block, so an error leaves the process running. |
638
+ | <a id="check-then-update-race"></a>[`check-then-update-race`](docs/rules/check-then-update-race.md) | high | A Mongoose or Sequelize document's numeric field is read, changed in JavaScript and saved without a transaction, losing concurrent updates. |
639
+ | <a id="child-process-without-error-listener"></a>[`child-process-without-error-listener`](docs/rules/child-process-without-error-listener.md) | high | A spawned child process has no 'error' listener, so a failed spawn crashes the parent process. |
640
+ | <a id="csharp-async-void"></a>[`csharp-async-void`](docs/rules/csharp-async-void.md) | high | An async void method cannot be awaited and can crash the process on unhandled exceptions. |
641
+ | <a id="csharp-disposable-without-using"></a>[`csharp-disposable-without-using`](docs/rules/csharp-disposable-without-using.md) | medium | A C# stream, connection or other IDisposable is created without using, so an exception leaks it. |
642
+ | <a id="discarded-error-result"></a>[`discarded-error-result`](docs/rules/discarded-error-result.md) | high | A call discards a typed Either or Result that can carry a failure as a value. |
643
+ | <a id="drizzle-unfiltered-write"></a>[`drizzle-unfiltered-write`](docs/rules/drizzle-unfiltered-write.md) | critical | A Drizzle update or delete executes without an effective where clause. |
644
+ | <a id="drizzle-write-preflight"></a>[`drizzle-write-preflight`](docs/rules/drizzle-write-preflight.md) | medium | A separate existence check before a Drizzle write can race with another request. |
645
+ | <a id="error-logged-without-stack"></a>[`error-logged-without-stack`](docs/rules/error-logged-without-stack.md) | low | A catch block logs only error.message and carries on, so the stack trace is lost. |
646
+ | <a id="error-rethrown-without-cause"></a>[`error-rethrown-without-cause`](docs/rules/error-rethrown-without-cause.md) | low | A catch block throws a new error without the caught one, so the original message and stack are lost. |
647
+ | <a id="file-handle-not-closed"></a>[`file-handle-not-closed`](docs/rules/file-handle-not-closed.md) | high | A FileHandle from fs/promises open() is not closed on every path, leaking a file descriptor. |
648
+ | <a id="find-then-create-race"></a>[`find-then-create-race`](docs/rules/find-then-create-race.md) | high | A lookup by key is followed by an insert with that key, with no unique constraint to stop duplicates. |
649
+ | <a id="floating-promise"></a>[`floating-promise`](docs/rules/floating-promise.md) | high | A promise-returning call is neither awaited, returned nor handled, so its failure goes unseen. |
650
+ | <a id="go-defer-before-error-check"></a>[`go-defer-before-error-check`](docs/rules/go-defer-before-error-check.md) | high | A Go defer closes a resource before its error is checked, so a failed open dereferences nil. |
651
+ | <a id="go-error-discarded"></a>[`go-error-discarded`](docs/rules/go-error-discarded.md) | high | A Go error result is assigned to the blank identifier and never checked. |
652
+ | <a id="http-call-without-timeout"></a>[`http-call-without-timeout`](docs/rules/http-call-without-timeout.md) | high | A fetch or axios call has no timeout or abort signal. |
653
+ | <a id="interval-not-cleared"></a>[`interval-not-cleared`](docs/rules/interval-not-cleared.md) | medium | A setInterval handle is discarded or never cleared, so the timer outlives its owner. |
654
+ | <a id="invalid-typeof-comparison"></a>[`invalid-typeof-comparison`](docs/rules/invalid-typeof-comparison.md) | high | A typeof result is compared to a string typeof never returns, so the check never matches. |
655
+ | <a id="java-resource-without-try"></a>[`java-resource-without-try`](docs/rules/java-resource-without-try.md) | high | A Java stream, reader or connection is opened outside try-with-resources, so an exception leaks it. |
656
+ | <a id="json-parse-unguarded"></a>[`json-parse-unguarded`](docs/rules/json-parse-unguarded.md) | medium | JSON.parse runs on outside input with no try/catch, so malformed input throws where it is not handled. |
657
+ | <a id="loop-index-past-length"></a>[`loop-index-past-length`](docs/rules/loop-index-past-length.md) | high | A loop runs its index up to and including length, so the last pass reads past the end. |
658
+ | <a id="mongoose-aggregate-uncast-id"></a>[`mongoose-aggregate-uncast-id`](docs/rules/mongoose-aggregate-uncast-id.md) | high | A Mongoose aggregate $match compares _id to an uncast string instead of an ObjectId. |
659
+ | <a id="nan-comparison"></a>[`nan-comparison`](docs/rules/nan-comparison.md) | high | A value is compared to NaN with an equality operator, which is never true. |
660
+ | <a id="next-server-env-in-client"></a>[`next-server-env-in-client`](docs/rules/next-server-env-in-client.md) | high | A 'use client' file reads a process.env variable without the NEXT_PUBLIC_ prefix, so it is unavailable in the browser by default. |
661
+ | <a id="payment-missing-idempotency-key"></a>[`payment-missing-idempotency-key`](docs/rules/payment-missing-idempotency-key.md) | high | A Stripe call that moves money has no idempotency key, so a retry can charge or pay out twice. |
662
+ | <a id="pg-transaction-on-pool"></a>[`pg-transaction-on-pool`](docs/rules/pg-transaction-on-pool.md) | critical | A transaction statement is sent to a pool, so its statements can run on different connections. |
663
+ | <a id="pool-without-connection-timeout"></a>[`pool-without-connection-timeout`](docs/rules/pool-without-connection-timeout.md) | medium | A pg Pool or Client sets no connectionTimeoutMillis, so its default of 0 waits for a connection forever. |
664
+ | <a id="prisma-dependent-writes"></a>[`prisma-dependent-writes`](docs/rules/prisma-dependent-writes.md) | high | Adjacent Prisma creates pass a value from the first record into the next write. |
665
+ | <a id="prisma-read-modify-write"></a>[`prisma-read-modify-write`](docs/rules/prisma-read-modify-write.md) | critical | A Prisma read feeds a numeric update of the same row, losing concurrent updates. |
666
+ | <a id="prisma-transaction-client-escape"></a>[`prisma-transaction-client-escape`](docs/rules/prisma-transaction-client-escape.md) | critical | A Prisma call inside an interactive transaction uses the outer client instead of the transaction client. |
667
+ | <a id="promise-return-escapes-catch"></a>[`promise-return-escapes-catch`](docs/rules/promise-return-escapes-catch.md) | high | Returning a promise directly from a protected try block can bypass its catch on rejection. |
668
+ | <a id="python-bare-except"></a>[`python-bare-except`](docs/rules/python-bare-except.md) | medium | A bare except also catches SystemExit and KeyboardInterrupt, hiding shutdowns and bugs. |
669
+ | <a id="python-swallowed-exception"></a>[`python-swallowed-exception`](docs/rules/python-swallowed-exception.md) | medium | A Python except block only passes, so the failure is dropped silently. |
670
+ | <a id="query-runner-not-released"></a>[`query-runner-not-released`](docs/rules/query-runner-not-released.md) | critical | A TypeORM QueryRunner is not released in a finally block, so an error leaks its pooled connection. |
671
+ | <a id="react-async-effect-callback"></a>[`react-async-effect-callback`](docs/rules/react-async-effect-callback.md) | medium | An async function is passed to useEffect, so its promise is treated as the cleanup function and its errors go unhandled. |
672
+ | <a id="react-effect-sets-state-every-render"></a>[`react-effect-sets-state-every-render`](docs/rules/react-effect-sets-state-every-render.md) | high | An effect with no dependency array sets state to a new value on every run, so the component re-renders forever. |
673
+ | <a id="react-list-missing-key"></a>[`react-list-missing-key`](docs/rules/react-list-missing-key.md) | medium | An element or fragment returned from .map() has no key prop, so React cannot track items when the list changes. |
674
+ | <a id="react-state-mutated-in-place"></a>[`react-state-mutated-in-place`](docs/rules/react-state-mutated-in-place.md) | high | A useState value is mutated in place and passed to its own setter, so React sees the same reference and skips the re-render. |
675
+ | <a id="redis-incr-then-expire"></a>[`redis-incr-then-expire`](docs/rules/redis-incr-then-expire.md) | medium | A Redis counter increment and its expire on the same key are two round trips and not atomic. |
676
+ | <a id="request-number-unvalidated"></a>[`request-number-unvalidated`](docs/rules/request-number-unvalidated.md) | medium | A number parsed from request input reaches a query or calculation with no NaN or range check. |
677
+ | <a id="retry-without-backoff"></a>[`retry-without-backoff`](docs/rules/retry-without-backoff.md) | medium | A retry loop calls the network again with no delay between attempts. |
678
+ | <a id="return-in-finally"></a>[`return-in-finally`](docs/rules/return-in-finally.md) | high | Returning from finally can replace a pending return value or suppress a thrown error. |
679
+ | <a id="return-newline"></a>[`return-newline`](docs/rules/return-newline.md) | high | A line break after return ends the statement before the apparent return value. |
680
+ | <a id="rust-unwrap-in-production"></a>[`rust-unwrap-in-production`](docs/rules/rust-unwrap-in-production.md) | medium | Rust code outside tests calls unwrap(), turning an Err or None into a panic. |
681
+ | <a id="sql-insert-truncated-at-semicolon"></a>[`sql-insert-truncated-at-semicolon`](docs/rules/sql-insert-truncated-at-semicolon.md) | high | A SQL dump parser ends INSERT values at a semicolon inside quoted text. |
682
+ | <a id="stream-pipe-unhandled-error"></a>[`stream-pipe-unhandled-error`](docs/rules/stream-pipe-unhandled-error.md) | high | A stream is piped with .pipe() and no error handling, so a stream error can crash the process or leak the file. |
683
+ | <a id="swallowed-error"></a>[`swallowed-error`](docs/rules/swallowed-error.md) | medium | A catch block drops the error and the code after the try carries on as if it succeeded. |
684
+ | <a id="switch-not-exhaustive"></a>[`switch-not-exhaustive`](docs/rules/switch-not-exhaustive.md) | medium | A switch over a union or enum has no default and misses members, so the missing value leaves the result undefined. |
685
+ | <a id="throw-non-error"></a>[`throw-non-error`](docs/rules/throw-non-error.md) | medium | A string, number or object literal is thrown instead of an Error, so there is no stack trace. |
686
+ | <a id="typeorm-transaction-client-escape"></a>[`typeorm-transaction-client-escape`](docs/rules/typeorm-transaction-client-escape.md) | critical | A write inside a TypeORM transaction goes through a repository not bound to it. |
687
+ | <a id="unbounded-promise-all"></a>[`unbounded-promise-all`](docs/rules/unbounded-promise-all.md) | high | Promise.all runs over an unbounded collection without a concurrency limit, risking memory spikes or downstream saturation. |
688
+ | <a id="uncaught-exception-continues"></a>[`uncaught-exception-continues`](docs/rules/uncaught-exception-continues.md) | high | An uncaughtException handler neither exits nor rethrows, so the process keeps running in an undefined state. |
689
+ | <a id="unguarded-boundary-access"></a>[`unguarded-boundary-access`](docs/rules/unguarded-boundary-access.md) | medium | A nested property is read from outside input or a lookup that can be missing, so absent data throws a TypeError. |
690
+ | <a id="unreachable-code"></a>[`unreachable-code`](docs/rules/unreachable-code.md) | medium | Statements follow a return, throw, break or continue in the same block and never run. |
691
+ | <a id="upload-without-size-limit"></a>[`upload-without-size-limit`](docs/rules/upload-without-size-limit.md) | high | A multer or Nest upload interceptor has no file size limit. |
692
+ | <a id="webhook-missing-idempotency-check"></a>[`webhook-missing-idempotency-check`](docs/rules/webhook-missing-idempotency-check.md) | medium | A webhook route inserts rows without first checking whether the event was already processed. |
693
+
694
+ <!-- loadwise:rules:end -->
873
695
 
874
696
  ## Migration safety
875
697
 
876
698
  `npx loadwise rel migrations` reads Prisma, Drizzle, TypeORM, Knex and Sequelize migrations (SQL or code) and flags statements that lock or rewrite a table. It reads files only. `--dialect postgres|mysql` selects the rule set, `--json` for structured output and `--ignore RULE` to skip a rule. The older `loadwise perf migrations` and `loadwise perf contracts` still work and print a note pointing to `rel`.
877
699
 
878
- | Rule | What it flags |
879
- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
880
- | <a id="migration-index-not-concurrent"></a><a id="migration-concurrent-in-transaction"></a>`migration-index-not-concurrent`, `migration-concurrent-in-transaction` | A PostgreSQL index built without `CONCURRENTLY`, or `CONCURRENTLY` inside a transaction that cannot run it. |
881
- | <a id="migration-not-null-without-default"></a><a id="migration-volatile-default"></a>`migration-not-null-without-default`, `migration-volatile-default` | A NOT NULL column added without a default (fails once rows exist), or a volatile default that rewrites the table. |
882
- | <a id="migration-column-type-rewrite"></a><a id="migration-table-rewrite-command"></a>`migration-column-type-rewrite`, `migration-table-rewrite-command` | A column type change or command (`VACUUM FULL`, `CLUSTER`, `REINDEX`) that rewrites the table. |
883
- | <a id="migration-set-not-null-scan"></a><a id="migration-constraint-not-valid"></a><a id="migration-constraint-without-index"></a>`migration-set-not-null-scan`, `migration-constraint-not-valid`, `migration-constraint-without-index` | Full-table validation scans, constraints that should be added `NOT VALID` first, and constraints that build an index while blocking writes. |
884
- | <a id="migration-breaking-drop"></a><a id="migration-breaking-rename"></a>`migration-breaking-drop`, `migration-breaking-rename` | Dropping or renaming a column or table that running application code may still use. |
885
- | <a id="migration-missing-lock-timeout"></a>`migration-missing-lock-timeout` | A locking statement with no `lock_timeout`. |
886
- | <a id="migration-mysql-table-copy"></a><a id="migration-mysql-lock-unspecified"></a>`migration-mysql-table-copy`, `migration-mysql-lock-unspecified` | MySQL changes that copy the table or leave the lock level unspecified. |
887
- | <a id="migration-unparsed"></a>`migration-unparsed` | A statement the checker could not read. Review it by hand. |
888
-
889
- Only new migrations fail the run. Older migrations are contextual: counted, listed with `--include-contextual`, and never exit 1.
890
-
891
- **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.
700
+ <!-- loadwise:rules:start checker=reliability group=migration-safety -->
701
+
702
+ | Rule | Impact | What it flags |
703
+ | ------------------------------------------------------------------------------------------------------------------------------------------ | -------- | -------------------------------------------------------------------------------------- |
704
+ | <a id="migration-breaking-drop"></a>[`migration-breaking-drop`](docs/rules/migration-breaking-drop.md) | critical | A migration drops a column or table that running code may still use. |
705
+ | <a id="migration-breaking-rename"></a>[`migration-breaking-rename`](docs/rules/migration-breaking-rename.md) | high | A migration renames a column or table that running code may still use. |
706
+ | <a id="migration-column-type-rewrite"></a>[`migration-column-type-rewrite`](docs/rules/migration-column-type-rewrite.md) | critical | A migration changes a column type in a way that rewrites the table. |
707
+ | <a id="migration-concurrent-in-transaction"></a>[`migration-concurrent-in-transaction`](docs/rules/migration-concurrent-in-transaction.md) | high | A CONCURRENTLY index statement runs inside a transaction, where PostgreSQL rejects it. |
708
+ | <a id="migration-constraint-not-valid"></a>[`migration-constraint-not-valid`](docs/rules/migration-constraint-not-valid.md) | high | A constraint is added and validated in one step instead of NOT VALID first. |
709
+ | <a id="migration-constraint-without-index"></a>[`migration-constraint-without-index`](docs/rules/migration-constraint-without-index.md) | high | A unique or primary key constraint builds its index while blocking writes. |
710
+ | <a id="migration-index-not-concurrent"></a>[`migration-index-not-concurrent`](docs/rules/migration-index-not-concurrent.md) | critical | A PostgreSQL index is built without CONCURRENTLY, blocking writes to the table. |
711
+ | <a id="migration-missing-lock-timeout"></a>[`migration-missing-lock-timeout`](docs/rules/migration-missing-lock-timeout.md) | high | A migration statement takes a lock with no lock_timeout set. |
712
+ | <a id="migration-mysql-lock-unspecified"></a>[`migration-mysql-lock-unspecified`](docs/rules/migration-mysql-lock-unspecified.md) | high | A MySQL ALTER does not state its LOCK level. |
713
+ | <a id="migration-mysql-table-copy"></a>[`migration-mysql-table-copy`](docs/rules/migration-mysql-table-copy.md) | critical | A MySQL ALTER copies the whole table. |
714
+ | <a id="migration-not-null-without-default"></a>[`migration-not-null-without-default`](docs/rules/migration-not-null-without-default.md) | high | A NOT NULL column is added without a default, which fails once rows exist. |
715
+ | <a id="migration-set-not-null-scan"></a>[`migration-set-not-null-scan`](docs/rules/migration-set-not-null-scan.md) | high | SET NOT NULL scans the whole table while holding a lock. |
716
+ | <a id="migration-table-rewrite-command"></a>[`migration-table-rewrite-command`](docs/rules/migration-table-rewrite-command.md) | critical | A migration runs VACUUM FULL, CLUSTER or REINDEX, which rewrites or locks the table. |
717
+ | <a id="migration-unparsed"></a>[`migration-unparsed`](docs/rules/migration-unparsed.md) | low | A migration statement could not be parsed and needs a manual review. |
718
+ | <a id="migration-volatile-default"></a>[`migration-volatile-default`](docs/rules/migration-volatile-default.md) | high | A column is added with a volatile default, which rewrites the table. |
719
+
720
+ <!-- loadwise:rules:end -->
721
+
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:
892
723
 
893
724
  ```sh
894
- npx loadwise rel migrations --changed-since origin/main
895
- ```
896
-
897
- **Baseline workflow.** For a project with existing migrations, accept them once and enforce the rest.
898
-
899
- ```sh
900
- 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
901
726
  npx loadwise rel migrations # new migrations fail; baselined ones do not
902
727
  ```
903
728
 
904
- Commit the baseline. `--baseline FILE` reads or writes another path. Exit codes match the source checks: 0 passed, 1 findings in enforced migrations, 2 invalid input.
729
+ `--baseline FILE` reads or writes another path. Exit codes: 0 passed, 1 findings in enforced migrations, 2 invalid input.
905
730
 
906
731
  ## API contract safety
907
732
 
908
- `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 performance report. Both commands respect workspace selection, ignored paths and rules, configured rule levels, and minimum impact. Visible breaking changes fail by default. Rules set to warn appear in the report and do not fail the check. Invalid input exits 2. Use a full-history checkout (`fetch-depth: 0`) so the ref resolves.
909
-
910
- It compares three kinds of source:
911
-
912
- - **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.
913
- - **GraphQL SDL** (`*.graphql`, `*.gql`, for example the `schema.gql` a code-first server emits). Query documents are skipped.
914
- - **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.
915
-
916
- | Rule | What it flags |
917
- | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
918
- | <a id="api-removed-operation"></a>`api-removed-operation` | An OpenAPI path and method, or a GraphQL `Query`, `Mutation` or `Subscription` field, that no longer exists. |
919
- | <a id="api-removed-field"></a>`api-removed-field` | A response field, GraphQL type, field, argument or union member, or a DTO property returned to clients, that was removed. |
920
- | <a id="api-required-input"></a>`api-required-input` | A request field, parameter, GraphQL argument or input field that is new and required, or changed from optional to required. |
921
- | <a id="api-type-changed"></a>`api-type-changed` | A field or parameter whose type changed, or a GraphQL type that became nullable (output) or non-null (input). |
922
- | <a id="api-enum-value-removed"></a>`api-enum-value-removed` | An enum value or string-literal option that requests (or, in GraphQL, any client) can no longer use. |
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.
923
734
 
924
- 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.
735
+ <!-- loadwise:rules:start checker=reliability group=api-contract-safety -->
925
736
 
926
- ```sh
927
- npx loadwise rel contracts --changed-since origin/main
928
- npx loadwise check --changed-since origin/main
929
- ```
930
-
931
- ## Impact levels
737
+ | Rule | Impact | What it flags |
738
+ | --------------------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------ |
739
+ | <a id="api-enum-value-removed"></a>[`api-enum-value-removed`](docs/rules/api-enum-value-removed.md) | high | An enum value or string-literal option that clients could send was removed. |
740
+ | <a id="api-removed-field"></a>[`api-removed-field`](docs/rules/api-removed-field.md) | high | A response field, GraphQL type, field, argument or union member, or returned DTO property was removed. |
741
+ | <a id="api-removed-operation"></a>[`api-removed-operation`](docs/rules/api-removed-operation.md) | critical | An OpenAPI operation or a GraphQL Query, Mutation or Subscription field was removed. |
742
+ | <a id="api-required-input"></a>[`api-required-input`](docs/rules/api-required-input.md) | high | A request field, parameter or GraphQL argument is new and required, or became required. |
743
+ | <a id="api-type-changed"></a>[`api-type-changed`](docs/rules/api-type-changed.md) | high | A field or parameter changed type, or a GraphQL type changed nullability in a breaking direction. |
932
744
 
933
- 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 this table.
934
-
935
- | Rule | Impact |
936
- | ------------------------------------- | -------- |
937
- | `api-removed-operation` | critical |
938
- | `drizzle-unfiltered-write` | critical |
939
- | `migration-breaking-drop` | critical |
940
- | `migration-column-type-rewrite` | critical |
941
- | `migration-index-not-concurrent` | critical |
942
- | `migration-mysql-table-copy` | critical |
943
- | `migration-table-rewrite-command` | critical |
944
- | `pg-transaction-on-pool` | critical |
945
- | `prisma-read-modify-write` | critical |
946
- | `prisma-transaction-client-escape` | critical |
947
- | `query-runner-not-released` | critical |
948
- | `typeorm-transaction-client-escape` | critical |
949
- | `api-enum-value-removed` | high |
950
- | `api-removed-field` | high |
951
- | `api-required-input` | high |
952
- | `api-type-changed` | high |
953
- | `assignment-in-condition` | high |
954
- | `async-callback-unhandled-rejection` | high |
955
- | `async-route-unhandled-rejection` | high |
956
- | `browser-not-closed` | high |
957
- | `check-then-update-race` | high |
958
- | `csharp-async-void` | high |
959
- | `discarded-error-result` | high |
960
- | `file-handle-not-closed` | high |
961
- | `find-then-create-race` | high |
962
- | `floating-promise` | high |
963
- | `go-defer-before-error-check` | high |
964
- | `go-error-discarded` | high |
965
- | `http-call-without-timeout` | high |
966
- | `invalid-typeof-comparison` | high |
967
- | `java-resource-without-try` | high |
968
- | `loop-index-past-length` | high |
969
- | `migration-breaking-rename` | high |
970
- | `migration-concurrent-in-transaction` | high |
971
- | `migration-constraint-not-valid` | high |
972
- | `migration-constraint-without-index` | high |
973
- | `migration-missing-lock-timeout` | high |
974
- | `migration-mysql-lock-unspecified` | high |
975
- | `migration-not-null-without-default` | high |
976
- | `migration-set-not-null-scan` | high |
977
- | `migration-volatile-default` | high |
978
- | `mongoose-aggregate-uncast-id` | high |
979
- | `nan-comparison` | high |
980
- | `payment-missing-idempotency-key` | high |
981
- | `prisma-dependent-writes` | high |
982
- | `promise-return-escapes-catch` | high |
983
- | `return-in-finally` | high |
984
- | `return-newline` | high |
985
- | `sql-insert-truncated-at-semicolon` | high |
986
- | `stream-pipe-unhandled-error` | high |
987
- | `unbounded-promise-all` | high |
988
- | `upload-without-size-limit` | high |
989
- | `csharp-disposable-without-using` | medium |
990
- | `drizzle-write-preflight` | medium |
991
- | `interval-not-cleared` | medium |
992
- | `json-parse-unguarded` | medium |
993
- | `python-bare-except` | medium |
994
- | `python-swallowed-exception` | medium |
995
- | `redis-incr-then-expire` | medium |
996
- | `request-number-unvalidated` | medium |
997
- | `retry-without-backoff` | medium |
998
- | `rust-unwrap-in-production` | medium |
999
- | `swallowed-error` | medium |
1000
- | `unguarded-boundary-access` | medium |
1001
- | `unreachable-code` | medium |
1002
- | `webhook-missing-idempotency-check` | medium |
1003
- | `migration-unparsed` | low |
745
+ <!-- loadwise:rules:end -->
1004
746
 
1005
747
  # Maintainability checker
1006
748
 
1007
- `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 structured output.
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).
1008
750
 
1009
751
  ## What gets checked
1010
752
 
1011
- | Rule | Evidence |
1012
- | ----------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1013
- | <a id="deep-control-flow"></a>`deep-control-flow` | Four nested control structures. JS/TS reports the deepest site in each function. The other parsers report threshold crossings in supported conditional and loop bodies. Independent function scopes start fresh. |
1014
- | <a id="high-branch-complexity"></a>`high-branch-complexity` | A JS/TS function reaches a score of 15. Start at one and count each conditional, loop, switch, catch or ternary. A flat switch contributes one decision. When most of a function's decisions are plain bail-outs (an `if` with no `else` that only returns, throws, continues or breaks, at the top of the body), up to twelve of them count half toward the 15, so a long run of independent guards is not reported on its own. The reported score is still the plain count. |
1015
- | <a id="duplicate-implementation"></a>`duplicate-implementation` | Substantial functions share a verified implementation. The report groups matching sites so a reviewer can compare their contracts before introducing a shared abstraction. JS/TS compares syntax while preserving identifiers, literals and operations. Python, Go, Java, C# and Rust compare exact body text of named functions selected by the parser. This deliberately misses reformatted or renamed copies. |
1016
- | <a id="dependency-cycle"></a>`dependency-cycle` | An eager internal dependency path returns to its starting module. One ordered example path is shown per strongly connected component. Deferred loads can still be checked against folder boundaries. |
1017
- | <a id="folder-boundary"></a><a id="file-placement"></a>`folder-boundary` and `file-placement` | An import crosses a boundary declared by the team, or a filename suffix occurs outside its allowed folders. Both policies are opt-in. |
1018
- | <a id="data-access-boundary"></a>`data-access-boundary` | A JS/TS file outside the approved paths imports a configured database driver or ORM module at runtime. Static imports, re-exports, `import x = require()`, literal dynamic imports and unshadowed `require()` calls are checked. The policy is opt-in via `dataAccess`. |
1019
- | <a id="query-mutates-state"></a>`query-mutates-state` | A JS/TS class instance method marked `/** @maintainabilityQuery */` writes directly through `this`. Assignments, increments, deletes and destructuring writes are covered. Mutations through aliases or arbitrary helper calls require review. |
1020
- | <a id="unused-export"></a><a id="unreferenced-file"></a>`unused-export` and `unreferenced-file` | An export no scanned file imports, and a source file nothing imports that is not an entry point. Static, type-only, `require()`, literal dynamic imports, `export … from` and `export *` count as use. An unshadowed `new Worker(new URL('./worker.ts', import.meta.url))` or `SharedWorker` counts as loading the file. A namespace import or `require()` uses the whole module. Deep imports by package name from sibling workspace members count as use of the names they import. When the scanned folder's own config has no `paths`, the aliases of an ancestor `tsconfig.json` or `jsconfig.json` that covers it resolve imports. Entry points are `package.json` `main`, `module`, `bin`, `exports` and script paths (also from a `package.json` above the scanned folder, mapped onto the scanned source), literal Node commands in GitHub Actions job steps, local script references in HTML, `nest-cli.json` entry files, `project.json` commands, `tsconfig` `files`, tests, scripts, configuration, migrations, entities, seeds, route folders (`pages/`, `routes/`, and `app/` in Next or Remix projects) and `main`/`index` files at a package root. A non-literal `import()` or `require()` makes findings contextual, project-wide when the specifier is unknown and for one folder when it starts with a relative path. Skipped in `--staged` and `--changed-since` runs, which do not see the whole project. When adopting loadwise on an existing codebase, record the current findings once with `loadwise check --write-baseline` and check with `--baseline`, so only new unused exports and files are reported. |
1021
- | <a id="large-module"></a>`large-module` | A JS/TS file has more than 600 lines of code, not counting comments and blank lines. Generated and test files are skipped. Override with `limits.largeModuleLines`. |
1022
- | <a id="large-class"></a>`large-class` | A class has more than 30 methods, accessors, constructors or function-valued fields. Plain data properties (entities, DTOs) are not counted. Override with `limits.largeClassMembers`. |
1023
- | <a id="long-parameter-list"></a>`long-parameter-list` | A function with a body takes more than 5 positional parameters. A destructured object counts as one. Constructors with decorators or parameter properties (dependency injection lists) and parameters with decorators (`@Body()`, `@Param()`) are not counted. Override with `limits.longParameterCount`. |
1024
- | <a id="unused-import"></a>`unused-import` | An imported name is never used in the file. Type positions, `typeof`, re-exports, decorators, JSDoc references and the `React` import under the classic JSX runtime count as use, and side-effect imports are never reported. Skipped when `noUnusedLocals` is on, since the compiler reports it, when an eslint-disable comment names `no-unused-vars` or `@typescript-eslint/no-unused-vars`, and in codemod `*.input` / `*.output` fixtures, fixture folders, docs, examples, vendored code and assets. The fix removes the name; removing a whole declaration is marked for review because the module may have side effects. |
1025
- | <a id="unused-local-variable"></a>`unused-local-variable` | A `const`, `let` or `var` is declared and never read. Names starting with `_`, destructuring (rest siblings omit keys on purpose), loop and catch variables, exports and files using `eval` or `with` are skipped, as is the whole rule when `noUnusedLocals` is on, a variable under an eslint-disable comment for `no-unused-vars` or `@typescript-eslint/no-unused-vars`, and codemod `*.input` / `*.output` fixtures, fixture folders, docs, examples, vendored code and assets. The fix deletes the declaration only when its initializer has no side effects. |
1026
- | <a id="stray-console"></a>`stray-console` | A `console.*` call in server or Node code, as the execution context classifies it, writes unleveled, unstructured output. Browser and frontend files, CLI scripts (a shebang or `process.argv`), vendored or bundled libraries, stories, playgrounds, docs, examples and fixtures, calls under an eslint-disable comment for `no-console`, and a call directly followed by `process.exit` or `throw` are skipped, as are tests, configuration, seeds, migrations, logger implementations, development-only guards, last-resort `uncaughtException` handlers and error boundaries. When the file already has a `logger` (or a Nest `this.logger`), the fix routes the call through it and is marked for review. |
1027
- | <a id="deprecated-node-api"></a>`deprecated-node-api` | `new Buffer()` (use `Buffer.alloc` or `Buffer.from`), `url.parse()` (use `new URL()`) or `fs.exists()` (use `fs.access` or `existsSync`). The `Buffer` fix applies to literal arguments; the `url.parse` fix is marked for review because relative input throws and the result has no `path`, `auth` or `query`. |
1028
-
1029
- JS and TS source checks use the TypeScript parser. The optional ast-grep executable supplies native parsers for Python, Go, Java, C#, Rust, PHP, Ruby, Kotlin, C and C++. The nesting rule recognizes specific grammar constructs. Braceless forms and pattern-matching constructs have different coverage across languages. A `.h` file uses the C grammar. Use a C++ header extension for C++ grammar.
1030
-
1031
- 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.
753
+ <!-- loadwise:rules:start checker=maintainability group=what-gets-checked -->
754
+
755
+ | Rule | Impact | What it flags |
756
+ | ------------------------------------------------------------------------------------------------------------------------ | ------ | ----------------------------------------------------------------------------------------------- |
757
+ | <a id="data-access-boundary"></a>[`data-access-boundary`](docs/rules/data-access-boundary.md) | medium | A file outside the approved paths imports a configured database driver or ORM. |
758
+ | <a id="deep-control-flow"></a>[`deep-control-flow`](docs/rules/deep-control-flow.md) | low | Control structures are nested four levels deep. |
759
+ | <a id="dependency-cycle"></a>[`dependency-cycle`](docs/rules/dependency-cycle.md) | high | An eager chain of internal imports leads back to the module it started from. |
760
+ | <a id="deprecated-node-api"></a>[`deprecated-node-api`](docs/rules/deprecated-node-api.md) | medium | A deprecated Node.js API is used: new Buffer(), url.parse() or fs.exists(). |
761
+ | <a id="double-type-assertion"></a>[`double-type-assertion`](docs/rules/double-type-assertion.md) | low | A value is cast through unknown or any to a second type, bypassing the type checker. |
762
+ | <a id="duplicate-implementation"></a>[`duplicate-implementation`](docs/rules/duplicate-implementation.md) | medium | Substantial functions share the same implementation. |
763
+ | <a id="file-placement"></a>[`file-placement`](docs/rules/file-placement.md) | low | A file with a configured suffix sits outside its allowed folders. |
764
+ | <a id="focused-test-committed"></a>[`focused-test-committed`](docs/rules/focused-test-committed.md) | medium | A committed .only, fit or fdescribe makes the test runner skip every other test. |
765
+ | <a id="folder-boundary"></a>[`folder-boundary`](docs/rules/folder-boundary.md) | medium | An import crosses a folder boundary the team declared. |
766
+ | <a id="high-branch-complexity"></a>[`high-branch-complexity`](docs/rules/high-branch-complexity.md) | medium | A function reaches a branch complexity score of 15. |
767
+ | <a id="large-class"></a>[`large-class`](docs/rules/large-class.md) | low | A class has more than 30 methods, accessors, constructors or function-valued fields. |
768
+ | <a id="large-module"></a>[`large-module`](docs/rules/large-module.md) | low | A file has more than 600 lines of code. |
769
+ | <a id="long-parameter-list"></a>[`long-parameter-list`](docs/rules/long-parameter-list.md) | low | A function takes more than 5 positional parameters. |
770
+ | <a id="query-mutates-state"></a>[`query-mutates-state`](docs/rules/query-mutates-state.md) | medium | A method marked @maintainabilityQuery writes through this. |
771
+ | <a id="stray-console"></a>[`stray-console`](docs/rules/stray-console.md) | low | A console call in production code bypasses the logger, so its output has no level or structure. |
772
+ | <a id="ts-suppression-without-reason"></a>[`ts-suppression-without-reason`](docs/rules/ts-suppression-without-reason.md) | low | A @ts-ignore, @ts-expect-error or @ts-nocheck directive has no explanation. |
773
+ | <a id="tsconfig-strict-disabled"></a>[`tsconfig-strict-disabled`](docs/rules/tsconfig-strict-disabled.md) | medium | A tsconfig turns off strict type checking. |
774
+ | <a id="unreferenced-file"></a>[`unreferenced-file`](docs/rules/unreferenced-file.md) | low | A source file that nothing imports and that is not an entry point. |
775
+ | <a id="unused-export"></a>[`unused-export`](docs/rules/unused-export.md) | low | An export that no scanned file imports. |
776
+ | <a id="unused-import"></a>[`unused-import`](docs/rules/unused-import.md) | low | An imported name is never used in the file. |
777
+ | <a id="unused-local-variable"></a>[`unused-local-variable`](docs/rules/unused-local-variable.md) | low | A local variable is assigned but never read. |
778
+
779
+ <!-- loadwise:rules:end -->
780
+
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`.
1032
782
 
1033
783
  ## Project rules
1034
784
 
@@ -1044,31 +794,7 @@ Save team decisions in the `maintainability` section of `loadwise.config.json` a
1044
794
  }
1045
795
  ```
1046
796
 
1047
- `limits` sets the thresholds of `large-module`, `large-class` and `long-parameter-list`. Each is a positive integer, and the values shown are the defaults.
1048
-
1049
- `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.
1050
-
1051
- 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.
1052
-
1053
- ## Inline fixes
1054
-
1055
- 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.
1056
-
1057
- ```sh
1058
- npx loadwise maint . --fix # asks y/n/a/q for each fix; needs a terminal
1059
- npx loadwise maint . --fix --yes # applies every fix without asking
1060
- ```
1061
-
1062
- `--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.
1063
-
1064
- | Rule | Rewrite |
1065
- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1066
- | `deep-control-flow` | Lifts the deepest branch one level with a guard clause, a merged nested `if`, or by dropping an `else` after a branch that exits. |
1067
- | `high-branch-complexity` | Combines nested conditional expressions with the same literal success label while preserving short-circuit order. Other fixes merge nested `if`s, join adjacent same-exit `if`s with `\|\|`, turn `x ? true : false` into `Boolean(x)`, and `if (!x) x = value` into `x \|\|= value`. |
1068
- | `duplicate-implementation` | Keeps one top-level function and makes each other copy delegate to it, adding an import where needed. Applied only when every name the copies use resolves to the same binding. |
1069
- | `dependency-cycle` | Turns an import whose names are used only as types into `import type`, which removes that edge from the runtime cycle. |
1070
-
1071
- 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.
1072
798
 
1073
799
  ## A module graph in any language
1074
800
 
@@ -1085,71 +811,11 @@ Other rules have no automatic rewrite.
1085
811
  npx loadwise maint . --graph modules.json --config policy.json
1086
812
  ```
1087
813
 
1088
- 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.
1089
-
1090
- ## CI and design review
1091
-
1092
- 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.
1093
-
1094
- 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.
1095
-
1096
- 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.
1097
-
1098
- 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/)
1099
-
1100
- ## Apply fixes by id
1101
-
1102
- 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.
1103
-
1104
- ```sh
1105
- npx loadwise maint . --fix --only <id>[,<id>...] [--json]
1106
- ```
1107
-
1108
- `--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.
1109
-
1110
- 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.
1111
-
1112
- ## Changed lines
1113
-
1114
- ```sh
1115
- npx loadwise maint --staged .
1116
- npx loadwise maint --changed-since <git-ref> .
1117
- ```
1118
-
1119
- `--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.
1120
-
1121
- 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.
1122
-
1123
- ## Impact levels
1124
-
1125
- The levels and the `--min-impact` flag work as described under the performance checker's impact levels.
1126
-
1127
- | Rule | Impact |
1128
- | -------------------------- | ------ |
1129
- | `dependency-cycle` | high |
1130
- | `data-access-boundary` | medium |
1131
- | `deprecated-node-api` | medium |
1132
- | `duplicate-implementation` | medium |
1133
- | `folder-boundary` | medium |
1134
- | `high-branch-complexity` | medium |
1135
- | `query-mutates-state` | medium |
1136
- | `syntax-error` | medium |
1137
- | `deep-control-flow` | low |
1138
- | `file-placement` | low |
1139
- | `large-class` | low |
1140
- | `large-module` | low |
1141
- | `long-parameter-list` | low |
1142
- | `stray-console` | low |
1143
- | `unreferenced-file` | low |
1144
- | `unused-export` | low |
1145
- | `unused-import` | low |
1146
- | `unused-local-variable` | low |
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.
1147
815
 
1148
816
  # Security checker
1149
817
 
1150
- `loadwise sec` reports code paths where input or missing scope can expose data: runtime text composed into SQL and, when the project declares them, Prisma and Drizzle queries that do not prove their row scope. 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.
1151
-
1152
- ## 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.
1153
819
 
1154
820
  ```sh
1155
821
  npx loadwise sec # tsconfig.json or jsconfig.json in the current folder
@@ -1160,270 +826,160 @@ npx loadwise sec deps --online # known-vulnerable packages in the lockfil
1160
826
  npx loadwise sec polyglot src/ # ast-grep rules for Python, Go, Java, C#, Rust
1161
827
  ```
1162
828
 
1163
- 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`. It uses the TypeScript 6 compiler: `--engine auto` (the default) and `--engine js` both run the JS engine, because the native engine finds less. `--engine native` (alias `--native`) runs the TypeScript 7 native compiler and prints a stderr 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 the package is installed; rules that recognise a library by its import work without `node_modules`. Test, fixture, mock, example and story files are contextual: they are counted, and `--include-contextual` shows them with the reason `Test or example source.`. `--fail-on contract` enforces no security rule by default. `--fix --yes` leaves changes to ValidationPipe whitelisting for individual review because enabling it can strip undecorated DTO properties.
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.
1164
830
 
1165
831
  ## Rules
1166
832
 
1167
- | Rule | What to review |
1168
- | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1169
- | <a id="pg-dynamic-query-text"></a>`pg-dynamic-query-text` | Runtime fragments enter SQL text directly. Bind data as parameters and verify how any dynamic identifiers are chosen and quoted. A finding is a code-review prompt. |
1170
- | <a id="prisma-scope-unverified"></a>`prisma-scope-unverified` | A Prisma read or write on a model listed in `prismaScopes` does not prove the configured scope in its filter, projection or write data. |
1171
- | <a id="drizzle-scope-unverified"></a>`drizzle-scope-unverified` | A Drizzle query on a table listed in `drizzleScopes` does not prove the configured predicate, projection or write data. |
1172
- | <a id="code-injection"></a>`code-injection` | Request data is evaluated as code: `eval`, `new Function`, `vm`, a string timer callback, `require`/`import()` of a request path, or node-serialize. |
1173
- | <a id="command-injection"></a>`command-injection` | Request data reaches a command line a shell parses: `exec`, or `spawn`/`execFile`/execa with `shell` or `sh -c`. An interpolated parameter with no traced caller is contextual. |
1174
- | <a id="drizzle-sql-raw-dynamic"></a>`drizzle-sql-raw-dynamic` | `sql.raw` from drizzle-orm receives text built from a runtime value. |
1175
- | <a id="knex-raw-dynamic-text"></a>`knex-raw-dynamic-text` | A Knex `*Raw` fragment or `knex.raw` receives text built from a runtime value instead of `?`/`??` bindings. |
1176
- | <a id="mysql-dynamic-query-text"></a>`mysql-dynamic-query-text` | A `mysql`/`mysql2` `query` or `execute` receives SQL text built from a runtime value instead of `?` placeholders. |
1177
- | <a id="nosql-operator-injection"></a>`nosql-operator-injection` | Request data that can arrive as an object is a Mongoose or MongoDB filter, a filter value or a `$where` expression. Contextual when applicable Express sanitizer registration is visible. Fix: wrap the value in `$eq`. |
1178
- | <a id="prisma-raw-unsafe-dynamic"></a>`prisma-raw-unsafe-dynamic` | `$queryRawUnsafe`, `$executeRawUnsafe` or `Prisma.raw` receives SQL text built from a runtime value. |
1179
- | <a id="regex-from-input"></a>`regex-from-input` | Request text becomes a regular expression through `RegExp`, `match`/`matchAll`/`search` on a string, or a `$regex` operand, without escaping. |
1180
- | <a id="regex-catastrophic-backtracking"></a>`regex-catastrophic-backtracking` | A fixed regular expression with nested or overlapping repetition (such as `(a+)+` or `(a\|aa)+`), or overlapping repeats in sequence (such as `\s+.*\s+$`), runs on request input and can backtrack exponentially or in polynomial time, blocking the event loop. Rewrite it so each part matches text one way, or cut the input to a fixed length first. |
1181
- | <a id="sequelize-dynamic-query-text"></a>`sequelize-dynamic-query-text` | `sequelize.query` or `literal` receives SQL text built from a runtime value instead of `replacements` or `bind`. |
1182
- | <a id="template-injection"></a>`template-injection` | Request data is the template text of `ejs`, `pug`, `handlebars`, `nunjucks`, `mustache` or lodash `template`. |
1183
- | <a id="typeorm-dynamic-query-text"></a>`typeorm-dynamic-query-text` | A TypeORM `query` or a query-builder condition, order, group, select or join receives SQL text built from a runtime value. |
1184
- | <a id="open-redirect"></a>`open-redirect` | A redirect target whose site comes from request data. A fixed origin or an enforced relative-path check can keep the target on site. A Referer target is contextual. |
1185
- | <a id="path-traversal"></a>`path-traversal` | A file path built from request data reaches `fs`, `res.sendFile` without `root`, `res.download` or `res.render`. `path.basename` and a containment check clear it. An anchored filename allowlist also clears it when the checker can prove the allowed characters and the validated value reaches the file operation unchanged. |
1186
- | <a id="ssrf-request-url"></a>`ssrf-request-url` | An outgoing HTTP request whose URL or host comes from request data. A fixed origin with a request path, an enforced exact host allowlist on the parsed URL, or an SSRF-filtering agent is quiet. |
1187
- | <a id="upload-client-filename"></a>`upload-client-filename` | multer disk storage saves uploads under the client's file name, so same-named uploads overwrite each other and the client picks the extension. |
1188
- | <a id="zip-slip-extraction"></a>`zip-slip-extraction` | An archive entry name (adm-zip, yauzl, unzipper, tar-stream, jszip, node-stream-zip) reaches a file write without a prior containment check. The trace follows aliases, destructuring and local call hops. |
1189
- | <a id="bcrypt-low-cost"></a>`bcrypt-low-cost` | A literal bcrypt cost below 10 passed to `hash`, `hashSync`, `genSalt` or `genSaltSync`. Use 10 or higher and measure the hashing time; the fix writes 12. |
1190
- | <a id="hardcoded-secret"></a>`hardcoded-secret` | A known credential shape (`sk_live_`, `AKIA...`, `ghp_`, private keys), a string literal used as a JWT, HMAC or session signing key, or a high-entropy value assigned to a secret-named variable or property. Placeholders, documentation examples and test sources are skipped; low-entropy named values are contextual. |
1191
- | <a id="insecure-cipher"></a>`insecure-cipher` | `createCipher` or `createDecipher` (no IV), DES, RC2, RC4 or Blowfish algorithms, ECB mode, or a fixed string or `Buffer.alloc` IV in `createCipheriv`. |
1192
- | <a id="insecure-random-for-secret"></a>`insecure-random-for-secret` | `Math.random()` feeds a token, code, nonce, session or secret. Use `crypto.randomBytes`, `randomInt` or `randomUUID`; names that only end in `id` are contextual. `Math.floor(Math.random() * N)` has a source fix. |
1193
- | <a id="jwt-decode-for-auth"></a>`jwt-decode-for-auth` | `decode` (`jsonwebtoken`, `JwtService`, the jwt-decode package) has no `verify` on the same token and its result becomes `req.user`, is used in a guard or auth middleware, or filters a query. Other uses are contextual. |
1194
- | <a id="jwt-none-algorithm"></a>`jwt-none-algorithm` | The `none` algorithm appears in an `algorithms` list or a `sign` call, so unsigned tokens are accepted or produced. |
1195
- | <a id="jwt-sign-without-expiry"></a>`jwt-sign-without-expiry` | `jsonwebtoken` `sign` with a literal payload and no `expiresIn` option or `exp` claim. Literal NestJS JwtService signing also uses expiry set by its bound JwtModule registration. Unresolved defaults are contextual. |
1196
- | <a id="jwt-verify-without-algorithms"></a>`jwt-verify-without-algorithms` | `jsonwebtoken` `verify` without `algorithms` in a literal options object. Public keys, key files and key-lookup callbacks are default; shared secrets are contextual. The fix pins the algorithm the same key signs with in the file. |
1197
- | <a id="secret-compared-non-constant-time"></a>`secret-compared-non-constant-time` | An HMAC or hash digest, or a value named like a signature, secret, token, OTP, password or CSRF token, is compared directly with request input. For strict comparisons of two proven strings in a Node module, the fix uses `crypto.timingSafeEqual` and preserves JavaScript string equality. |
1198
- | <a id="tls-verification-disabled"></a>`tls-verification-disabled` | A literal `rejectUnauthorized: false`, `strictSSL: false` or `NODE_TLS_REJECT_UNAUTHORIZED = '0'`. Under a non-production guard it is contextual; database `ssl` options count too. |
1199
- | <a id="weak-password-hash"></a>`weak-password-hash` | `createHash` with md5, sha1, sha256 or sha512 (or the crypto-js or md5 package) hashes a password or the digest is stored as one. Use `argon2`, `bcrypt` or `crypto.scrypt`. |
1200
- | <a id="plaintext-password-storage"></a>`plaintext-password-storage` | A request password is written by an ORM create, update or save, or a raw INSERT or UPDATE, without being hashed. A value named like a hash or digest, and a model hook that hashes on save, keep it quiet. Hash it with `argon2`, `bcrypt` or `crypto.scrypt` first. |
1201
- | <a id="auth-route-without-rate-limit"></a>`auth-route-without-rate-limit` | A login, signup, password-reset or OTP route has no rate limiter, which allows brute force and credential stuffing. A route is contextual when a limiter package is imported in a module connected to its file by imports (the file itself, one it imports, or app setup that imports it) but not tied to the route; dismiss a gateway or proxy limit with a review comment. |
1202
- | <a id="cookie-missing-security-flags"></a>`cookie-missing-security-flags` | A session, token or auth cookie is set without `httpOnly`, or with `secure: false`. A missing `secure` or `sameSite` is contextual. Non-literal options are not judged. |
1203
- | <a id="cors-credentials-any-origin"></a>`cors-credentials-any-origin` | CORS options allow credentials with origin `*`, `true`, a match-everything regex or a callback that always accepts. Listed or configured origins are clean. |
1204
- | <a id="cors-origin-regex-unanchored"></a>`cors-origin-regex-unanchored` | CORS `origin` regexes, and regex `.test` calls on the request origin, whose host can be prefixed (no `^`, `//` or `\.` before it), extended (no `$` after it) or has an unescaped dot. URL values passed to `new RegExp` count too. Without credentials it is contextual. The fix anchors and escapes a single-branch literal and needs review. |
1205
- | <a id="error-stack-in-response"></a>`error-stack-in-response` | An error `.stack` is written into a response body. A whole error object is contextual. Code that runs only outside production is clean. |
1206
- | <a id="graphql-introspection-enabled"></a>`graphql-introspection-enabled` | A GraphQL server config turns on `introspection`, `playground` or `graphiql` with a literal `true`. Expressions are not judged. |
1207
- | <a id="mass-assignment"></a>`mass-assignment` | The whole request body reaches a Prisma, TypeORM, Mongoose or Sequelize write. Decorated DTO classes, schema parses and explicit field picks are clean. |
1208
- | <a id="nest-validation-without-whitelist"></a>`nest-validation-without-whitelist` | A NestJS `ValidationPipe` is created without `whitelist: true`, so undeclared properties reach handlers. Without `forbidNonWhitelisted` it is contextual. |
1209
- | <a id="prototype-pollution"></a>`prototype-pollution` | A request-controlled key is written through a nested path, or the whole request goes to lodash `merge`, `defaultsDeep`, a path `set` or an unguarded local deep merge. |
1210
- | <a id="reflected-xss-response"></a>`reflected-xss-response` | Request data is interpolated into an HTML string sent with `res.send`. Contextual only in this version. |
1211
- | <a id="secret-in-log"></a>`secret-in-log` | A password, token, key or authorization value is passed to a logger call. Logging a whole request body or headers object is contextual. |
1212
- | <a id="template-autoescape-disabled"></a>`template-autoescape-disabled` | `swig.setDefaults`, `nunjucks.configure` or `new nunjucks.Environment` sets `autoescape: false`, or Handlebars `compile`/`precompile` sets `noEscape: true`. |
1213
- | <a id="xml-external-entities"></a>`xml-external-entities` | `libxmljs` is asked to load entities or the DTD with `noent: true` or `dtdload: true`. |
1214
- | <a id="password-hash-in-response"></a>`password-hash-in-response` | A request handler sends a user record read without a field selection, so its password hash reaches the client. Select or omit the field, or hide it on the model (`select: false`, `@Exclude()`). |
1215
- | <a id="storage-object-public-acl"></a>`storage-object-public-acl` | An S3 or Google Cloud Storage upload sets a public-read ACL, so anyone can read the object. Keep objects private and hand out short-lived presigned URLs. Keys or buckets named like public assets are contextual; a public read-write ACL never is. |
1216
- | <a id="secret-in-url-query"></a>`secret-in-url-query` | A password, token or API key is read from, or sent in, a URL query string, where it ends up in access logs, browser history and Referer headers. Send it in a header or the body. Reset, verify and invite tokens, and map or weather APIs that require a query key, are contextual. |
1217
- | <a id="graphql-query-depth-unbounded"></a>`graphql-query-depth-unbounded` | An Apollo, Yoga, graphql-http, mercurius or Nest GraphQL server has no query depth or cost limit, so one deeply nested query can exhaust it. Contextual when the options are not visible or a limit library is imported elsewhere. |
1218
- | <a id="database-error-in-response"></a>`database-error-in-response` | A 5xx response sends a raw database error, or its message, caught from a database call. Driver messages reveal table, column and constraint names; log the error and return a generic message. Express error middleware is contextual. |
1219
- | <a id="dom-xss-sink"></a>`dom-xss-sink` | Untrusted or dynamic HTML is written to innerHTML, outerHTML, insertAdjacentHTML, document.write or createContextualFragment, which allows DOM-based XSS. |
1220
- | <a id="react-dangerously-set-inner-html"></a>`react-dangerously-set-inner-html` | dangerouslySetInnerHTML receives HTML that is not a constant or sanitized. |
1221
- | <a id="angular-bypass-security-trust"></a>`angular-bypass-security-trust` | DomSanitizer.bypassSecurityTrust* is called on a dynamic value, which turns off Angular's built-in sanitization. |
1222
- | <a id="vue-v-html-unsanitized"></a>`vue-v-html-unsanitized` | A Vue render function binds unsanitized dynamic HTML to innerHTML. |
1223
- | <a id="frontend-storage-secret-token"></a>`frontend-storage-secret-token` | A token, JWT, password or API key is stored in localStorage or sessionStorage, readable by any script on the page. |
1224
- | <a id="postmessage-missing-origin-check"></a>`postmessage-missing-origin-check` | postMessage targets '*', or a window message listener reads event.data without checking origin or source. |
1225
- | <a id="express-missing-helmet"></a>`express-missing-helmet` | The Express or NestJS server starts without helmet security headers middleware (contextual: a proxy may set them). |
1226
- | <a id="committed-secret"></a>`committed-secret` | A tracked file holds a credential: a non-placeholder value for a secret-looking key in a tracked `.env` file, or a high-confidence token format (AWS, GitHub, Slack, Stripe live, Google API key, private key block) in any tracked text file. Ignored `.env` files are never read, and the message shows only the key and a four-character prefix. |
1227
- | <a id="compose-hardcoded-secret"></a>`compose-hardcoded-secret` | A docker-compose `environment:` entry sets a secret-looking key to a literal value instead of a substitution or secret. |
1228
- | <a id="dockerfile-add-remote-url"></a>`dockerfile-add-remote-url` | `ADD` fetches an `http(s)` URL without a checksum. Download with curl and verify a checksum, or `COPY` a local file. |
1229
- | <a id="dockerfile-runs-as-root"></a>`dockerfile-runs-as-root` | The final stage has no `USER` instruction, or its last `USER` is root. Builder stages are not checked. |
1230
- | <a id="dockerfile-secret-in-build"></a>`dockerfile-secret-in-build` | An `ARG` or `ENV` with a secret-looking name has a literal default, or `COPY`/`ADD` puts an env file or private key into the image. |
1231
- | <a id="dockerfile-unpinned-base-image"></a>`dockerfile-unpinned-base-image` | A `FROM` image has no tag or uses `:latest`. A version tag is fine; a digest is best. |
1232
- | <a id="server-action-missing-auth"></a>`server-action-missing-auth` | An exported Next.js Server Action performs work without verifying authentication or session state. |
1233
- | <a id="ssrf-redirect-bypass"></a>`ssrf-redirect-bypass` | An outbound HTTP request with a dynamic URL does not disable redirects (`redirect: 'error'` / `'manual'` or `maxRedirects: 0`), allowing SSRF allowlist bypasses. |
1234
- | <a id="vm-sandbox-escape"></a>`vm-sandbox-escape` | Node `vm` or `vm2` executes dynamic code or an untrusted context, risking sandbox escape and host RCE. |
1235
- | <a id="jwt-weak-secret-literal"></a>`jwt-weak-secret-literal` | JWT signing or verification uses a short (< 32 chars) or weak literal secret susceptible to brute-force forgery. |
1236
- | <a id="graphql-batching-unbounded"></a>`graphql-batching-unbounded` | GraphQL query batching is enabled without a batch size, query depth, or cost/complexity limit. |
1237
- | <a id="express-cookie-auth-missing-csrf"></a>`express-cookie-auth-missing-csrf` | Cookie-based session or auth is paired with state-changing routes without CSRF protection or `sameSite: "strict"`. |
1238
-
1239
- The SQL rules report text assembled from a runtime value. When a part of that text traces to request data the finding is default and names the source; when no part does, it is contextual, because the value is usually an internal schema or table name. Every injection rule other than the SQL rules reports only values traced to request data.
1240
-
1241
- 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`.
1242
-
1243
- 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.
1244
-
1245
- 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.
833
+ <!-- loadwise:rules:start checker=security group=rules -->
834
+
835
+ | Rule | Impact | What it flags |
836
+ | ------------------------------------------------------------------------------------------------------------------------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
837
+ | <a id="angular-bypass-security-trust"></a>[`angular-bypass-security-trust`](docs/rules/angular-bypass-security-trust.md) | high | DomSanitizer.bypassSecurityTrust* is called on a dynamic value, which turns off Angular's built-in sanitization. |
838
+ | <a id="auth-route-without-rate-limit"></a>[`auth-route-without-rate-limit`](docs/rules/auth-route-without-rate-limit.md) | medium | A login, signup or password-reset route has no rate limiter. |
839
+ | <a id="bcrypt-low-cost"></a>[`bcrypt-low-cost`](docs/rules/bcrypt-low-cost.md) | medium | A bcrypt password hash uses a work factor below the recommended minimum. |
840
+ | <a id="client-env-secret-exposed"></a>[`client-env-secret-exposed`](docs/rules/client-env-secret-exposed.md) | critical | A secret-named env variable is read under a browser prefix (NEXT_PUBLIC_, VITE_, REACT_APP_...), so the build ships it to every visitor. |
841
+ | <a id="code-injection"></a>[`code-injection`](docs/rules/code-injection.md) | critical | Request-controlled input becomes source code evaluated by the application. |
842
+ | <a id="command-injection"></a>[`command-injection`](docs/rules/command-injection.md) | critical | Request-controlled input reaches a shell command string. |
843
+ | <a id="committed-secret"></a>[`committed-secret`](docs/rules/committed-secret.md) | critical | A tracked file contains a value that appears to be a credential. |
844
+ | <a id="compose-hardcoded-secret"></a>[`compose-hardcoded-secret`](docs/rules/compose-hardcoded-secret.md) | high | A Docker Compose service supplies a secret as a literal environment value. |
845
+ | <a id="cookie-missing-security-flags"></a>[`cookie-missing-security-flags`](docs/rules/cookie-missing-security-flags.md) | high | A sensitive cookie is set without the expected security attributes. |
846
+ | <a id="cors-credentials-any-origin"></a>[`cors-credentials-any-origin`](docs/rules/cors-credentials-any-origin.md) | high | A credentialed CORS response allows arbitrary origins. |
847
+ | <a id="cors-origin-regex-unanchored"></a>[`cors-origin-regex-unanchored`](docs/rules/cors-origin-regex-unanchored.md) | medium | A CORS origin regex also accepts look-alike hosts. |
848
+ | <a id="database-error-in-response"></a>[`database-error-in-response`](docs/rules/database-error-in-response.md) | medium | An HTTP response includes a raw database error message. |
849
+ | <a id="dockerfile-add-remote-url"></a>[`dockerfile-add-remote-url`](docs/rules/dockerfile-add-remote-url.md) | medium | A Dockerfile ADD instruction retrieves a resource from a remote URL. |
850
+ | <a id="dockerfile-runs-as-root"></a>[`dockerfile-runs-as-root`](docs/rules/dockerfile-runs-as-root.md) | medium | The final image selects root or inherits an unverified base-image user. |
851
+ | <a id="dockerfile-secret-in-build"></a>[`dockerfile-secret-in-build`](docs/rules/dockerfile-secret-in-build.md) | high | A Dockerfile exposes a secret through a build argument or environment variable. |
852
+ | <a id="dockerfile-unpinned-base-image"></a>[`dockerfile-unpinned-base-image`](docs/rules/dockerfile-unpinned-base-image.md) | low | A Dockerfile uses a base image reference that can change between builds. |
853
+ | <a id="dom-xss-sink"></a>[`dom-xss-sink`](docs/rules/dom-xss-sink.md) | high | Untrusted or dynamic HTML reaches innerHTML, outerHTML, insertAdjacentHTML, document.write or createContextualFragment (DOM XSS). |
854
+ | <a id="drizzle-scope-unverified"></a>[`drizzle-scope-unverified`](docs/rules/drizzle-scope-unverified.md) | high | A Drizzle operation lacks the row scope required by the declared policy. |
855
+ | <a id="drizzle-sql-raw-dynamic"></a>[`drizzle-sql-raw-dynamic`](docs/rules/drizzle-sql-raw-dynamic.md) | critical | A dynamic SQL fragment reaches Drizzle without parameter binding. |
856
+ | <a id="error-stack-in-response"></a>[`error-stack-in-response`](docs/rules/error-stack-in-response.md) | medium | An HTTP response includes an internal error stack. |
857
+ | <a id="express-cookie-auth-missing-csrf"></a>[`express-cookie-auth-missing-csrf`](docs/rules/express-cookie-auth-missing-csrf.md) | high | Cookie-based session or auth is paired with state-changing routes without CSRF protection or `sameSite: "strict"`. |
858
+ | <a id="express-missing-helmet"></a>[`express-missing-helmet`](docs/rules/express-missing-helmet.md) | low | The Express or NestJS server starts without helmet security headers middleware (contextual: a proxy may set them). |
859
+ | <a id="frontend-storage-secret-token"></a>[`frontend-storage-secret-token`](docs/rules/frontend-storage-secret-token.md) | medium | A token, JWT, password or API key is stored in localStorage or sessionStorage, readable by any script on the page. |
860
+ | <a id="graphql-batching-unbounded"></a>[`graphql-batching-unbounded`](docs/rules/graphql-batching-unbounded.md) | medium | GraphQL query batching is enabled without a batch size, query depth, or cost/complexity limit. |
861
+ | <a id="graphql-introspection-enabled"></a>[`graphql-introspection-enabled`](docs/rules/graphql-introspection-enabled.md) | medium | A GraphQL server explicitly enables schema introspection. |
862
+ | <a id="graphql-query-depth-unbounded"></a>[`graphql-query-depth-unbounded`](docs/rules/graphql-query-depth-unbounded.md) | medium | A GraphQL server accepts queries of any depth. |
863
+ | <a id="hardcoded-secret"></a>[`hardcoded-secret`](docs/rules/hardcoded-secret.md) | critical | The source supplies a literal credential or cryptographic secret. |
864
+ | <a id="insecure-cipher"></a>[`insecure-cipher`](docs/rules/insecure-cipher.md) | medium | A cryptographic operation selects an insecure cipher or mode. |
865
+ | <a id="insecure-random-for-secret"></a>[`insecure-random-for-secret`](docs/rules/insecure-random-for-secret.md) | high | A sensitive token or secret uses a non-cryptographic random source. |
866
+ | <a id="jsx-javascript-url"></a>[`jsx-javascript-url`](docs/rules/jsx-javascript-url.md) | high | In React 18 and older or Preact, a URL search parameter or location hash starts a JSX href, action or iframe src (javascript: XSS). |
867
+ | <a id="jwt-decode-for-auth"></a>[`jwt-decode-for-auth`](docs/rules/jwt-decode-for-auth.md) | high | Authentication uses decoded JWT claims without verifying the token signature. |
868
+ | <a id="jwt-none-algorithm"></a>[`jwt-none-algorithm`](docs/rules/jwt-none-algorithm.md) | critical | JWT signing or verification allows an unsigned token. |
869
+ | <a id="jwt-sign-without-expiry"></a>[`jwt-sign-without-expiry`](docs/rules/jwt-sign-without-expiry.md) | medium | A signed JWT has no explicit expiration. |
870
+ | <a id="jwt-verify-without-algorithms"></a>[`jwt-verify-without-algorithms`](docs/rules/jwt-verify-without-algorithms.md) | high | JWT verification does not restrict the accepted signing algorithms. |
871
+ | <a id="jwt-weak-secret-literal"></a>[`jwt-weak-secret-literal`](docs/rules/jwt-weak-secret-literal.md) | high | JWT signing or verification uses a short (< 32 chars) or weak literal secret susceptible to brute-force forgery. |
872
+ | <a id="knex-raw-dynamic-text"></a>[`knex-raw-dynamic-text`](docs/rules/knex-raw-dynamic-text.md) | critical | A dynamic SQL fragment reaches Knex without parameter binding. |
873
+ | <a id="mass-assignment"></a>[`mass-assignment`](docs/rules/mass-assignment.md) | high | An unfiltered request body reaches a persistence operation. |
874
+ | <a id="mysql-dynamic-query-text"></a>[`mysql-dynamic-query-text`](docs/rules/mysql-dynamic-query-text.md) | critical | Dynamic SQL text reaches a MySQL client without parameter binding. |
875
+ | <a id="nest-validation-without-whitelist"></a>[`nest-validation-without-whitelist`](docs/rules/nest-validation-without-whitelist.md) | medium | A NestJS ValidationPipe permits properties outside the validated DTO. |
876
+ | <a id="next-image-any-remote-host"></a>[`next-image-any-remote-host`](docs/rules/next-image-any-remote-host.md) | medium | A Next.js images.remotePatterns entry sets hostname '**', so the image optimizer fetches and serves any host (open proxy). |
877
+ | <a id="nosql-operator-injection"></a>[`nosql-operator-injection`](docs/rules/nosql-operator-injection.md) | high | Request data can introduce query operators into a NoSQL filter. |
878
+ | <a id="open-redirect"></a>[`open-redirect`](docs/rules/open-redirect.md) | medium | An HTTP redirect destination is controlled by request data. |
879
+ | <a id="password-hash-in-response"></a>[`password-hash-in-response`](docs/rules/password-hash-in-response.md) | high | A response returns a user record that still holds its password hash. |
880
+ | <a id="path-traversal"></a>[`path-traversal`](docs/rules/path-traversal.md) | high | Request data controls a filesystem path without a recognized containment check. |
881
+ | <a id="pg-dynamic-query-text"></a>[`pg-dynamic-query-text`](docs/rules/pg-dynamic-query-text.md) | medium | Dynamic SQL text reaches the PostgreSQL client without parameter binding. |
882
+ | <a id="plaintext-password-storage"></a>[`plaintext-password-storage`](docs/rules/plaintext-password-storage.md) | critical | A password is stored or written without being hashed. |
883
+ | <a id="postmessage-missing-origin-check"></a>[`postmessage-missing-origin-check`](docs/rules/postmessage-missing-origin-check.md) | medium | postMessage targets '*', or a window message listener reads event.data without checking origin or source. |
884
+ | <a id="prisma-raw-unsafe-dynamic"></a>[`prisma-raw-unsafe-dynamic`](docs/rules/prisma-raw-unsafe-dynamic.md) | critical | Dynamic SQL text reaches an unsafe Prisma raw-query method. |
885
+ | <a id="prisma-scope-unverified"></a>[`prisma-scope-unverified`](docs/rules/prisma-scope-unverified.md) | high | A Prisma operation lacks the row scope required by the declared policy. |
886
+ | <a id="prototype-pollution"></a>[`prototype-pollution`](docs/rules/prototype-pollution.md) | high | Request data can supply keys to a write or merge that can modify an object prototype. |
887
+ | <a id="react-dangerously-set-inner-html"></a>[`react-dangerously-set-inner-html`](docs/rules/react-dangerously-set-inner-html.md) | high | dangerouslySetInnerHTML receives HTML that is not a constant or sanitized. |
888
+ | <a id="reflected-xss-response"></a>[`reflected-xss-response`](docs/rules/reflected-xss-response.md) | low | An HTML response reflects request data without recognized escaping. |
889
+ | <a id="regex-catastrophic-backtracking"></a>[`regex-catastrophic-backtracking`](docs/rules/regex-catastrophic-backtracking.md) | high | A regular expression that can backtrack exponentially or in polynomial time runs on request input. |
890
+ | <a id="regex-from-input"></a>[`regex-from-input`](docs/rules/regex-from-input.md) | medium | Request input supplies a regular expression pattern without recognized escaping. |
891
+ | <a id="secret-compared-non-constant-time"></a>[`secret-compared-non-constant-time`](docs/rules/secret-compared-non-constant-time.md) | medium | A secret is compared with an operation that can vary in timing with its contents. |
892
+ | <a id="secret-in-log"></a>[`secret-in-log`](docs/rules/secret-in-log.md) | high | A log statement can expose a credential, token, or other secret. |
893
+ | <a id="secret-in-url-query"></a>[`secret-in-url-query`](docs/rules/secret-in-url-query.md) | medium | A password, token or API key is passed in a URL query string. |
894
+ | <a id="sequelize-dynamic-query-text"></a>[`sequelize-dynamic-query-text`](docs/rules/sequelize-dynamic-query-text.md) | critical | Dynamic SQL text reaches Sequelize without parameter binding. |
895
+ | <a id="server-action-missing-auth"></a>[`server-action-missing-auth`](docs/rules/server-action-missing-auth.md) | high | An exported Next.js Server Action performs work without verifying authentication or session state. |
896
+ | <a id="ssrf-redirect-bypass"></a>[`ssrf-redirect-bypass`](docs/rules/ssrf-redirect-bypass.md) | high | An outbound HTTP request with a dynamic URL does not disable redirects, allowing SSRF allowlist bypasses. |
897
+ | <a id="ssrf-request-url"></a>[`ssrf-request-url`](docs/rules/ssrf-request-url.md) | high | Request data controls the destination of a server-side network request. |
898
+ | <a id="storage-object-public-acl"></a>[`storage-object-public-acl`](docs/rules/storage-object-public-acl.md) | high | A storage upload makes the object publicly readable. |
899
+ | <a id="template-autoescape-disabled"></a>[`template-autoescape-disabled`](docs/rules/template-autoescape-disabled.md) | medium | A template engine is configured to render values without HTML escaping. |
900
+ | <a id="template-injection"></a>[`template-injection`](docs/rules/template-injection.md) | critical | Request data is interpreted as template source rather than a template value. |
901
+ | <a id="tls-verification-disabled"></a>[`tls-verification-disabled`](docs/rules/tls-verification-disabled.md) | high | A TLS client skips certificate or server hostname verification. |
902
+ | <a id="typeorm-dynamic-query-text"></a>[`typeorm-dynamic-query-text`](docs/rules/typeorm-dynamic-query-text.md) | critical | A dynamic SQL fragment reaches TypeORM without parameter binding. |
903
+ | <a id="upload-client-filename"></a>[`upload-client-filename`](docs/rules/upload-client-filename.md) | medium | A file upload is stored under the original name supplied by the client. |
904
+ | <a id="vm-sandbox-escape"></a>[`vm-sandbox-escape`](docs/rules/vm-sandbox-escape.md) | critical | Node `vm` or `vm2` executes dynamic code or an untrusted context, risking sandbox escape and host RCE. |
905
+ | <a id="vue-v-html-unsanitized"></a>[`vue-v-html-unsanitized`](docs/rules/vue-v-html-unsanitized.md) | high | A Vue render function binds unsanitized dynamic HTML to innerHTML. |
906
+ | <a id="weak-password-hash"></a>[`weak-password-hash`](docs/rules/weak-password-hash.md) | high | A password is hashed with an algorithm unsuitable for password storage. |
907
+ | <a id="xml-external-entities"></a>[`xml-external-entities`](docs/rules/xml-external-entities.md) | medium | An XML parser allows processing of external entities. |
908
+ | <a id="zip-slip-extraction"></a>[`zip-slip-extraction`](docs/rules/zip-slip-extraction.md) | high | An archive entry controls an extraction path without a recognized containment check. |
909
+
910
+ <!-- loadwise:rules:end -->
911
+
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.
1246
913
 
1247
914
  ## Polyglot source checks
1248
915
 
1249
- `npx loadwise sec polyglot src/` accepts directories or individual `.py`, `.go`, `.java`, `.cs` and `.rs` files. It uses the optional ast-grep native binary and its syntax-tree patterns. These are syntactic patterns without taint tracking, so each finding is a review prompt: confirm that untrusted input can reach the call. They are not `--ignore` rule ids of the TypeScript source checks. [ast-grep](https://ast-grep.github.io/)
1250
-
1251
- | Rule | What to review |
1252
- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
1253
- | <a id="csharp-process-start"></a>`csharp-process-start` | `Process.Start` launches an external process. Validate inputs and use `ProcessStartInfo` with `ArgumentList`. |
1254
- | <a id="csharp-ef-from-sql-raw"></a>`csharp-ef-from-sql-raw` | `FromSqlRaw` or `ExecuteSqlRaw` receives a concatenated or interpolated string. Use `FromSqlInterpolated` or bind parameters. |
1255
- | <a id="go-exec-command-shell"></a>`go-exec-command-shell` | `exec.Command` invokes a shell. Execute the target binary directly with explicit arguments. |
1256
- | <a id="go-sql-sprintf-injection"></a>`go-sql-sprintf-injection` | SQL text is formatted with `fmt.Sprintf`. Use parameterized queries with placeholders. |
1257
- | <a id="java-runtime-exec"></a>`java-runtime-exec` | `Runtime.getRuntime().exec` runs an OS command. Use `ProcessBuilder` with an explicit argument array. |
1258
- | <a id="java-sql-string-concat"></a>`java-sql-string-concat` | A SQL query is built by string concatenation. Use `PreparedStatement` with bound parameters. |
1259
- | <a id="python-insecure-deserialization"></a>`python-insecure-deserialization` | `pickle` or `marshal` deserializes data that may be untrusted. Use `json` or a schema-validated format. |
1260
- | <a id="python-unsafe-yaml-load"></a>`python-unsafe-yaml-load` | `yaml.load` without `SafeLoader` can construct arbitrary objects. Use `yaml.safe_load`. |
1261
- | <a id="python-subprocess-shell-true"></a>`python-subprocess-shell-true` | `subprocess` with `shell=True` or `os.system` passes input through a shell. Pass an argument list with `shell=False`. |
1262
- | <a id="rust-command-shell"></a>`rust-command-shell` | `Command::new("sh")` or `Command::new("bash")` spawns a shell. Invoke the executable directly with `.arg()`. |
1263
- | <a id="rust-unsafe-raw-pointer-deref"></a>`rust-unsafe-raw-pointer-deref` | A raw pointer is dereferenced in an `unsafe` block. Verify pointer validity and alignment or use safe abstractions. |
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.
1264
917
 
1265
- ## Dependency checks
918
+ <!-- loadwise:rules:start checker=security group=polyglot-source-checks -->
1266
919
 
1267
- `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.
1268
-
1269
- 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.
1270
-
1271
- | Rule | What to review |
1272
- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1273
- | <a id="dependency-known-vulnerability"></a>`dependency-known-vulnerability` | A locked package version has published advisories. One finding per package and version lists the advisory ids, the highest severity, the fixed version and the fix: `npm install pkg@fixed` for a direct dependency, or an overrides or resolutions entry for a transitive one. Development-only dependencies are contextual. |
1274
-
1275
- ## Security impact levels
1276
-
1277
- `--min-impact` sets the minimum level to report. Dependency findings use the advisory severity.
1278
-
1279
- | Rule | Impact |
1280
- | ----------------------------------- | ------------------------------------------- |
1281
- | `pg-dynamic-query-text` | medium |
1282
- | `prisma-scope-unverified` | high |
1283
- | `drizzle-scope-unverified` | high |
1284
- | `code-injection` | critical |
1285
- | `command-injection` | critical |
1286
- | `drizzle-sql-raw-dynamic` | critical |
1287
- | `knex-raw-dynamic-text` | critical |
1288
- | `mysql-dynamic-query-text` | critical |
1289
- | `nosql-operator-injection` | high |
1290
- | `prisma-raw-unsafe-dynamic` | critical |
1291
- | `regex-from-input` | medium |
1292
- | `regex-catastrophic-backtracking` | high |
1293
- | `sequelize-dynamic-query-text` | critical |
1294
- | `template-injection` | critical |
1295
- | `typeorm-dynamic-query-text` | critical |
1296
- | `open-redirect` | medium |
1297
- | `path-traversal` | high |
1298
- | `ssrf-request-url` | high |
1299
- | `upload-client-filename` | medium |
1300
- | `zip-slip-extraction` | high |
1301
- | `bcrypt-low-cost` | medium |
1302
- | `hardcoded-secret` | critical |
1303
- | `insecure-cipher` | medium |
1304
- | `insecure-random-for-secret` | high |
1305
- | `jwt-decode-for-auth` | high |
1306
- | `jwt-none-algorithm` | critical |
1307
- | `jwt-sign-without-expiry` | medium |
1308
- | `jwt-verify-without-algorithms` | high |
1309
- | `secret-compared-non-constant-time` | medium |
1310
- | `tls-verification-disabled` | high |
1311
- | `weak-password-hash` | high |
1312
- | `plaintext-password-storage` | critical |
1313
- | `cookie-missing-security-flags` | high |
1314
- | `cors-credentials-any-origin` | high |
1315
- | `cors-origin-regex-unanchored` | medium |
1316
- | `error-stack-in-response` | medium |
1317
- | `graphql-introspection-enabled` | medium |
1318
- | `mass-assignment` | high |
1319
- | `nest-validation-without-whitelist` | medium |
1320
- | `prototype-pollution` | high |
1321
- | `reflected-xss-response` | low |
1322
- | `secret-in-log` | high |
1323
- | `template-autoescape-disabled` | medium |
1324
- | `xml-external-entities` | medium |
1325
- | `password-hash-in-response` | high |
1326
- | `storage-object-public-acl` | high |
1327
- | `secret-in-url-query` | medium |
1328
- | `auth-route-without-rate-limit` | medium |
1329
- | `graphql-query-depth-unbounded` | medium |
1330
- | `database-error-in-response` | medium |
1331
- | `dom-xss-sink` | high |
1332
- | `react-dangerously-set-inner-html` | high |
1333
- | `angular-bypass-security-trust` | high |
1334
- | `vue-v-html-unsanitized` | high |
1335
- | `frontend-storage-secret-token` | medium |
1336
- | `postmessage-missing-origin-check` | medium |
1337
- | `express-missing-helmet` | low |
1338
- | `dependency-known-vulnerability` | Advisory severity (medium when unavailable) |
1339
- | `committed-secret` | critical |
1340
- | `compose-hardcoded-secret` | high |
1341
- | `dockerfile-add-remote-url` | medium |
1342
- | `dockerfile-runs-as-root` | medium |
1343
- | `dockerfile-secret-in-build` | high |
1344
- | `dockerfile-unpinned-base-image` | low |
1345
- | `server-action-missing-auth` | high |
1346
- | `ssrf-redirect-bypass` | high |
1347
- | `vm-sandbox-escape` | critical |
1348
- | `jwt-weak-secret-literal` | high |
1349
- | `graphql-batching-unbounded` | medium |
1350
- | `express-cookie-auth-missing-csrf` | high |
1351
- | `csharp-process-start` | medium |
1352
- | `csharp-ef-from-sql-raw` | high |
1353
- | `go-exec-command-shell` | high |
1354
- | `go-sql-sprintf-injection` | high |
1355
- | `java-runtime-exec` | medium |
1356
- | `java-sql-string-concat` | high |
1357
- | `python-insecure-deserialization` | high |
1358
- | `python-unsafe-yaml-load` | high |
1359
- | `python-subprocess-shell-true` | high |
1360
- | `rust-command-shell` | high |
1361
- | `rust-unsafe-raw-pointer-deref` | medium |
920
+ | Rule | Impact | What it flags |
921
+ | ------------------------------------------------------------------------------------------------------------------------------ | ------ | -------------------------------------------------------------------------------------------------- |
922
+ | <a id="csharp-ef-from-sql-raw"></a>[`csharp-ef-from-sql-raw`](docs/rules/csharp-ef-from-sql-raw.md) | high | FromSqlRaw or ExecuteSqlRaw receives a concatenated or interpolated string, risking SQL injection. |
923
+ | <a id="csharp-process-start"></a>[`csharp-process-start`](docs/rules/csharp-process-start.md) | medium | Process.Start launches an external process and risks command injection with untrusted arguments. |
924
+ | <a id="go-exec-command-shell"></a>[`go-exec-command-shell`](docs/rules/go-exec-command-shell.md) | high | exec.Command invokes a shell, which risks command injection. |
925
+ | <a id="go-sql-sprintf-injection"></a>[`go-sql-sprintf-injection`](docs/rules/go-sql-sprintf-injection.md) | high | SQL text formatted with fmt.Sprintf risks SQL injection. |
926
+ | <a id="java-runtime-exec"></a>[`java-runtime-exec`](docs/rules/java-runtime-exec.md) | medium | Runtime.getRuntime().exec runs an OS command and risks command injection with untrusted arguments. |
927
+ | <a id="java-sql-string-concat"></a>[`java-sql-string-concat`](docs/rules/java-sql-string-concat.md) | high | A SQL query built by string concatenation risks SQL injection. |
928
+ | <a id="python-insecure-deserialization"></a>[`python-insecure-deserialization`](docs/rules/python-insecure-deserialization.md) | high | pickle or marshal deserialization of untrusted data can execute arbitrary code. |
929
+ | <a id="python-subprocess-shell-true"></a>[`python-subprocess-shell-true`](docs/rules/python-subprocess-shell-true.md) | high | subprocess with shell=True or os.system passes input through a shell, risking command injection. |
930
+ | <a id="python-unsafe-yaml-load"></a>[`python-unsafe-yaml-load`](docs/rules/python-unsafe-yaml-load.md) | high | yaml.load without SafeLoader can construct arbitrary Python objects. |
931
+ | <a id="rust-command-shell"></a>[`rust-command-shell`](docs/rules/rust-command-shell.md) | high | Command::new("sh") or Command::new("bash") spawns a shell and risks command injection. |
932
+ | <a id="rust-unsafe-raw-pointer-deref"></a>[`rust-unsafe-raw-pointer-deref`](docs/rules/rust-unsafe-raw-pointer-deref.md) | medium | A raw pointer dereference in an unsafe block bypasses Rust memory safety guarantees. |
1362
933
 
1363
- ## Project-defined row scopes
934
+ <!-- loadwise:rules:end -->
1364
935
 
1365
- Row-scope checks read `prismaScopes` and `drizzleScopes` from the `performance` section of `loadwise.config.json`, found the same way as for the performance checker (see [Project-defined access policy](#project-defined-access-policy)). Every other rule runs without a scope policy. Row-scope checks start when the project identifies the existing model or table, its scoped property, and the helper that supplies an authorized scalar. Columns such as `tenantId`, `organizationId` and `workspace_id` have no special meaning to the checker on their own. Database mappings can keep the original storage column name. [Prisma database mapping](https://www.prisma.io/docs/orm/prisma-schema/data-model/database-mapping) · [Drizzle schema declarations](https://orm.drizzle.team/docs/sql-schema-declaration)
936
+ ## Dependency checks
937
+
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.
1366
939
 
1367
- 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.
940
+ <!-- loadwise:rules:start checker=security group=dependency-checks -->
1368
941
 
1369
- `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.
942
+ | Rule | Impact | What it flags |
943
+ | --------------------------------------------------------------------------------------------------------------------------- | ------ | ------------------------------------------------------------------------------ |
944
+ | <a id="dependency-known-vulnerability"></a>[`dependency-known-vulnerability`](docs/rules/dependency-known-vulnerability.md) | medium | A resolved dependency version is listed in a published vulnerability advisory. |
1370
945
 
1371
- `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.
946
+ <!-- loadwise:rules:end -->
1372
947
 
1373
- The import boundary for database modules is a maintainability rule; configure it through the `dataAccess` field of the `maintainability` section in `loadwise.config.json`.
948
+ ## Project-defined row scopes
1374
949
 
1375
- 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.
1376
951
 
1377
952
  # Accessibility checker
1378
953
 
1379
- `loadwise a11y` finds markup that people using screen readers, keyboards or zoom cannot use: images without alt text, unlabelled form controls, click handlers on non-interactive elements, invalid ARIA, a missing page language and similar. 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`, so project discovery, config, engines, baselines and fix flags are the same, and `loadwise check` type-checks the project once for all of them. 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.
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.
1380
955
 
1381
956
  ```sh
1382
957
  npx loadwise a11y -p tsconfig.json # JSX, Angular templates and the project's markup files
1383
958
  npx loadwise a11y src/index.html # explicit markup files
1384
- npx loadwise a11y --staged # only findings on staged lines
1385
959
  npx loadwise a11y --fix --only <id> # apply one generated fix
1386
960
  ```
1387
961
 
1388
- `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.
1389
-
1390
962
  ## Rules
1391
963
 
1392
- | Rule | What to review | Fix |
1393
- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ |
1394
- | <a id="a11y-img-missing-alt"></a>`a11y-img-missing-alt` | Review whether the image is informative, which needs descriptive alt text, or decorative, which needs `alt=""`. | Manual |
1395
- | <a id="a11y-button-missing-type"></a>`a11y-button-missing-type` | A button inside a form (or tied to one with `form=`) has no `type`, so it submits. Review whether it should submit (`type="submit"`) or only run a click handler (`type="button"`). | Automatic (review) |
1396
- | <a id="a11y-clickable-non-interactive"></a>`a11y-clickable-non-interactive` | Review whether a `<button>` or `<a>` can replace the element, or whether it needs a role, `tabIndex` and key handler. Handlers that only stop propagation are accepted. | Manual |
1397
- | <a id="a11y-invalid-aria"></a>`a11y-invalid-aria` | Review the misspelled ARIA attribute or role against the WAI-ARIA names and use the suggested one. | Manual |
1398
- | <a id="a11y-missing-form-label"></a>`a11y-missing-form-label` | Review how the control is named: a wrapping `<label>`, a `<label for>` matching its id, or aria-label. A placeholder is not a label. | Manual |
1399
- | <a id="a11y-html-missing-lang"></a>`a11y-html-missing-lang` | Review which language the page is written in and set `lang` to it. | Manual |
1400
- | <a id="a11y-iframe-missing-title"></a>`a11y-iframe-missing-title` | Review what the embedded content is and give the iframe a `title` that says so. | Manual |
1401
- | <a id="a11y-positive-tabindex"></a>`a11y-positive-tabindex` | Review whether the focus order can come from the markup order, then use `tabIndex` 0 or -1. | Manual |
1402
- | <a id="a11y-viewport-zoom-disabled"></a>`a11y-viewport-zoom-disabled` | Review whether the zoom limit is needed. Remove `user-scalable=no` and keep maximum-scale at 2 or more. | Manual |
1403
-
1404
- ## Impact levels
1405
-
1406
- 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 this table.
1407
-
1408
- | Rule | Impact |
1409
- | -------------------------------- | ------ |
1410
- | `a11y-clickable-non-interactive` | high |
1411
- | `a11y-img-missing-alt` | high |
1412
- | `a11y-invalid-aria` | high |
1413
- | `a11y-missing-form-label` | high |
1414
- | `a11y-viewport-zoom-disabled` | high |
1415
- | `a11y-button-missing-type` | medium |
1416
- | `a11y-html-missing-lang` | medium |
1417
- | `a11y-iframe-missing-title` | medium |
1418
- | `a11y-positive-tabindex` | medium |
964
+ <!-- loadwise:rules:start checker=accessibility group=rules -->
1419
965
 
1420
- # Developing locally
966
+ | Rule | Impact | What it flags |
967
+ | --------------------------------------------------------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------- |
968
+ | <a id="a11y-button-missing-type"></a>[`a11y-button-missing-type`](docs/rules/a11y-button-missing-type.md) | medium | A button inside a form has no type, so it submits the form even when it only meant to run a handler. |
969
+ | <a id="a11y-clickable-non-interactive"></a>[`a11y-clickable-non-interactive`](docs/rules/a11y-clickable-non-interactive.md) | high | A click handler sits on a non-interactive element without a role and keyboard support, so keyboard users cannot activate it. |
970
+ | <a id="a11y-html-missing-lang"></a>[`a11y-html-missing-lang`](docs/rules/a11y-html-missing-lang.md) | medium | The html element has no lang attribute, so screen readers guess the pronunciation. |
971
+ | <a id="a11y-iframe-missing-title"></a>[`a11y-iframe-missing-title`](docs/rules/a11y-iframe-missing-title.md) | medium | An iframe has no title, so screen readers cannot say what it contains. |
972
+ | <a id="a11y-img-missing-alt"></a>[`a11y-img-missing-alt`](docs/rules/a11y-img-missing-alt.md) | high | An image has no alt text, so screen readers announce its file name or nothing. |
973
+ | <a id="a11y-invalid-aria"></a>[`a11y-invalid-aria`](docs/rules/a11y-invalid-aria.md) | high | An ARIA attribute or role is misspelled or invalid, so assistive technology ignores it. |
974
+ | <a id="a11y-missing-form-label"></a>[`a11y-missing-form-label`](docs/rules/a11y-missing-form-label.md) | high | A form control has no label, so screen readers announce it without its purpose. |
975
+ | <a id="a11y-positive-tabindex"></a>[`a11y-positive-tabindex`](docs/rules/a11y-positive-tabindex.md) | medium | A positive tabindex reorders keyboard focus away from the visual order. |
976
+ | <a id="a11y-viewport-zoom-disabled"></a>[`a11y-viewport-zoom-disabled`](docs/rules/a11y-viewport-zoom-disabled.md) | high | The viewport meta tag disables zoom, so people with low vision cannot enlarge the page. |
1421
977
 
1422
- 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.
978
+ <!-- loadwise:rules:end -->
1423
979
 
1424
- 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
1425
981
 
1426
- From this checkout, run `node bin/loadwise.js check --config scripts/self-scan/loadwise.config.json` to scan Loadwise itself; that config excludes vendored files, tests, examples, and benchmark workloads so they keep their intended behavior.
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).
1427
983
 
1428
984
  # License
1429
985