LibreChat/.github/workflows/static-checks.yml
Marco Beretta 339a323ff1 🎨 chore: Enforce Design-System Rules With @shadcn/lint (#15981)
* 🎨 chore: Enforce Design-System Rules With @shadcn/lint

Registers @shadcn/lint for client/src and packages/client/src, resolving\n@librechat/client as the design system so a className that overrides what a\nprimitive owns is reported with the variants and sizes to use instead.\n\nFive rules run at error. no-unknown-classes stays off: it needs Tailwind v4.\nContracts record what callers legitimately own (text typography, skeleton\nsilhouette); eslint-suppressions.json records the 3,141 violations the tree\nalready carried, so the rules gate new code without a tree-wide migration.\n

* 🩹 fix: Close the Gaps Review Found in the Design-Rule Gate

Five findings against this pull request, and one that killed its CI:

- The lockfile entries this change added resolved to a private mirror, so every
  job died in `npm ci`. They now resolve from registry.npmjs.org, with each
  integrity hash checked against the tarball npmjs.org serves.
- The pre-commit hook ran ESLint twice and the first run had no
  `--pass-on-unpruned-suppressions`, so it exited 2 on the suppression the fix
  had just made unused and lint-staged never reached the command that tolerates
  it. One invocation now does both; ESLint applies suppressions after fixes, so
  it reports the post-fix state.
- `scripts/static-checks.mts` omitted that same flag, so `npm run static-checks`
  failed locally on a diff the Static Checks lane passes.
- `lint:design:suppress` recorded a moved file's new path and left the old one
  behind, because only `--prune-suppressions` removes it and ESLint refuses both
  flags in one run. The script now chains the prune, and CLAUDE.md documents the
  scoped recipe that does not re-baseline the whole surface.
- The design rules matched only `.ts`/`.tsx`, so the client's `.jsx` entry points
  bypassed all five. Both globs now cover `.js`/`.jsx`; the one violation that
  exposed — an inline `display: none` on App.jsx's silent-audio iframe — is fixed
  at the source rather than recorded.
- A suppressions-only diff started no workflow and nothing read the baseline. It
  is now a trigger path and its own filter group, and a new `suppressions` check
  rejects a shape ESLint cannot load, a count no run can reach, a rule the plugin
  does not define, and a path that no longer exists.

The count-neutral swap two reviewers raised is not closed: ESLint's baseline
format records a count, not violation identities, so replacing one suppressed
violation with another of the same rule in the same file is invisible here.
CLAUDE.md now says that instead of implying detection.

Four `@scenario`-tagged specs cover the developer-facing behaviour: the report a
caller gets on a primitive override, a `.jsx` file being checked, the fixing
commit staying green (with the counter-proof that it exits 2 without the flag),
the move recipe dropping the old path, and every locked tarball being fetchable
from the public registry.

* 🧪 fix: Close the Dormant-Entry and Gate-Trigger Gaps

The suppressions gate did not run when the file that implements it changed, a
count recorded against a path no design-rule lint reaches passed validation, the
documented re-record chain could not run under cmd.exe, and the lockfile
scenario failed a legitimate SheetJS upgrade. The trigger scenarios also ran
four full-tree sweeps inside one test that declared a 180s deadline for work
measured at 100-280s per sweep.

- scripts/static-checks.mts: `scripts/static-checks.mts` joins the suppressions
  filter and the whole-record trigger, and a recorded path ESLint never reports
  on is rejected as dormant.
- package.json/CLAUDE.md: `|| node -e ""` in place of `|| true`, which cmd.exe
  does not define.
- e2e: the whole-record triggers are a matrix over a miniature repository (2-6s
  each instead of 100-280s), the oversized scenario is split into five
  behaviour-shaped ones, scratch baselines live in os.tmpdir(), and the lint
  gate runs in one project because it has no viewport.

* 📏 chore: Re-Record the Counts Dev Moved Under the Backlog

Rebasing onto dev brought #16067, which restyled three files the recorded
backlog speaks for: MarketplaceSidebar.tsx gained one arbitrary value and two
`no-restyle` violations, ToolsMarketplaceDialog.tsx gained one, and SkillsDialog
lost one. Counts above the file fail the lint for whoever edits it next; the one
below leaves capacity a later violation would spend. Scoped re-record and prune
of those three paths, per the recipe in CLAUDE.md.

* 🧭 test: Run the Copied Runner From the Tree It Is Testing

The trigger matrix pointed the copied static-checks runner at a miniature
repository but invoked it from the real one. The runner derives its repository
from its own location and relativizes file arguments against the working
directory, so `eslint.config.mjs` resolved to a path outside the miniature tree,
the suppressions group read as "not affected by this diff", and the scenario
passed a check that never ran (verify recorded it as a failure: exit 0 where a
rejection was expected). `run` now takes a `cwd`, and both synthetic-root probes
use it.

* 🔇 fix: Reject a Disable Comment With Nothing Behind It Yet

Comparing the two ESLint runs finds a directive only while it is silencing
something. A `/* eslint-disable shadcn/no-raw-colors */` over a file with no raw
colour left both runs agreeing, so it landed unseen and then silenced the first
violation anyone added to that file. The configured run now also asks for unused
directives, which is how ESLint names a disable with nothing behind it: a
dormant design-rule disable and a dormant blanket disable are rejected, a
dormant directive for another rule is not. Neither root carries one today (0
reports across 2,241 files), so what this rejects is new ones.

The same pass also has to see the primitives' variants, so `validateSuppressions`
builds `packages/client/dist` before the directive check rather than inside the
capacity scan that follows it; without the metadata both runs report strictly
fewer design diagnostics and a comment silencing a `no-restyle` violation is
invisible to the comparison.

* 🧱 fix: Count the Library's Build Inputs as Sources

`designMetadataIsFresh` compared `packages/client/dist` with `packages/client/src`
alone, so a commit that changed only the library's manifest or its tsdown config
left every source older than the build and the runner skipped the rebuild. The
design rules then classified against output emitted under the old contract —
locally only, since CI always builds before validating, which is the shape of
divergence nobody sees until the lane disagrees with the commit that passed.

Both files already count as design metadata everywhere else (the suppressions
filter, the whole-record trigger); they now count in the freshness comparison
too. The scenario runs the miniature repository with an observable
`build:client-package`: a current build is not rebuilt, and touching either
input asks for one.

* ⏱️ test: Set the Times the Freshness Rule Compares

The rebuild scenario wrote the build output and then the manifest, and node
wrote both inside the same millisecond, so the manifest was not newer than the
build and the runner correctly declined to rebuild — the assertion failed on the
filesystem clock rather than on the rule. The scenario now sets each mtime it
depends on with `utimesSync`, which is what it meant to say.

* 🩹 fix: Restore the Write the Import Edit Dropped

Adding \ to the import list replaced \ instead of joining it, and nothing local caught it: no tsconfig covers e2e/, and the flat config leaves \ to TypeScript there. The mock harness did — every scenario in the file failed with ReferenceError — which is the point of running it. Typechecked the four scenario files directly this time.

* 🚫 fix: Reject Every Inline Escape, Not Only the Ones in Use

Codex found three more ways past the gate, one shape each. A blanket
\ busy silencing an unrelated rule is used, so ESLint's
unused-directive report never names it, and the configured-versus-ignored
comparison sees no design delta — it waits for the file's first design
violation and takes it. Inline \ over a
clean file is invisible the same way. And a nested baseline that drops an entry
for an unchanged source was checked against its remaining keys only, so the
violation it used to speak for went unread.

The directive check now has two halves: ESLint still answers what a comment is
silencing today, and the comments themselves are read out of the parser — not
the text, so a string that reads like a directive is not one — for a disable
naming a design rule, a blanket disable, or inline configuration naming a
design rule, whether or not anything is behind it yet. That supersedes
\, which could only see the unused ones.
Neither design root carries any of the three today.

\ unions the entries a diff removes into a nested baseline's
file list, and \ joins the design metadata: it
carries the \ mapping, the entry emit and the include/exclude that decide
what reaches the bundle the rules read, which is why the repository's own build
caches key on \.

* 🔐 fix: Make the Hook Select What the Lane Selects, and Distrust a Half-Built Bundle

Two more shapes of the same mistake — trusting a proxy for the thing itself.

The pre-commit group listed individual files while the Static Checks lane's
filter also names both design roots, so staging a primitive ran ESLint locally
and the whole-record sweep only in CI: the commit passed and the lane failed on
callers nobody staged. The hook's group is now the lane's filter pattern for
pattern, and the count-edit scenario reads both files and fails when the two
lists differ, so the next path added to one has to reach the other.

Freshness took the newest timestamp under \ as proof of a
finished build. The build empties that directory before it writes, so a build
that failed halfway leaves a recent directory over a bundle with no entry
point, and every later run skipped rebuilding it. The check now also requires
what \ promises inside \ — its entry fields
and every string leaf of \ — to exist.

* 🧾 fix: Give the CDN Exception to xlsx, Not to the Host

The lockfile rule allowed \ for anything and then compared
versions against the base branch, so regenerating the lockfile against that CDN
could move any package off the public registry at the same version and pass.
The exception now belongs to the package — \, at any version, nested or
not — and every other entry has to come from the registry, which drops the
version comparison and the shallow-clone caveat with it.

The rule is a function the scenario applies to the repository's lockfile and to
lockfiles written for the purpose: an xlsx upgrade on its CDN passes, lodash
rewritten onto the same CDN at the same version fails, a new package from a
private mirror fails, and a nested xlsx is still xlsx.

* ↩️ fix: One Local Entry Point, Asked of the Runner

The pre-commit group I added for the backlog and the design metadata was
redundant and slower: \ already ends by running the runner
over the staged diff with \, and that run
selects its groups from the same filters — including both design roots, and
including deletions, which lint-staged never hands to a task. The group made
the whole-record sweep run twice for one commit. It is gone.

The scenario now asserts the property instead of a copy of the list: the hook
still runs the runner over the staged diff, and for every path the lane's
suppressions paths-filter names, the runner reports that check as selected
(\), while a path outside both roots is not affected.

* 🗺️ fix: Assert Where the Rules Are Asked, Not Only What They Found

A report cannot say where the rules were asked. Narrowing the design block over
a subtree that happens to be clean today — \, say —
produces no new diagnostic, no changed count, and no baseline entry to inspect,
so every gate stays green while the styling written there next goes unread.

The new scenario asks the resolved flat configuration instead: for one
representative path of each source extension in every directory under both
roots, all five design rules must be at error in the app and at the library's
own profile inside \ (overriding a primitive is off there;
colour and inline geometry still hold), and server code must carry none of
them. 1,184 paths, answered through ESLint's API in one process in under a
second — \ would have been eleven minutes of subprocesses.

* 🎯 fix: Spend the Budget Once — Reject a Swap Inside the Allowance

The recorded count is a budget per file and rule, and until now it could be
respent: removing one raw colour while adding a different one keeps the total
equal, so ESLint suppresses the new violation inside the old allowance and the
count checks see nothing move. The backlog was documented as unable to tell
that apart, and it was the one hole Codex kept finding its way back to.

What the totals cannot distinguish the diagnostics can. For every design source
a diff touches, the runner now lints that file's version at the base — through
ESLint's API, one process for the whole diff — and reports a design-rule
message the head has that the base did not, naming it. A violation that only
moved keeps its message and is not reported; a file with no version at the base
has no allowance to hide in and the count checks already answer for it.

Measured on the checkout: swapping one `fill="#AFC1FF"` for `fill="#BEEF11"`
in a file recording five raw colours is rejected in 4.9s naming the new one,
and the unchanged file passes. The scenario proves all three states — recorded,
moved, swapped — in a miniature repository with a history of its own, and
CLAUDE.md no longer claims the swap is undetectable.

* 🧰 fix: The Root Manifests Are Build Inputs Too

\ is defined in the root manifest and runs with the
toolchain the root lockfile pins, and both already select the suppressions
check — but neither counted as an input to bundle freshness, so a commit that
changed the build definition could validate locally against output made by the
previous one while CI rebuilt. They count now, beside the library's own
manifest, build config and compiler options, and the rebuild scenario drives
the lockfile case through the miniature repository's observable build.

* 🧭 fix: Read the Base From the Merge Base, and Give a New File No Allowance

Two holes in the swap check, both about what "the base" means.

It read each changed file's prior version from the base branch's tip, while the
changed-file set comes from \. With \ moving under a branch,
that calls a violation dev added since the branch diverged this change's doing,
and forgives one this change added that dev happens to carry. It resolves the
merge base once and reads from there.

And a file with no version at the base was skipped, so adding a source with a
violation and recording it in the same commit passed as "already recorded".
A file the change adds has no allowance to inherit: every design violation in
it is new. Renames are followed (\), so the
documented re-record of a moved path stays green — its violations came with the
file.

The scenario now walks recorded, moved, swapped, added-with-its-own-entry and
renamed through one miniature repository with a history of its own.

* 🔗 fix: One Base Commit, Asked Once

\ resolved the merge base; \ still read
the baseline from the base branch's tip, so the two checks in the same run
disagreed about what "before" meant — and an entry the base branch edited after
the branch diverged entered \ as though this change had edited it.

\ resolves it once and both ask it.

* 🔤 fix: A Suppressed Message Carries Its Text

\ omitted \, and the swap check reads it
— the union of messages and suppressed messages is what a file's diagnostics
are, and what the baseline silences is exactly what that check has to see.
Nothing local caught it: node strips types without checking them and no
tsconfig covers scripts/, so the runner is now typechecked directly
(                                                                               
                This is not the tsc command you are looking for                
                                                                               

To get access to the TypeScript compiler, tsc, from the command line either:

- Use npm install typescript to first add TypeScript to your project before using npx
- Use yarn to avoid accidentally running code from un-installed packages, clean).

* ⚖️ fix: Let the Record Grow, Out Loud

The swap check reported every violation a change added, which also forbade the
one path CLAUDE.md sanctions: add the violation and raise the count, so the
debt arrives as a line in the diff a reviewer reads. What separates that from a
swap is not the violation, it is whether the record said so — a swap keeps the
count still.

The check now charges each new diagnostic against how much that entry's count
grew between the merge base and here, and reports only what the growth does not
cover. Measured: a swap at an unchanged count fails, the same violation with
the count raised passes, and raising nothing fails naming the class. CLAUDE.md
says which of the three is which.

* 🚧 fix: A File the Change Adds Brings No Allowance

Letting the record grow to cover a new violation is right for a file that
already existed — the raised count is the line a reviewer reads — but it also
let a brand-new source arrive with its own entry, which is the backlog
recording what the tree never owed. Growth applies only where there is
something to grow: a file present at the merge base, renamed or not. A file the
change adds owes everything in it, and the message says so.

* ✏️ test: Assert the Wording the Added-File Rule Uses

The scenario still expected "is new here" for a file the change adds, which now
gets its own message — the backlog records what the tree owed, not what a new
file brings. The harness caught it; the assertion follows the rule.

* 🧮 fix: Ask Git What Existed, and Where Its Entry Lived

Three faults in the new swap check, one cause: it inferred from content what
only git can answer.

A tracked empty file at the base reads as absent, so an existing file was
treated as newly added and its recorded growth refused. A renamed file's
growth was measured at the new key, where the base has no entry at all, so the
move itself looked like room to spend. And a base commit missing from the clone
made every changed file look new, silently.

Existence is now \ succeeding, the allowance is read under the name
the entry had (the rename map already resolved the source; it resolves the
entry too), and a base commit that is not in the clone is reported rather than
guessed at. Measured: a rename carrying a new violation with its count raised
at the new key fails, a plain rename passes, a swap at an equal count fails.

* 🗃️ fix: A Deleted Baseline Is a Deleted Baseline, Nested or Not

The root baseline's deletion failed the check; a nested one was quietly dropped
from the target list by the same \ filter that was meant to skip
paths never present. What a nested baseline silences goes back to being
reported — or stops being — and nothing else reads it, so its deletion is the
same failure and now says which file is missing.

* 📚 fix: A Baseline in the Diff Is Read in Full

The comment said a baseline named in the diff is checked in full; the code
checked only the entries the diff moved, because \ made
\ non-empty and the full-record branch required it to be empty. So a
count edit never revalidated the rest of the record — dormant paths and stale
counts in unedited entries went unread. Editing the baseline now reads every
path it records.

And the rename map keyed on git's raw line, so a CRLF checkout left a \ on
the new path and the rename never matched — the file read as added and its
inherited allowance was refused. The lines are trimmed.

* 🧷 fix: Lint the Base Under the Name It Had, and Compare a Commit With Its Parent

Two last seams in the swap check.

A renamed file's base contents were linted under the new path, so moving a
component out of \ — where overriding a primitive is the
library's own business — into \ made the destination's stricter
rules apply to both sides: the diagnostics the move itself introduces looked
inherited, and a matching entry would have hidden them. The base is linted as
the path it had.

And \, the documented single-commit mode, resolved its
comparison to \ — the commit against itself, which forgives everything.
It resolves to the commit's parent.

* 🔖 fix: Quotes Do Not Hide an Inline Rule Configuration

ESLint reads \ exactly as it reads
the unquoted key, but the comment scan required the colon to follow the rule id
directly, so the quoted form passed over a file that does not violate the rule
yet — and then silences the first violation a primitive or config fan-out
creates there. Over a violating file the two-run comparison always caught it;
the dormant case is the one that slipped. The scan accepts either quoting, and
the scenario carries the quoted spelling beside the rest.

* 🧪 perf: A Spec Is Not Component Metadata

Both roots the design rules police are full of specs — every primitive in
`packages/client/src/components` has one — and editing any of them ran the
two-root suppression sweep, because the metadata predicate asked only whether
the path was a lintable source under a metadata root. A spec is neither: the
flat config turns all five design rules off inside it and the library's
tsconfig keeps it out of the bundle the caller rules resolve primitives
through, so it carries no `cva` variant and can report no design diagnostic of
its own.

`packages/client/src/components/Button.spec.tsx` through the runner:
59.7s before, 0.0s after.

The same `DESIGN_TEST_SOURCE` test is applied everywhere the invariant holds:
the freshness input no longer treats a spec as something `dist` is built from
(directory mtimes stay, so an added or deleted source still forces a rebuild),
the directive gate no longer fails a commit over a comment in a file where the
design rules are already off, and the base-vs-head lint no longer fetches a
spec's base version to ask a question with one possible answer.

* 🔎 fix: A Build That Reports Success Is Not a Build

Two gates trusted a signal instead of the condition it stands for.

`buildClientPackage` returned on the build's exit code. A build that exits 0
while leaving `packages/client/dist` incomplete or older than its sources left
`designMetadataIsFresh()`'s answer exactly as it found it, and the suppression
lint that follows then classified callers against a bundle describing something
else — reporting fewer violations than CI, which is the failure the rebuild
exists to prevent, reached through the branch meant to fix it. The freshness
question is now asked again after a successful build, and a bundle still stale
is an error naming `packages/client/dist`.

The workflow's `on.pull_request.paths` named only the root
`eslint-suppressions.json` while the inner `suppressions` filter names
`**/eslint-suppressions.json`. A diff touching only a nested baseline outside
`api|client|config|packages|scripts` — `e2e/fixtures`, say — started no
workflow at all, so `validateSuppressions()` never ran over exactly the nested
baselines it advertises. The trigger carries both spellings now.

The miniature repository's `build:client-package` writes the bundle its
manifest promises instead of only a marker, so the rebuild rows assert a
finished build rather than a claim of one, and a build that writes nothing is
its own row.

* 🧭 fix: Ask the Tool, Don't Reconstruct Its Answer

Four findings on the last head, and three of them were the next variant of a
family this branch had already patched once. The shared cause is one habit:
the gate re-derived a fact from a cheaper proxy instead of asking whatever owns
it, and every round found another case the proxy got wrong.

An inline `eslint` configuration comment was matched by the spelling of its
rule key, so `shadcn/x`, `"shadcn/x"`, `"shadcn\/x"` and `"shadcn\u002fx"` —
one key, four spellings, all of which ESLint honours — needed four regexes.
The key is now decoded before it is compared, which ends the family rather
than adding the fourth.

Bundle freshness reduced a set of outputs to the newest file anywhere under
`dist`. A resolver loads one entry, not a directory, so a build that rewrote
the ESM bundle and left the CJS one or the type declarations behind passed
while `@shadcn/lint` read the stale one. Every declared output is compared
now, which is the same reason their existence was already checked one by one.

Target discovery read `git diff --name-only` with rename detection, which
names one side. `git mv eslint-suppressions.json backlog.json` therefore
selected no group that owns the source, and the baseline's disappearance was
reported by nothing. `--no-renames` at the single funnel makes a rename two
paths; the one caller that wants the pairing asks for it separately.

The fourth was the parity assertion added last round, sitting in the mock
Playwright lane — whose own trigger excludes `.github/workflows` apart from its
own file, so a workflow-only diff never ran the assertion guarding it. The
claim moved into the runner, where the file that can break it already
activates the group, and the scenario now exercises the runner both ways over
a copy of the real workflow instead of reimplementing its parser.

* 📝 docs: Say Which Swaps the Ratchet Misses

The ratchet paragraph claimed a swap arrives as a failure, full stop. Two do
not, and a reader deciding whether to trust the gate needs both.

A swap whose diagnostic message equals the one it replaced is invisible,
because the comparison keys on the message and some rules name the property
without the value — `Inline style sets display.` is one message for `none` and
for `flex`. And a swap the diff itself causes, by changing a primitive or the
config, is invisible because both versions are linted under the head's design
inputs.

Tracked at berry-13/LibreChat#70 and berry-13/LibreChat#69.

* 📏 chore: Re-Record the Count Dev Moved Under the Backlog

`dev` fixed one `shadcn/no-restyle` violation in
`client/src/components/SharePoint/SharePointPickerDialog.tsx`, so the rebased
branch records 8 where the file now has 7. An entry with slack is exactly what
this change added a check for: the unused 1 would silence the next violation
anyone writes there, and the gate says so rather than letting it through.

`npm run lint:design:prune` drops the one count; the trailing newline it strips
is restored by prettier, the way the pre-commit hook's `*.json` group does.

* 📝 docs: Drop a Recorded Count That Dev Keeps Moving

The backlog total moves with every rebase that picks up new violations from
`dev`, so a number written into CLAUDE.md is stale by the next re-record — it
read 3,230 against a baseline holding 3,232. The recipe does not need the
figure; `eslint-suppressions.json` is the record.

* 📏 chore: Re-Record the Counts Canary Moved Under the Backlog

Retargeting onto canary changes the tree the design rules read, so five
files carry different violation counts than the recorded backlog claims:
Wakeup and SubagentConversation shed no-restyle violations and picked up
a require-static-classes one, and Ledger, UnifiedSidebar and ChatRoute
each gained one. Re-recorded those entries and pruned; nothing else in
the baseline moved.

* 🧱 fix: Build the Primitives Before Recording What They Own

`lint:design:record` was the one exposed design script that linted without
building `packages/client/dist` first. The rules read each primitive's `cva`
variants out of that bundle, so a fresh checkout or a primitive change left
the recording run classifying against a library that does not exist yet and
writing counts lower than the ones CI reports.

Moved the build onto the record script, where the other three already have
it, and dropped it from the `lint:design:suppress` wrapper so the wrapper
still pays for exactly two builds. A build failure inside the wrapper is
still loud: the record step cannot rewrite the baseline when the build it is
chained to fails, and the prune that follows does not swallow its own.

* 📏 chore: Re-Record the Counts Canary Moved Under the Backlog

Rebasing onto canary picks up PR #15798, which rewrote the agent marketplace
components, so eighteen recorded entries no longer describe the files they
name: AgentDetail is gone, AgentCard traded its restyle and arbitrary-value
violations for inline styles, AgentDetailContent grew to eighteen restyles,
and CopyLink, GridSkeleton, Marketplace, MineFilterToggle, SortDropdown and
LoadingDots arrived with violations nothing had recorded.

Re-recorded and pruned; every entry that moved belongs to a file that commit
touched, and nothing else in the baseline changed.

* 🧪 test: Assert the Record Asks for a Build Before It Writes

The build-freshness scenario covers the runner. Nothing covered the other
entry point: `npm run lint:design:record`, which writes the budget every
later change is measured against and, until now, linted whatever bundle
happened to be on disk.

The miniature repository's `build:client-package` appends to a log, so the
scenario can ask whether the record built before it wrote, and whether a
build that fails still stops the wrapper now that the wrapper no longer
carries a build of its own.

---------

Co-authored-by: berry-13 <berry-13@users.noreply.github.com>
(cherry picked from commit 8d5e1a75ee)

Original-PR: https://github.com/LibreChat-AI/LibreChat/pull/15981
2026-10-01 03:46:16 +00:00

983 lines
46 KiB
YAML

name: Static Checks
on:
pull_request:
paths:
- 'api/**'
- 'client/**'
- 'config/**'
- 'packages/**'
- 'scripts/**'
- 'package.json'
- 'package-lock.json'
- 'eslint.config.mjs'
# Both spellings: the trigger has to start the workflow for the root
# baseline and for a nested one outside the source trees above, which is
# exactly what the `suppressions` filter below and validateSuppressions()
# claim to cover.
- 'eslint-suppressions.json'
- '**/eslint-suppressions.json'
- '.github/workflows/static-checks.yml'
- '!**.md'
permissions:
contents: read
pull-requests: read
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
env:
NODE_ENV: CI
NODE_OPTIONS: '--max-old-space-size=${{ secrets.NODE_MAX_OLD_SPACE_SIZE || 6144 }}'
jobs:
static-checks:
name: Static checks
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout repository
uses: actions/checkout@v5
with:
# Full history is load-bearing: changed-file steps diff against the
# PR base and the ESLint regression gate reads the base ref's
# config via git show — a shallow checkout breaks both.
fetch-depth: 0
# scripts/static-checks.mts mirrors these filters to run the same checks
# locally on a commit's diff — keep the two in sync.
- name: Detect affected checks
id: paths
uses: dorny/paths-filter@v4
with:
predicate-quantifier: 'some-with-excludes'
filters: |
eslint:
- 'api/**'
- 'client/**'
- 'packages/**'
- 'eslint.config.mjs'
- 'eslint-suppressions.json'
- '.github/workflows/static-checks.yml'
- '!**.md'
eslint_config:
- 'eslint.config.mjs'
- '.github/workflows/static-checks.yml'
# The recorded design-rule backlog is data the lint reads, not code it
# lints, so a diff that only edits it matches no source file. Its own
# group runs the baseline validation below; it deliberately stays out
# of `eslint_config`, which gates the full-tree double sweep and could
# learn nothing from a count changing.
suppressions:
- 'eslint-suppressions.json'
- '**/eslint-suppressions.json'
- 'client/src/**'
- 'packages/client/src/**'
# The bundle the rules resolve primitives through is named by the
# library's manifest, produced by its build config and shaped by
# its compiler options.
- 'packages/client/package.json'
- 'packages/client/tsdown.config.mjs'
- 'packages/client/tsconfig.json'
- 'eslint.config.mjs'
# The plugin is a dependency: a bump changes what the rules
# classify and a removal takes them with it, and neither touches a
# source file.
- 'package.json'
- 'package-lock.json'
# The runner is the gate: `validateSuppressions` is what a recorded
# count is measured against, so a change to it has to run against
# the record — the ESLint step above only ever sees sources.
- 'scripts/static-checks.mts'
- '.github/workflows/static-checks.yml'
- '!**.md'
config:
- 'api/**'
- 'config/**'
- 'packages/**'
- '.github/workflows/static-checks.yml'
- '!**.md'
i18n:
- 'api/**'
- 'client/src/**'
- 'packages/client/**'
- 'packages/data-provider/src/**'
- 'packages/data-schemas/src/**'
- '.github/workflows/static-checks.yml'
- '!**.md'
runner:
- 'scripts/static-checks.mts'
- '.github/workflows/static-checks.yml'
unused_packages:
- 'api/**'
- 'client/**'
- 'packages/api/**'
- 'packages/client/**'
# Every workspace manifest the JSON validation step covers, plus
# the ones whose dependencies feed the unused-package calculation
# through api/package.json's @librechat/data-schemas entry.
- 'packages/data-provider/package.json'
- 'packages/data-schemas/package.json'
- 'package.json'
- 'package-lock.json'
- '.github/workflows/static-checks.yml'
- '!**.md'
- name: Set up Node.js 24.16.0
uses: actions/setup-node@v5
with:
node-version: '24.16.0'
cache: npm
- name: Install dependencies
id: install_dependencies
continue-on-error: true
run: npm ci
# The @shadcn/lint design rules read each primitive's `cva` variants through
# the @librechat/client entry point, which resolves to packages/client/dist.
# Without it they classify nothing and report strictly fewer violations than
# the same tree does on a machine that built the package — a lint that passes
# for the wrong reason, and a recorded baseline that cannot be trusted.
- name: Build client-package for the design rules
id: design_rules_build
if: always() && (steps.paths.outputs.eslint == 'true' || steps.paths.outputs.suppressions == 'true')
continue-on-error: true
run: npm run build:client-package
# Run ESLint on changed files within the api/, client/, and packages/ directories.
- name: Run ESLint on changed files
id: eslint
if: always() && steps.paths.outputs.eslint == 'true'
continue-on-error: true
run: |
# Extract the base commit SHA from the pull_request event payload.
BASE_SHA=$(jq --raw-output .pull_request.base.sha "$GITHUB_EVENT_PATH")
echo "Base commit SHA: $BASE_SHA"
# Get changed files (only JS/TS files in api/, client/, or packages/)
mapfile -d '' -t CHANGED_FILES < <(
git diff -z --name-only --diff-filter=ACMRTUXB "$BASE_SHA" HEAD |
grep -zE '^(api|client|packages)/.*\.(js|jsx|ts|tsx)$' || true
)
# Debug output
echo "Changed files:"
printf '%s\n' "${CHANGED_FILES[@]}"
# Ensure there are files to lint before running ESLint
if [[ ${#CHANGED_FILES[@]} -eq 0 ]]; then
echo "No matching files changed. Skipping ESLint."
exit 0
fi
# Run ESLint
# --no-warn-ignored: changed files under config-ignored paths
# (e.g. packages/data-schemas/misc/**) must not fail --max-warnings=0
# Invoke the installed binary, not `npx`: npm exec joins the whole
# command into one shell string, and Linux rejects a single argv
# string over 128 KiB (MAX_ARG_STRLEN) — past ~2,200 changed files
# npx dies with exit 249 and no output.
# --pass-on-unpruned-suppressions: the @shadcn/lint design rules run at error
# against a recorded backlog in eslint-suppressions.json. Fixing one of those
# violations leaves its suppression unused, which otherwise fails the PR that
# fixed it; `npm run lint:design:prune` tightens the counts.
node_modules/.bin/eslint --no-error-on-unmatched-pattern \
--config eslint.config.mjs \
--no-warn-ignored \
--max-warnings=0 \
--pass-on-unpruned-suppressions \
-- "${CHANGED_FILES[@]}"
# Run Prettier --check on the same set of changed files to catch
# formatting drift in PRs that bypassed the local pre-commit hook
# (e.g. GitHub UI edit-and-merge, `git commit --no-verify`).
- name: Run Prettier --check on changed files
id: prettier
if: always() && steps.paths.outputs.eslint == 'true'
continue-on-error: true
run: |
BASE_SHA=$(jq --raw-output .pull_request.base.sha "$GITHUB_EVENT_PATH")
mapfile -d '' -t CHANGED_FILES < <(
git diff -z --name-only --diff-filter=ACMRTUXB "$BASE_SHA" HEAD |
grep -zE '^(api|client|packages)/.*\.(js|jsx|ts|tsx)$' || true
)
if [[ ${#CHANGED_FILES[@]} -eq 0 ]]; then
echo "No matching files changed. Skipping Prettier."
exit 0
fi
echo "Files to check:"
printf '%s\n' "${CHANGED_FILES[@]}"
# `prettier --check` exits non-zero if any file would be reformatted.
# Suggest the local fix in the failure message so contributors aren't
# left guessing how to resolve.
if ! node_modules/.bin/prettier --check --no-error-on-unmatched-pattern -- "${CHANGED_FILES[@]}"; then
echo ""
echo "::error::Prettier formatting drift detected. Fix locally with:"
echo "::error:: npx prettier --write <files>"
echo "::error::Or rely on the lint-staged pre-commit hook (do not bypass with --no-verify)."
exit 1
fi
# Verify import ordering on the same set of changed files. The script
# only sorts files under known source roots, so unrelated changed files
# (configs, etc.) are ignored. Matches the lint-staged pre-commit hook.
- name: Check import sorting on changed files
id: import_sort
if: always() && steps.paths.outputs.eslint == 'true'
continue-on-error: true
run: |
BASE_SHA=$(jq --raw-output .pull_request.base.sha "$GITHUB_EVENT_PATH")
mapfile -d '' -t CHANGED_FILES < <(
git diff -z --name-only --diff-filter=ACMRTUXB "$BASE_SHA" HEAD |
grep -zE '^(api|client|packages)/.*\.(js|jsx|ts|tsx)$' || true
)
if [[ ${#CHANGED_FILES[@]} -eq 0 ]]; then
echo "No matching files changed. Skipping import-sort check."
exit 0
fi
echo "Files to check:"
printf '%s\n' "${CHANGED_FILES[@]}"
# `--check` lists offending files and exits non-zero without writing.
if ! node scripts/sort-imports.mts --check "${CHANGED_FILES[@]}"; then
echo ""
echo "::error::Import order drift detected. Fix locally with:"
echo "::error:: npm run sort-imports"
echo "::error::For specific files:"
echo "::error:: npm run sort-imports -- packages/api/src/app/metrics.ts packages/api/src/rum/proxy.ts"
echo "::error::To check without writing files:"
echo "::error:: npm run sort-imports:check"
echo "::error::Or rely on the lint-staged pre-commit hook (do not bypass with --no-verify)."
exit 1
fi
# The changed-file lint above never loads a changed root config: a
# config-only PR matches no lintable files, so even a malformed
# eslint.config.mjs would pass. When the config changes, gate on it
# loading and applying cleanly to representative sources, then run the
# full-tree regression gate below.
# Directory args, not `npm run lint`: the root brace-expansion@^5
# override breaks minimatch@3's brace expansion, so that script's
# braced glob crashes on a clean install; dir args never brace-expand.
# scripts/static-checks.mts runs these same checks locally from the
# pre-commit hook, and nothing else in this job loads it: ESLint has no
# flat-config match for scripts/**/*.mts. Run it against the PR's own
# diff so a syntax error or a broken filter fails here rather than in
# every contributor's next commit.
- name: Smoke the local static-checks runner
id: runner
if: always() && steps.paths.outputs.runner == 'true'
continue-on-error: true
run: |
BASE_SHA=$(jq --raw-output .pull_request.base.sha "$GITHUB_EVENT_PATH")
node scripts/static-checks.mts --against "$BASE_SHA" --list
# An explicit target, because --list never executes a check and a
# script-only PR activates no group — so neither would exercise the
# execution path this step exists to protect.
node scripts/static-checks.mts package.json --only json
- name: Validate ESLint config on config changes
id: eslint_config
if: always() && steps.paths.outputs.eslint_config == 'true'
continue-on-error: true
run: |
node_modules/.bin/eslint --config eslint.config.mjs \
api/server/index.js client/src/main.jsx packages/api/src/index.ts
- name: Validate the design-rule suppressions baseline
id: suppressions
if: always() && steps.paths.outputs.suppressions == 'true'
continue-on-error: true
run: |
# The changed-file ESLint step above selects JS/TS sources, so a diff that
# only edits eslint-suppressions.json lints nothing and would otherwise
# merge unread. The runner owns the rules for what the baseline may say.
# --against the PR base, not just the baseline path: the check also asks
# whether the changed files still owe what they record, and that needs
# the diff rather than one file name.
BASE_SHA=$(jq --raw-output .pull_request.base.sha "$GITHUB_EVENT_PATH")
node scripts/static-checks.mts --against "$BASE_SHA" --only suppressions
- name: Restore data-provider build cache
if: always() && steps.paths.outputs.config == 'true'
id: cache-data-provider
continue-on-error: true
uses: actions/cache@v5
with:
path: packages/data-provider/dist
key: build-data-provider-${{ runner.os }}-${{ hashFiles('package.json', 'package-lock.json', 'packages/data-provider/src/**', 'packages/data-provider/tsconfig*.json', 'packages/data-provider/tsdown.config.mjs', 'packages/data-provider/package.json') }}
- name: Build data-provider
id: config_data_provider
if: always() && steps.paths.outputs.config == 'true' && steps.cache-data-provider.outputs.cache-hit != 'true'
continue-on-error: true
run: npm run build:data-provider
- name: Restore data-schemas build cache
if: always() && steps.paths.outputs.config == 'true'
id: cache-data-schemas
continue-on-error: true
uses: actions/cache@v5
with:
path: packages/data-schemas/dist
key: build-data-schemas-${{ runner.os }}-${{ hashFiles('package.json', 'package-lock.json', 'packages/data-schemas/src/**', 'packages/data-schemas/tsconfig*.json', 'packages/data-schemas/tsdown.config.mjs', 'packages/data-schemas/package.json', 'packages/data-provider/src/**', 'packages/data-provider/tsconfig*.json', 'packages/data-provider/tsdown.config.mjs', 'packages/data-provider/package.json') }}
- name: Build data-schemas
id: config_data_schemas
if: always() && steps.paths.outputs.config == 'true' && steps.cache-data-schemas.outputs.cache-hit != 'true'
continue-on-error: true
run: npm run build:data-schemas
- name: Restore api build cache
if: always() && steps.paths.outputs.config == 'true'
id: cache-api
continue-on-error: true
uses: actions/cache@v5
with:
path: packages/api/dist
key: build-api-${{ runner.os }}-${{ hashFiles('package.json', 'package-lock.json', 'packages/api/src/**', 'packages/api/tsconfig*.json', 'packages/api/tsdown.config.mjs', 'packages/api/package.json', 'packages/data-provider/src/**', 'packages/data-provider/tsconfig*.json', 'packages/data-provider/tsdown.config.mjs', 'packages/data-provider/package.json', 'packages/data-schemas/src/**', 'packages/data-schemas/tsconfig*.json', 'packages/data-schemas/tsdown.config.mjs', 'packages/data-schemas/package.json') }}
- name: Build api
id: config_api
if: always() && steps.paths.outputs.config == 'true' && steps.cache-api.outputs.cache-hit != 'true'
continue-on-error: true
run: npm run build:api
- name: Create empty auth.json file
id: config_auth
if: always() && steps.paths.outputs.config == 'true'
continue-on-error: true
run: |
mkdir -p api/data
echo '{}' > api/data/auth.json
- name: Prepare .env.test file
id: config_env
if: always() && steps.paths.outputs.config == 'true'
continue-on-error: true
run: cp api/test/.env.test.example api/test/.env.test
- name: Run config migration tests
id: config_tests
if: always() && steps.paths.outputs.config == 'true'
continue-on-error: true
run: npm run test:config
- name: Find unused i18next keys
id: find_unused_i18n
if: always() && steps.paths.outputs.i18n == 'true'
continue-on-error: true
run: |
echo "🔍 Scanning for unused i18next keys..."
# Define paths
I18N_FILE="client/src/locales/en/translation.json"
SOURCE_DIRS=("client/src" "api" "packages/data-provider/src" "packages/client" "packages/data-schemas/src")
# Check if translation file exists
if [[ ! -f "$I18N_FILE" ]]; then
echo "::error title=Missing i18n File::Translation file not found: $I18N_FILE"
exit 1
fi
# Extract all keys from the JSON file
KEYS=$(jq -r 'keys[]' "$I18N_FILE")
# Track unused keys
UNUSED_KEYS=()
# Check if each key is used in the source code
for KEY in $KEYS; do
FOUND=false
# Special case for dynamically constructed special variable keys
if [[ "$KEY" == com_ui_special_var_* ]]; then
# Check if TSpecialVarLabel is used in the codebase
for DIR in "${SOURCE_DIRS[@]}"; do
if grep -r --include=\*.{js,jsx,ts,tsx} -q "TSpecialVarLabel" "$DIR"; then
FOUND=true
break
fi
done
# Also check if the key is directly used somewhere
if [[ "$FOUND" == false ]]; then
for DIR in "${SOURCE_DIRS[@]}"; do
if grep -r --include=\*.{js,jsx,ts,tsx} -q "$KEY" "$DIR"; then
FOUND=true
break
fi
done
fi
# Special case for agent category keys that are dynamically used from database
elif [[ "$KEY" == com_agents_category_* ]]; then
# Check if agent category localization is being used
for DIR in "${SOURCE_DIRS[@]}"; do
# Check for dynamic category label/description usage
if grep -r --include=\*.{js,jsx,ts,tsx} -E "category\.(label|description).*startsWith.*['\"]com_" "$DIR" > /dev/null 2>&1 || \
# Check for the method that defines these keys
grep -r --include=\*.{js,jsx,ts,tsx} "ensureDefaultCategories" "$DIR" > /dev/null 2>&1 || \
# Check for direct usage in agentCategory.ts
grep -r --include=\*.ts -E "label:.*['\"]$KEY['\"]" "$DIR" > /dev/null 2>&1 || \
grep -r --include=\*.ts -E "description:.*['\"]$KEY['\"]" "$DIR" > /dev/null 2>&1; then
FOUND=true
break
fi
done
# Also check if the key is directly used somewhere
if [[ "$FOUND" == false ]]; then
for DIR in "${SOURCE_DIRS[@]}"; do
if grep -r --include=\*.{js,jsx,ts,tsx} -q "$KEY" "$DIR"; then
FOUND=true
break
fi
done
fi
else
# Regular check for other keys
for DIR in "${SOURCE_DIRS[@]}"; do
if grep -r --include=\*.{js,jsx,ts,tsx} -q "$KEY" "$DIR"; then
FOUND=true
break
fi
done
fi
if [[ "$FOUND" == false ]]; then
UNUSED_KEYS+=("$KEY")
fi
done
# Output results
if [[ ${#UNUSED_KEYS[@]} -gt 0 ]]; then
echo "🛑 Found ${#UNUSED_KEYS[@]} unused i18n keys:"
echo "unused_keys=$(echo "${UNUSED_KEYS[@]}" | jq -R -s -c 'split(" ")')" >> $GITHUB_ENV
for KEY in "${UNUSED_KEYS[@]}"; do
echo "::warning title=Unused i18n Key::'$KEY' is defined but not used in the codebase."
done
else
echo "✅ No unused i18n keys detected!"
echo "unused_keys=[]" >> $GITHUB_ENV
fi
- name: Fail workflow if unused keys found
id: i18n
if: >
always() &&
steps.paths.outputs.i18n == 'true' &&
(steps.find_unused_i18n.outcome == 'failure' || env.unused_keys != '[]')
continue-on-error: true
run: exit 1
- name: Install depcheck
id: install_depcheck
if: always() && steps.paths.outputs.unused_packages == 'true'
continue-on-error: true
run: npm install -g depcheck
- name: Validate JSON files
id: validate_package_json
if: always() && steps.paths.outputs.unused_packages == 'true'
continue-on-error: true
run: |
for FILE in package.json client/package.json api/package.json packages/api/package.json packages/client/package.json packages/data-provider/package.json packages/data-schemas/package.json; do
if [[ -f "$FILE" ]]; then
jq empty "$FILE" || (echo "::error title=Invalid JSON::$FILE is invalid" && exit 1)
fi
done
- name: Extract Dependencies Used in Scripts
if: always() && steps.paths.outputs.unused_packages == 'true'
id: extract-used-scripts
continue-on-error: true
run: |
extract_deps_from_scripts() {
local package_file=$1
if [[ -f "$package_file" ]]; then
jq -r '.scripts | to_entries[].value' "$package_file" | \
grep -oE '([a-zA-Z0-9_-]+)' | sort -u > used_scripts.txt
else
touch used_scripts.txt
fi
}
extract_deps_from_scripts "package.json"
mv used_scripts.txt root_used_deps.txt
extract_deps_from_scripts "client/package.json"
mv used_scripts.txt client_used_deps.txt
extract_deps_from_scripts "api/package.json"
mv used_scripts.txt api_used_deps.txt
- name: Extract Dependencies Used in Source Code
if: always() && steps.paths.outputs.unused_packages == 'true'
id: extract-used-code
continue-on-error: true
run: |
extract_deps_from_code() {
local folder=$1
local output_file=$2
# Initialize empty output file
> "$output_file"
if [[ -d "$folder" ]]; then
# Extract require() statements (use explicit includes for portability)
grep -rEho "require\\(['\"]([a-zA-Z0-9@/._-]+)['\"]\\)" "$folder" \
--include='*.js' --include='*.ts' --include='*.tsx' --include='*.jsx' --include='*.mjs' --include='*.cjs' 2>/dev/null | \
sed -E "s/require\\(['\"]([a-zA-Z0-9@/._-]+)['\"]\\)/\1/" >> "$output_file" || true
# Extract ES6 imports - import x from 'module'
grep -rEho "import .* from ['\"]([a-zA-Z0-9@/._-]+)['\"]" "$folder" \
--include='*.js' --include='*.ts' --include='*.tsx' --include='*.jsx' --include='*.mjs' --include='*.cjs' 2>/dev/null | \
sed -E "s/import .* from ['\"]([a-zA-Z0-9@/._-]+)['\"]/\1/" >> "$output_file" || true
# import 'module' (side-effect imports)
grep -rEho "import ['\"]([a-zA-Z0-9@/._-]+)['\"]" "$folder" \
--include='*.js' --include='*.ts' --include='*.tsx' --include='*.jsx' --include='*.mjs' --include='*.cjs' 2>/dev/null | \
sed -E "s/import ['\"]([a-zA-Z0-9@/._-]+)['\"]/\1/" >> "$output_file" || true
# export { x } from 'module' or export * from 'module'
grep -rEho "export .* from ['\"]([a-zA-Z0-9@/._-]+)['\"]" "$folder" \
--include='*.js' --include='*.ts' --include='*.tsx' --include='*.jsx' --include='*.mjs' --include='*.cjs' 2>/dev/null | \
sed -E "s/export .* from ['\"]([a-zA-Z0-9@/._-]+)['\"]/\1/" >> "$output_file" || true
# import type { x } from 'module' (TypeScript)
grep -rEho "import type .* from ['\"]([a-zA-Z0-9@/._-]+)['\"]" "$folder" \
--include='*.ts' --include='*.tsx' 2>/dev/null | \
sed -E "s/import type .* from ['\"]([a-zA-Z0-9@/._-]+)['\"]/\1/" >> "$output_file" || true
# Remove subpath imports but keep the base package
# For scoped packages: '@scope/pkg/subpath' -> '@scope/pkg'
# For regular packages: 'pkg/subpath' -> 'pkg'
# Scoped packages (must keep @scope/package, strip anything after)
sed -i -E 's|^(@[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+)/.*|\1|' "$output_file" 2>/dev/null || true
# Non-scoped packages (keep package name, strip subpath)
sed -i -E 's|^([a-zA-Z0-9_-]+)/.*|\1|' "$output_file" 2>/dev/null || true
sort -u "$output_file" -o "$output_file"
fi
}
extract_deps_from_code "." root_used_code.txt
extract_deps_from_code "client" client_used_code.txt
extract_deps_from_code "api" api_used_code.txt
# Extract dependencies used by workspace packages
# These packages are used in the workspace but dependencies are provided by parent package.json
extract_deps_from_code "packages/client" packages_client_used_code.txt
extract_deps_from_code "packages/api" packages_api_used_code.txt
- name: Get @librechat/client dependencies
if: always() && steps.paths.outputs.unused_packages == 'true'
id: get-librechat-client-deps
continue-on-error: true
run: |
if [[ -f "packages/client/package.json" ]]; then
# Get all dependencies from @librechat/client (dependencies, devDependencies, and peerDependencies)
DEPS=$(jq -r '.dependencies // {} | keys[]' packages/client/package.json 2>/dev/null || echo "")
DEV_DEPS=$(jq -r '.devDependencies // {} | keys[]' packages/client/package.json 2>/dev/null || echo "")
PEER_DEPS=$(jq -r '.peerDependencies // {} | keys[]' packages/client/package.json 2>/dev/null || echo "")
# Combine all dependencies
echo "$DEPS" > librechat_client_deps.txt
echo "$DEV_DEPS" >> librechat_client_deps.txt
echo "$PEER_DEPS" >> librechat_client_deps.txt
# Also include dependencies that are imported in packages/client
cat packages_client_used_code.txt >> librechat_client_deps.txt
# Remove empty lines and sort
grep -v '^$' librechat_client_deps.txt | sort -u > temp_deps.txt
mv temp_deps.txt librechat_client_deps.txt
else
touch librechat_client_deps.txt
fi
- name: Get @librechat/api dependencies
if: always() && steps.paths.outputs.unused_packages == 'true'
id: get-librechat-api-deps
continue-on-error: true
run: |
if [[ -f "packages/api/package.json" ]]; then
# Get all dependencies from @librechat/api (dependencies, devDependencies, and peerDependencies)
DEPS=$(jq -r '.dependencies // {} | keys[]' packages/api/package.json 2>/dev/null || echo "")
DEV_DEPS=$(jq -r '.devDependencies // {} | keys[]' packages/api/package.json 2>/dev/null || echo "")
PEER_DEPS=$(jq -r '.peerDependencies // {} | keys[]' packages/api/package.json 2>/dev/null || echo "")
# Combine all dependencies
echo "$DEPS" > librechat_api_deps.txt
echo "$DEV_DEPS" >> librechat_api_deps.txt
echo "$PEER_DEPS" >> librechat_api_deps.txt
# Also include dependencies that are imported in packages/api
cat packages_api_used_code.txt >> librechat_api_deps.txt
# Remove empty lines and sort
grep -v '^$' librechat_api_deps.txt | sort -u > temp_deps.txt
mv temp_deps.txt librechat_api_deps.txt
else
touch librechat_api_deps.txt
fi
- name: Extract Workspace Dependencies
if: always() && steps.paths.outputs.unused_packages == 'true'
id: extract-workspace-deps
continue-on-error: true
run: |
# Function to get dependencies from a workspace package that are used by another package
get_workspace_package_deps() {
local package_json=$1
local output_file=$2
# Get all workspace dependencies (starting with @librechat/)
if [[ -f "$package_json" ]]; then
local workspace_deps=$(jq -r '.dependencies // {} | to_entries[] | select(.key | startswith("@librechat/")) | .key' "$package_json" 2>/dev/null || echo "")
# For each workspace dependency, get its dependencies
for dep in $workspace_deps; do
# Convert @librechat/api to packages/api
local workspace_path=$(echo "$dep" | sed 's/@librechat\//packages\//')
local workspace_package_json="${workspace_path}/package.json"
if [[ -f "$workspace_package_json" ]]; then
# Extract all dependencies from the workspace package
jq -r '.dependencies // {} | keys[]' "$workspace_package_json" 2>/dev/null >> "$output_file"
# Also extract peerDependencies
jq -r '.peerDependencies // {} | keys[]' "$workspace_package_json" 2>/dev/null >> "$output_file"
fi
done
fi
if [[ -f "$output_file" ]]; then
sort -u "$output_file" -o "$output_file"
else
touch "$output_file"
fi
}
# Get workspace dependencies for each package
get_workspace_package_deps "package.json" root_workspace_deps.txt
get_workspace_package_deps "client/package.json" client_workspace_deps.txt
get_workspace_package_deps "api/package.json" api_workspace_deps.txt
- name: Run depcheck for root package.json
if: always() && steps.paths.outputs.unused_packages == 'true'
id: check-root
continue-on-error: true
run: |
if [[ -f "package.json" ]]; then
UNUSED=$(depcheck --json | jq -r '.dependencies | join("\n")' || echo "")
# Exclude dependencies used in scripts, code, and workspace packages
UNUSED=$(comm -23 <(echo "$UNUSED" | sort) <(cat root_used_deps.txt root_used_code.txt root_workspace_deps.txt | sort) || echo "")
echo "ROOT_UNUSED<<EOF" >> $GITHUB_ENV
echo "$UNUSED" >> $GITHUB_ENV
echo "EOF" >> $GITHUB_ENV
fi
- name: Run depcheck for client/package.json
if: always() && steps.paths.outputs.unused_packages == 'true'
id: check-client
continue-on-error: true
run: |
if [[ -f "client/package.json" ]]; then
chmod -R 755 client
cd client
UNUSED=$(depcheck --json | jq -r '.dependencies | join("\n")' || echo "")
# Exclude dependencies used in scripts, code, workspace packages, and @librechat/client imports
UNUSED=$(comm -23 <(echo "$UNUSED" | sort) <(cat ../client_used_deps.txt ../client_used_code.txt ../client_workspace_deps.txt ../packages_client_used_code.txt ../librechat_client_deps.txt 2>/dev/null | sort -u) || echo "")
# Filter out false positives
UNUSED=$(echo "$UNUSED" | grep -v "^micromark-extension-llm-math$" || echo "")
echo "CLIENT_UNUSED<<EOF" >> $GITHUB_ENV
echo "$UNUSED" >> $GITHUB_ENV
echo "EOF" >> $GITHUB_ENV
cd ..
fi
- name: Run depcheck for api/package.json
if: always() && steps.paths.outputs.unused_packages == 'true'
id: check-api
continue-on-error: true
run: |
if [[ -f "api/package.json" ]]; then
chmod -R 755 api
cd api
UNUSED=$(depcheck --json | jq -r '.dependencies | join("\n")' || echo "")
# Exclude dependencies used in scripts, code, workspace packages, and @librechat/api imports
UNUSED=$(comm -23 <(echo "$UNUSED" | sort) <(cat ../api_used_deps.txt ../api_used_code.txt ../api_workspace_deps.txt ../packages_api_used_code.txt ../librechat_api_deps.txt 2>/dev/null | sort -u) || echo "")
echo "API_UNUSED<<EOF" >> $GITHUB_ENV
echo "$UNUSED" >> $GITHUB_ENV
echo "EOF" >> $GITHUB_ENV
cd ..
fi
- name: Fail workflow if unused dependencies found
id: unused_packages
if: >
always() &&
steps.paths.outputs.unused_packages == 'true' &&
(env.ROOT_UNUSED != '' || env.CLIENT_UNUSED != '' || env.API_UNUSED != '')
continue-on-error: true
run: exit 1
- name: Summarize static check failures
if: always()
env:
INSTALL_DEPENDENCIES_OUTCOME: ${{ steps.install_dependencies.outcome }}
ESLINT_OUTCOME: ${{ steps.eslint.outcome }}
ESLINT_CONFIG_OUTCOME: ${{ steps.eslint_config.outcome }}
DESIGN_RULES_BUILD_OUTCOME: ${{ steps.design_rules_build.outcome }}
SUPPRESSIONS_OUTCOME: ${{ steps.suppressions.outcome }}
PRETTIER_OUTCOME: ${{ steps.prettier.outcome }}
IMPORT_SORT_OUTCOME: ${{ steps.import_sort.outcome }}
RUNNER_OUTCOME: ${{ steps.runner.outcome }}
CACHE_DATA_PROVIDER_OUTCOME: ${{ steps.cache-data-provider.outcome }}
CONFIG_DATA_PROVIDER_OUTCOME: ${{ steps.config_data_provider.outcome }}
CACHE_DATA_SCHEMAS_OUTCOME: ${{ steps.cache-data-schemas.outcome }}
CONFIG_DATA_SCHEMAS_OUTCOME: ${{ steps.config_data_schemas.outcome }}
CACHE_API_OUTCOME: ${{ steps.cache-api.outcome }}
CONFIG_API_OUTCOME: ${{ steps.config_api.outcome }}
CONFIG_AUTH_OUTCOME: ${{ steps.config_auth.outcome }}
CONFIG_ENV_OUTCOME: ${{ steps.config_env.outcome }}
CONFIG_TESTS_OUTCOME: ${{ steps.config_tests.outcome }}
FIND_I18N_OUTCOME: ${{ steps.find_unused_i18n.outcome }}
I18N_OUTCOME: ${{ steps.i18n.outcome }}
INSTALL_DEPCHECK_OUTCOME: ${{ steps.install_depcheck.outcome }}
VALIDATE_PACKAGE_JSON_OUTCOME: ${{ steps.validate_package_json.outcome }}
EXTRACT_USED_SCRIPTS_OUTCOME: ${{ steps.extract-used-scripts.outcome }}
EXTRACT_USED_CODE_OUTCOME: ${{ steps.extract-used-code.outcome }}
GET_CLIENT_DEPS_OUTCOME: ${{ steps.get-librechat-client-deps.outcome }}
GET_API_DEPS_OUTCOME: ${{ steps.get-librechat-api-deps.outcome }}
EXTRACT_WORKSPACE_DEPS_OUTCOME: ${{ steps.extract-workspace-deps.outcome }}
CHECK_ROOT_OUTCOME: ${{ steps.check-root.outcome }}
CHECK_CLIENT_OUTCOME: ${{ steps.check-client.outcome }}
CHECK_API_OUTCOME: ${{ steps.check-api.outcome }}
UNUSED_PACKAGES_OUTCOME: ${{ steps.unused_packages.outcome }}
run: |
failures=()
record_failure() {
if [[ "$2" == "failure" ]]; then
failures+=("$1")
fi
}
record_failure "Dependency installation" "$INSTALL_DEPENDENCIES_OUTCOME"
record_failure "ESLint" "$ESLINT_OUTCOME"
record_failure "ESLint config validation" "$ESLINT_CONFIG_OUTCOME"
record_failure "Client-package build for the design rules" "$DESIGN_RULES_BUILD_OUTCOME"
record_failure "Design-rule suppressions" "$SUPPRESSIONS_OUTCOME"
record_failure "Prettier" "$PRETTIER_OUTCOME"
record_failure "Import sorting" "$IMPORT_SORT_OUTCOME"
record_failure "Local static-checks runner" "$RUNNER_OUTCOME"
record_failure "Config data-provider cache" "$CACHE_DATA_PROVIDER_OUTCOME"
record_failure "Config data-provider build" "$CONFIG_DATA_PROVIDER_OUTCOME"
record_failure "Config data-schemas cache" "$CACHE_DATA_SCHEMAS_OUTCOME"
record_failure "Config data-schemas build" "$CONFIG_DATA_SCHEMAS_OUTCOME"
record_failure "Config API cache" "$CACHE_API_OUTCOME"
record_failure "Config API build" "$CONFIG_API_OUTCOME"
record_failure "Config auth preparation" "$CONFIG_AUTH_OUTCOME"
record_failure "Config environment preparation" "$CONFIG_ENV_OUTCOME"
record_failure "Config migration tests" "$CONFIG_TESTS_OUTCOME"
record_failure "Unused i18n scan" "$FIND_I18N_OUTCOME"
record_failure "Unused i18n keys" "$I18N_OUTCOME"
record_failure "depcheck installation" "$INSTALL_DEPCHECK_OUTCOME"
record_failure "Package JSON validation" "$VALIDATE_PACKAGE_JSON_OUTCOME"
record_failure "Package script dependency extraction" "$EXTRACT_USED_SCRIPTS_OUTCOME"
record_failure "Source dependency extraction" "$EXTRACT_USED_CODE_OUTCOME"
record_failure "Client dependency collection" "$GET_CLIENT_DEPS_OUTCOME"
record_failure "API dependency collection" "$GET_API_DEPS_OUTCOME"
record_failure "Workspace dependency extraction" "$EXTRACT_WORKSPACE_DEPS_OUTCOME"
record_failure "Root depcheck" "$CHECK_ROOT_OUTCOME"
record_failure "Client depcheck" "$CHECK_CLIENT_OUTCOME"
record_failure "API depcheck" "$CHECK_API_OUTCOME"
record_failure "Unused NPM packages" "$UNUSED_PACKAGES_OUTCOME"
if [[ "$UNUSED_PACKAGES_OUTCOME" == "failure" ]]; then
[[ -n "$ROOT_UNUSED" ]] && printf 'Root unused dependencies:\n%s\n' "$ROOT_UNUSED"
[[ -n "$CLIENT_UNUSED" ]] && printf 'Client unused dependencies:\n%s\n' "$CLIENT_UNUSED"
[[ -n "$API_UNUSED" ]] && printf 'API unused dependencies:\n%s\n' "$API_UNUSED"
fi
if [[ ${#failures[@]} -eq 0 ]]; then
echo "All affected static checks passed."
exit 0
fi
echo "::error::Static checks failed:"
printf ' - %s\n' "${failures[@]}"
exit 1
# Runs as its own job rather than a step inside `static-checks`. Two full
# type-aware sweeps of api+client+packages cost more than the rest of that
# job combined, and sharing one 30-minute budget with ~20 later steps meant a
# slow sweep starved config-migration, i18n and depcheck — the job then
# reported nothing at all, which is strictly worse than not running the gate.
eslint-sweep:
name: ESLint config regression sweep
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- name: Checkout repository
uses: actions/checkout@v5
with:
# fetch-depth: 0 is load-bearing — the gate reads the base ref's
# config via `git show`, which a shallow checkout cannot resolve.
fetch-depth: 0
- name: Detect config changes
id: paths
uses: dorny/paths-filter@v4
with:
predicate-quantifier: 'some-with-excludes'
filters: |
eslint_config:
- 'eslint.config.mjs'
- '.github/workflows/static-checks.yml'
- name: Set up Node.js 24.16.0
if: steps.paths.outputs.eslint_config == 'true'
uses: actions/setup-node@v5
with:
node-version: '24.16.0'
cache: npm
- name: Install dependencies
if: steps.paths.outputs.eslint_config == 'true'
run: npm ci
# This job has its own clean checkout, so it needs the primitive metadata
# the design rules read out of packages/client/dist as much as the Static
# checks job does: without it `shadcn/no-restyle` sees no `cva` variants
# and classifies fewer overrides, which would let the full-tree gate pass
# a component-ownership regression.
- name: Build client-package for the design rules
if: steps.paths.outputs.eslint_config == 'true'
run: npm run build:client-package
# Full-tree sweep that gates on regression, not cleanliness: the tree
# carries a pre-existing lint backlog (70 errors at time of wiring), so
# requiring a clean sweep would fail config PRs on unrelated debt.
# Instead, lint the same tree under the PR's config and under the base
# ref's config and fail when the PR's config (a) stops linting files
# the base config covered — the signature of a mis-scoped ignores — or
# (b) produces more diagnostics for some (file, rule, severity) triple.
# On an identical tree, any delta is attributable to the config change
# alone. Severity is part of the key so a warn->error escalation must
# land with the tree clean for that rule; downgrades and fixes are
# never penalized.
- name: ESLint full-sweep regression gate on config changes
id: eslint_sweep
if: steps.paths.outputs.eslint_config == 'true'
env:
# A sweep that outruns this budget yields a notice, not a failure:
# the gate is advisory about config scope, and an unfinished sweep is
# no evidence of a regression. Bounding it also keeps a pathological
# config from burning the whole job timeout with nothing to show.
ESLINT_SWEEP_BUDGET_SECONDS: '900'
run: |
run_sweep() {
set +e
# Two rules are switched off for the sweep only: `prettier/prettier`
# reformats every file (formatting drift is caught per changed file
# by the Static checks job and is not a config regression), and
# `import/no-cycle` walks the whole import graph from every file
# while config/circular-deps.mjs already owns cycle detection.
# Together they were ~85% of a full-tree lint.
timeout -k 15 "$ESLINT_SWEEP_BUDGET_SECONDS" \
node_modules/.bin/eslint --config "$1" api client packages -f json -o "$2" \
--rule 'prettier/prettier: off' \
--rule 'import/no-cycle: off'
local status=$?
set -e
# 124 = timeout sent TERM; 137 = it escalated to KILL.
if [ "$status" -eq 124 ] || [ "$status" -eq 137 ]; then
return 124
fi
return 0
}
if ! run_sweep eslint.config.mjs "$RUNNER_TEMP/eslint-head.json"; then
echo "::notice title=ESLint sweep::Head sweep exceeded ${ESLINT_SWEEP_BUDGET_SECONDS}s; skipping the regression gate for this run."
exit 0
fi
if [ ! -s "$RUNNER_TEMP/eslint-head.json" ]; then
echo "::error title=ESLint sweep::Head-config sweep produced no report — ESLint likely crashed under the new config."
exit 1
fi
BASE_SHA=$(jq --raw-output .pull_request.base.sha "$GITHUB_EVENT_PATH")
if ! git cat-file -e "$BASE_SHA^{commit}" 2>/dev/null; then
echo "::error title=ESLint sweep::Base commit is unavailable — this gate requires the checkout above to keep fetch-depth: 0."
exit 1
fi
# The base config is written to the repo root, not $RUNNER_TEMP:
# flat-config files/ignores patterns and plugin imports resolve
# relative to the config's own directory, so a temp-dir copy would
# scope to nothing and the comparison would pass vacuously.
# An unchanged config cannot regress: the head sweep above already
# proved this workflow still runs it, so a second identical sweep
# would only double the job's runtime.
if git diff --quiet "$BASE_SHA" HEAD -- eslint.config.mjs; then
echo "::notice title=ESLint sweep::eslint.config.mjs is unchanged from base; skipping the regression comparison."
exit 0
fi
trap 'rm -f eslint.config.base.mjs' EXIT
if ! git show "$BASE_SHA:eslint.config.mjs" > eslint.config.base.mjs 2>/dev/null; then
echo "::notice title=ESLint sweep::No eslint.config.mjs at base ref; skipping regression comparison."
exit 0
fi
if ! run_sweep eslint.config.base.mjs "$RUNNER_TEMP/eslint-base.json"; then
echo "::notice title=ESLint sweep::Base sweep exceeded ${ESLINT_SWEEP_BUDGET_SECONDS}s; skipping the regression comparison."
exit 0
fi
if [ ! -s "$RUNNER_TEMP/eslint-base.json" ]; then
echo "::notice title=ESLint sweep::Base config cannot run against this tree; skipping regression comparison."
exit 0
fi
jq -r '.[].filePath' "$RUNNER_TEMP/eslint-head.json" | sort > "$RUNNER_TEMP/head.files"
jq -r '.[].filePath' "$RUNNER_TEMP/eslint-base.json" | sort > "$RUNNER_TEMP/base.files"
LOST=$(comm -23 "$RUNNER_TEMP/base.files" "$RUNNER_TEMP/head.files")
if [ -n "$LOST" ]; then
LOST_COUNT=$(printf '%s\n' "$LOST" | wc -l)
echo "::error title=ESLint coverage regression::The config change stops linting $LOST_COUNT file(s) the base config covered (showing up to 20):"
printf '%s\n' "$LOST" | head -20
exit 1
fi
fingerprints() {
jq -r '.[] | .filePath as $f | .messages[] | "\($f)\t\(.ruleId // "parse-error")\t\(.severity)"' "$1" |
sort | uniq -c | sed -E 's/^ *([0-9]+) /\1\t/'
}
fingerprints "$RUNNER_TEMP/eslint-head.json" > "$RUNNER_TEMP/head.fp"
fingerprints "$RUNNER_TEMP/eslint-base.json" > "$RUNNER_TEMP/base.fp"
REGRESSIONS=$(awk -F'\t' '
NR==FNR { base[$2 FS $3 FS $4] = $1; next }
{
if ($1 > base[$2 FS $3 FS $4] + 0) {
sev = ($4 == 2) ? "error" : "warn"
printf "%s %s (%s): %d -> %d\n", $2, $3, sev, base[$2 FS $3 FS $4] + 0, $1
}
}
' "$RUNNER_TEMP/base.fp" "$RUNNER_TEMP/head.fp")
if [ -n "$REGRESSIONS" ]; then
echo "::error title=ESLint config regression::The config change introduces new diagnostics (file rule (severity): base -> head):"
echo "$REGRESSIONS"
exit 1
fi
echo "No coverage loss and no new diagnostics versus the base config."