> ## Documentation Index
> Fetch the complete documentation index at: https://loadwise.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Contributing

> Develop, test, benchmark and release Loadwise.

Thanks for your interest in contributing to Loadwise.

This project follows the [Code of Conduct](https://github.com/IbrahimHafez1/loadwise/blob/main/CODE_OF_CONDUCT.md). By participating, you agree to uphold it.

## Prerequisites

* **Node.js 22.13+** and **npm**
* Install dependencies including optional native packages (`@ast-grep/cli` and the `@typescript/typescript-*` native compiler binaries):

```sh theme={null}
npm ci --include=optional
```

The install configures Git hooks only when run from the primary checkout and `core.hooksPath` has no effective value there. It sets `core.hooksPath` to `hooks` in the shared local Git config, so linked worktrees inherit the setting unless they have a worktree-specific override. The pre-commit hook formats and lints staged files. If you installed with scripts disabled, run `npm run prepare` from the primary checkout to enable the hook under the same conditions.

## Development Loop

When updating the native TypeScript compiler, pin all `@typescript/typescript-*` optional dependencies
in `package.json` to the same published version and refresh the lockfile. After building, run
`node dist/scripts/vendor-native.js <path-to-typescript-package>` with the matching upstream
`typescript` package to regenerate the bindings. Update the pins, lockfile, and vendored bindings together.

Build the TypeScript sources (`npm run build` emits `.js` / `.cjs` files into `dist/`, mirroring the source folders) and run targeted tests while iterating:

```sh theme={null}
npm run build
node --import ./dist/test/manual-session.js --test dist/test/shared/fix-resilience.test.js
```

The property-based fuzz tests use [fast-check](https://fast-check.dev) and live in `test/shared/fuzz-properties.test.ts`. Run them with `node --import ./dist/test/manual-session.js --test dist/test/shared/fuzz-properties.test.js`. A failure prints the seed and a shrunk counterexample; turn the counterexample into a plain regression test.

For the language server and editor module tests:

```sh theme={null}
node --import ./dist/test/manual-session.js --test dist/test/editor/*.test.js
```

Open this repository folder as a trusted workspace in VS Code or Grok Build (formerly Cursor) and enable the recommended Prettier extension; `.vscode/settings.json` formats supported files on save. Run `npm run format` to format files, `npm run lint` for correctness checks, or `npm run check` to verify formatting, lint and tests together.

To scan Loadwise itself, run `node dist/bin/loadwise.js check --config scripts/self-scan/loadwise.config.json`. That config excludes vendored files, tests, examples and benchmark workloads so they keep their intended behavior. `node dist/bin/loadwise.js perf -p examples` scans the bundled examples.

Baseline fingerprints come from the text of each finding's line, so a refactor that rewrites a baselined line moves its fingerprint. Only in that case, run `npm run selfscan:baseline` to rewrite `scripts/self-scan/loadwise-baseline.json`. Never use it to hide a new finding; fix the code instead. [scripts/self-scan/README.md](https://github.com/IbrahimHafez1/loadwise/blob/main/scripts/self-scan/README.md) records the current baseline audit.

Follow the [rule and fix walkthrough](#walkthrough-from-a-rule-to-a-verified-fix) below or use the [rule request form](https://github.com/IbrahimHafez1/loadwise/issues/new?template=rule-request.yml) to propose a rule or edit.

## Source conventions

The CLI, checkers and security example tables are TypeScript (`.ts`) compiled by `npm run build` to ES modules (`.js`) under `dist/`. `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.

* Write ES `import`/`export`, with imports at the top of the file. Oxlint rejects `require()`. Where load order or startup cost forbids a top-level import (the compiler must be chosen before the rules load, and `maint --staged` must not load TypeScript), load lazily in an async function with `await import()`.
* 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.
* 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.
* Comments wrap at 100 columns, and Prettier formats everything.

## Where files belong

* Add checker code to the existing topic under `lib/<checker>/`, such as `lib/performance/request/` or `lib/security/exposure/`. Keep each rule and its implementation helpers in the topic that owns the behavior.
* Keep a helper next to its callers. Use `lib/shared/` when multiple checkers share the same behavior, and place the helper in the existing topic, such as `analysis/`, `fix/`, or `reporting/`. Keep checker-specific policy in the checker.
* Put tests under `test/<checker>/` in the closest matching topic. If a regular test falls outside the existing patterns, update `scripts/test-files.ts`.

## Walkthrough from a rule to a verified fix

`array-repeated-membership` reports repeated `.includes()` searches in a loop or array callback when a `Set` can avoid repeated linear lookup. [Source example](https://github.com/IbrahimHafez1/loadwise/blob/main/examples/slow.ts) · [Canonical rule page](https://loadwise.mintlify.site/rules/performance/array-repeated-membership.md)

```sh theme={null}
npm run build
node dist/bin/loadwise.js perf examples/slow.ts --json
node dist/bin/loadwise.js explain array-repeated-membership
```

In the JSON report, find the `array-repeated-membership` entry and use its file and line to locate `orders.filter(order => allowed.includes(order.customerId))`. The control below builds the lookup once and preserves order for an ordinary, stable array of customer IDs.

```ts theme={null}
const allowedSet = new Set(allowed);
const visible = orders.filter((order) => allowedSet.has(order.customerId));
```

For this performance rule, the detector reports through the shared rule context, the performance rule registry declares the ID and metadata, and the editor's performance-example registry provides the before-and-after guidance. Other checkers have their own registries. [Detector](https://github.com/IbrahimHafez1/loadwise/blob/main/lib/performance/collections/collection-lookups.ts) · [Rule IDs](https://github.com/IbrahimHafez1/loadwise/blob/main/lib/performance/rule-ids.ts) · [Editor examples](https://github.com/IbrahimHafez1/loadwise/blob/main/lib/editor/performance-examples.ts)

The performance fix registry maps that same ID to the membership builder. Test a detected case, a nearby safe case, and a finding that must stay manual. For example, rebuilding the lookup can be necessary when the input array changes between calls. Mark a proposed edit `requiresReview` when a maintainer must confirm a behavioral assumption. [Fix registry](https://github.com/IbrahimHafez1/loadwise/blob/main/lib/performance/site-fixes/collections.ts) · [Membership builder](https://github.com/IbrahimHafez1/loadwise/blob/main/lib/performance/site-fixes/collection-membership.ts)

```sh theme={null}
node --test dist/test/performance/accuracy-collections.test.js dist/test/performance/site-fixes-collections.test.js
npm run docs:rules
```

When changing a generated edit, use the shared `verifyFix` helper to exercise a real checker and recheck the edited fixture. Add behavior assertions for decisions the static scan cannot verify. The checker-specific verification suites show how to supply the correct pillar, policy and fixtures. [Verification helper](https://github.com/IbrahimHafez1/loadwise/blob/main/test/shared/fix-verification.ts) · [Performance fixtures](https://github.com/IbrahimHafez1/loadwise/blob/main/test/shared/fix-verification-performance.test.ts)

## Benchmarks

For everyday development, use the focused regression tests above and run `npm run check` before submitting a change. Benchmarks run locally when a change raises a specific question.

| Question | Local command |
| - | - |
| Did a rule change affect a reviewed upstream location? | Run `npm run bench:holdout -- --strict` on the cached pinned files. Add `--fetch` when hydrating a new manifest. |
| Did the rule miss a known bug or mishandle a specialized input? | Use `npm run bench:recall -- --case <id>` for a known bug, or `npm run bench:evidence` for migrations, API contracts and query plans. |
| How did accuracy change across projects? | Start with `npm run bench:corpus -- --repos directus,medusa --concurrency 1`, choosing repositories that exercise the rule. Use the full corpus for broad detector changes or a release accuracy review. |
| Did the scanner slow down? | Use `npm run bench:scan` for the scanner. Add `-- --large` for the 3,200-file workload. The `bench:security` and `bench:traces` commands isolate those subsystems. |
| Do the two engines agree, or does a suggested optimization help? | Use `npm run bench:parity -- <projectDir>` to compare the `perf`, `rel` and `sec` results of both engines on one project. Use `npm run bench:patterns` to compare application patterns with equal outputs. |
| Do automatic fixes keep real projects compiling? | Run `npm run bench:fix-sweep -- --repos juice-shop` after changing a fix builder. Use the full corpus before a release. |

The public rule scorecard is a snapshot. `npm run bench:scorecard` renders it from saved scores and labels without scanning repositories. Refresh it when publishing new accuracy measurements. Read precision and recall alongside the sample counts and known misses.

The corpus expects pinned checkouts from `bench/corpus/manifest.json` under `../loadwise-corpus/<name>`; pass `--corpus <dir>` when they live elsewhere. Check the run's skipped-project list before interpreting results. The corpus run also prints the wall time of each repository and checker scan (`timings` with `--json`); add `--concurrency 1` when comparing them. The existing precision floor is 80% for default-level rules with at least ten reported findings, subject to the recorded exceptions. See [PERFORMANCE.md](https://github.com/IbrahimHafez1/loadwise/blob/main/PERFORMANCE.md) for the timing methodology.

`npm run bench:parity` with no arguments scans every corpus checkout. A project whose scan skipped files it cannot parse is still compared, and both engines must skip the same files.

`npm run bench:fix-sweep` copies the tracked files of each pinned checkout to a temporary directory, so the checkout is never edited. It scans the copy with `loadwise check`, applies `loadwise fix --all` and scans again. Each changed file is type-checked against its original text with the nearest `tsconfig.json` or `jsconfig.json`, and files without one are listed as not type-checked. The report lists applied fixes per rule, review-marked and refused fixes, and each new type error with its `file:line` and the rule whose hunk touched that line. A fix whose own finding is still reported afterwards is listed as `still reported after its fix`. It exits 1 when a fix adds a type error or a finding, and 2 when a repository cannot be swept. Each checker is fixed in its own run, so one checker that cannot run leaves the others' fixes in the report. Add `--no-verify-types` to bypass the fix command's own type check and surface edits it would refuse, and `--keep` to inspect the fixed copies. The corpus checkouts have no installed dependencies, so errors that need package types are out of reach.

The **scanner benchmark trends** workflow runs the scanner, security, trace and pattern benchmarks weekly on main and on manual dispatch, and compares each run with the previous successful one on the same branch. Two measurement notes record decisions that are not repeated in CI: [bench/maintainability-syntax.md](https://github.com/IbrahimHafez1/loadwise/blob/main/bench/maintainability-syntax.md) covers the native syntax pilot for the maintainability scanner, and [bench/ci-apple-silicon.md](https://github.com/IbrahimHafez1/loadwise/blob/main/bench/ci-apple-silicon.md) covers the macOS jobs in full CI.

To repeat the optional six-package ORM declaration integration, run the commands below. The fixture typechecks the application, compares exact diagnostic locations and checks that clean controls stay quiet.

```sh theme={null}
npm --prefix test/performance/integration/orms install --ignore-scripts --omit=optional --no-audit --no-fund
npm --prefix test/performance/integration/orms run verify -- --native
```

Earlier integration checks used PostgreSQL 18.0, MongoDB 8.2.3 and Redis 7.2.16: PostgreSQL and MongoDB each reported a scan of 20,000 records for one match, a deep page that walked 15,010 entries to return ten and a disk sort, and the indexed and keyset equivalents passed. Redis reported a real `KEYS` call, a batching finding for eight redacted `GET` reads and a request-local reuse finding for eight reads of a visible key.

### Follow one corpus label

In the pinned Immich checkout, [`session.service.ts:59`](https://github.com/immich-app/immich/blob/08fe0470fa884e1cddd42e9a19539fbe618c44bc/server/src/services/session.service.ts#L59) calls `filter` only to test whether any update field is present. The resulting array never leaves that condition. The reviewer marked the finding as a true positive because an existence check can stop at the first defined value and needs no result array.

```json theme={null}
{
  "pillar": "perf",
  "ruleId": "filter-for-existence",
  "file": "server/src/services/session.service.ts",
  "line": 59,
  "verdict": "tp",
  "note": "filter().length === 0 used only as an existence check"
}
```

The scorer joins review labels to default-level findings by checker, rule ID, repository-relative file and line. A matching `tp` counts toward precision and recall. A matching `fp` records a warning the reviewer judged incorrect. A `missed` label records an independently identified location that remains a recall miss until the checker reports it. A detection without an exact label stays unreviewed and contributes to neither precision nor recall.

With the Immich checkout at the manifest pin, run `npm run bench:corpus -- --repos immich --concurrency 1` to scan just that repository and compare its results. Run `npm run bench:scorecard` to render saved measurements and current labels without scanning the checkout.

## Docs site

The [Mintlify](https://mintlify.com) docs site lives in `docs/`, configured by `docs/docs.json`. Its guide pages (`docs/*.mdx` and `docs/checkers/*.mdx`) are written from `README.md` and `CONTRIBUTING.md`, so a change to either needs the same change on the matching page. Each rule under `docs/rules/` is also a site page. `npm run docs:rules` writes the rule lists between the `{/* loadwise:rules:start ... */}` markers of the checker pages and updates the Rules tab and legacy rule redirects in `docs/docs.json` (`test/shared/site-docs.test.ts` enforces this). MDX rejects HTML comments and a bare `<` or `{` in prose, so escape them with a backslash, as `\<` and `\{`.

When moving a published rule page, keep a one-link Markdown alias at its old GitHub path. Start the alias with the `loadwise:rule-alias` marker and add its path to `docs/.mintignore` so Mintlify serves the redirect.

## Before Opening a Pull Request

For a new rule or a large change, open an issue first so we can agree on the approach. Small fixes can go straight to a pull request. Report a vulnerability in Loadwise privately as [SECURITY.md](https://github.com/IbrahimHafez1/loadwise/blob/main/SECURITY.md) describes, not in an issue.

Run the full verification suite from the repository root:

```sh theme={null}
npm run check
npm run bench:recall
```

`npm run check` runs Prettier format checks, `oxlint --deny-warnings`, `tsc -p tsconfig.json`, and the full Node test suite.

* Keep rules, autofixes, and `--help` docs in sync. Add a new rule page alongside that checker’s existing canonical pages, such as `docs/rules/performance/<rule-id>.md` for a performance rule. Copy a neighbouring canonical page for the frontmatter and sections, then run `npm run docs:rules` to refresh the rule index in `README.md` and the docs site (`test/shared/docs-sync.test.ts` enforces this).
* For a new maintainability rule, run `npm run build` and then `node dist/scripts/scaffold-rule.js --id example-rule --description "Describe what the rule checks." --impact low` from the repository root. The scaffold inserts sorted registry and config schema entries, creates a canonical rule page, and reserves positive and safe-control tests. Implement the detector, fill in the fixtures, and run `npm run docs:rules` to refresh the indexes.
* For each detector or parser change, pair a small buggy example with its closest safe counterpart under `test/<checker>/`. When fixing a real report, reduce the original source to the smallest example that reproduces the mistake. Assert the rule ID and source location for the warning and check that the safe example has no warning from that rule. Keep these tests offline so they run in ordinary CI.
* For an autofix, use the CLI to apply the edit and rescan the file. Check that the finding clears, compare the original and fixed behavior on representative inputs and edge cases, and verify that a second fix leaves the file byte-for-byte identical.
* Insert a new rule id in sorted position in every rule registry list (`test/shared/registry-order.test.ts` enforces this), so parallel rule pull requests do not conflict.
* Keep commits small and focused: one logical change per commit (a rule, a fix, a refactor, a docs update), with its tests in the same commit, and a [Conventional Commits](https://www.conventionalcommits.org/) message such as `fix(rel): ...` or `feat(a11y): ...`. Don't mix unrelated changes, formatting sweeps or dependency updates into a feature commit. Each commit should build and pass its tests.
* Add a changelog fragment instead of editing `CHANGELOG.md`: one file `changes/<short-kebab-slug>.md` with `section: Added|Changed|Deprecated|Removed|Fixed|Security` in its frontmatter and the entry text as the body, written like a `CHANGELOG.md` bullet without the leading `- `. [changes/README.md](https://github.com/IbrahimHafez1/loadwise/blob/main/changes/README.md) has an example. This keeps open pull requests from conflicting over the same lines.
* Do not commit built `.js` / `.cjs` artifacts or `.tgz` archives (they are gitignored).

## Continuous integration

`CI passed` is the only check the `main` branch requires. It passes when every job in `.github/workflows/check.yml` succeeded or was skipped as the run's scope expects. Pushes to `main` run the full matrix. A pull request runs a scoped set: the Linux Node 24 shards always run, Windows and Node 22 run only when the change touches CI, packaging, editor, script or other platform-sensitive paths, and macOS runs only with the `full-ci` label. To force the full matrix, including macOS and the ARM64 VSIX, add the `full-ci` label and re-run all jobs. When hosted runners are busy (the run's first job waited more than two minutes for a runner), the tests run in the single `tests (serial)` job instead of the Linux shards.

## Pull request scope and conflicts

Keep a pull request to one or two rules. A refactor that touches many rules or shared code goes in its own pull request, so it can be reviewed and reverted on its own.

Split larger work into independently reviewable PRs. Base independent branches on `main`. Stack a PR on another branch when it needs an unmerged prerequisite, and name the prerequisite in the description.

When branches touch the same behavior, coordinate the order of edits. Resolve overlapping source and test changes together to preserve both intended behaviors. For rule index conflicts, reconcile the rule pages and sorted registries, then run `npm run docs:rules`. Keep each PR's changelog fragment. Review the resulting diff against its base and rerun the affected tests.

## Review comments

Loadwise is precision-first: a false alarm costs more than a missed detection. These block a merge until fixed: false positives, crashes, wrong output, wrong fixes, and docs that misstate behavior. A missed case (recall widening) or a new syntax family does not block. Reply to it, open an issue or a tracked follow-up, and resolve the thread.

## Releasing (maintainers)

1. In a pull request, bump the root and editor package versions and their lockfiles, verify the editor accepts the release version, and add the new release line to the supported versions in `SECURITY.md`. Then run `npm run changelog -- X.Y.Z`. It folds the fragments in `changes/`, moves the `[Unreleased]` notes in `CHANGELOG.md` under a new `## [X.Y.Z]` heading, and adds that version's compare link.

   The Zed extension in `integrations/zed` has its own version, independent of the npm package. Bump `version` in `integrations/zed/extension.toml` (a patch bump for fixes) only when files under `integrations/zed` changed since the last release tag; leave it alone otherwise. The release workflow fails when those files changed and the manifest version did not.

2. After it merges, wait for `check`, `codeql` and `scorecard` to pass on the exact merge commit on `main`. Then push the tag `vX.Y.Z` at that commit. The `release` workflow checks the commit again, runs the full release checks and stages the npm publish through Trusted Publishing.

3. Approve the staged version on npmjs.com with 2FA; only then does it go live. A `-` in the version (for example `v0.6.0-rc.1`) publishes under the `next` dist-tag instead of `latest`. Approve stages in version order and reject an older pending one, since approving it later would move the dist-tag back to the older version.

4. The npm approval verifier waits up to two hours. After approval, the GitHub release job verifies and publishes the versioned VSIX editor packages and moves the `v0` Action tag for a stable `v0.x` release. If the wait times out, approve the version and re-run the failed job.

   If approval will be delayed, you can cancel the **verify approved npm package from this run** job after npm staging succeeds. After approving on npmjs.com, re-run the failed and cancelled jobs in the original tag run. That run keeps the tag ref, so it signs the editor packages and attaches the attestation bundle. A manual **release** run with `release-tag` and the original `source-run-id` runs from the default branch and skips attestation, so it stops before publishing the GitHub release unless the tagged run already uploaded the bundle. Use it only to repair a release that the tagged run signed. It checks the approved npm tarball and the release tag against the original run, then reuses its verified editor artifacts. The original tarball and editor artifacts must still be available. An existing VSIX asset is reused only when its digest matches the selected run.

5. If npm approval is still pending after a failure, settle the stage on npmjs.com before retrying. Approve a good build to continue from the published version, or reject the stage before staging it again. A duplicate stage fails with `409 Conflict`.

6. After the GitHub release, the **Sentry release** workflow records the published version and associates its commit range when a previous release is available. Eligible tag pushes and resumed releases use the source maps from the original tag run. Source-map preparation has its own job and can fail without blocking npm or GitHub publication. If the map artifact is missing, Sentry still associates the verified release and reports that symbols were unavailable. To upload symbols later, rerun **prepare Sentry source maps** in the original tag run when available, then retry **Sentry release** in the release workflow.

   For a published tag whose npm `gitHead` matches the tag commit, run the standalone **Sentry release** workflow to backfill metadata and commits. This backfill skips source maps.

   When npm has no `gitHead`, run **release** manually from the default branch with `release-tag` and the original `source-run-id`. The resume verifies the public npm version against the original tarball and passes the verified commit and integrity to Sentry. It requires the original tarball and editor artifacts. Uploading symbols for releases with source maps requires the original tag run's map artifact.

### Signing an older release

A release published before signing existed has no `loadwise-<version>.sigstore.json` asset. Once per such release, run the **sign published release** workflow manually with `release-tag`. It checks every VSIX against the digest GitHub recorded and the npm tarball against the registry integrity, signs them with a custom predicate (not build provenance, since this workflow did not build them), and uploads the bundle. It stops without changes when the bundle already exists. [Verifying release signatures](https://github.com/IbrahimHafez1/loadwise/blob/main/docs/release-signatures.md)

### Editor registry preflight

The desktop extension is not published to the Visual Studio Marketplace or Open VSX. GitHub Releases is the only distribution channel, and `loadwise editor setup` installs from it. The preflight below is for a maintainer who later decides to publish to a registry. Before publishing, confirm access to the `IbrahimHafez1` publisher or namespace and the `IbrahimHafez1.loadwise` listing on each registry. Keep the same extension ID, license, description and repository link as the packaged extension. [Visual Studio Marketplace publishing](https://code.visualstudio.com/api/working-with-extensions/publishing-extension) · [Open VSX publishing](https://github.com/eclipse-openvsx/openvsx/wiki/Publishing-Extensions) · [Open VSX namespace access](https://github.com/eclipse-openvsx/openvsx/wiki/Namespace-Access)

Use GitHub CLI 2.75.0 or later (which includes asset digests in `gh release view --json assets`) and Python 3.11 or later to check the six assets from one verified GitHub release before any registry upload. Set `release_tag` to the release under review.

```sh theme={null}
release_tag=v0.9.0
gh release view "$release_tag" --json tagName,isPrerelease,assets > editor-release.json
gh release download "$release_tag" --pattern '*.vsix' --dir editor-assets --clobber
python scripts/plan-editor-registry.py editor-release.json editor-assets
```

The preflight checks each archive's size and SHA-256 against GitHub, verifies the embedded ID, version, target and channel, and prints an ordered JSON plan. It runs offline after the download and has no registry credentials or upload step. A repeat on the same archives produces the same plan.

Keep stable and pre-release catalog versions distinct. The registry version is numeric `X.Y.Z`, and a pre-release VSIX also carries the editor package's pre-release marker. The existing build makes stable VSIX packages. Run the preflight with `--channel pre-release` only for a separately verified numeric editor release built with that marker and flagged as pre-release on GitHub. An npm release suffix such as `-rc.1` cannot serve as its editor catalog version. [VS Code pre-release versioning](https://code.visualstudio.com/api/working-with-extensions/publishing-extension#prerelease-extensions)

Once registry access is confirmed, have the maintainer review the plan and publish those exact archives using each registry's documented upload method. Record the registry, channel, version, target and archive digest for each successful upload. On a retry, check what exists for each target, skip uploads already verified against that record, and investigate a mismatch before continuing. Leave the GitHub release assets available.

Catalog install and update still require a live check in compatible editors. In disposable profiles, verify that the stable listing selects the correct native target and starts diagnostics on the quickstart fixture, that a stable update preserves activation, and that a separately published preview is offered through pre-release opt-in. Repeat for every supported OS and architecture and record the registry, editor version, selected target and result.

## License

By contributing, you agree that your contributions will be licensed under the [Apache License 2.0](https://github.com/IbrahimHafez1/loadwise/blob/main/LICENSE).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.