Skip to content

Documentation

Testing Scripts Catalog

Complete catalog of all testing-related scripts in scripts/ — purpose, invocation, git hook/CI integration (July 2026).

11/13/2026
28 min read Edit on GitHub
On this page

CI log policy (quiet by default)

GitHub Actions sets CI=true and the workflow sets CI_QUIET=1. Together they keep signal high without dropping failure detail:

Layer Quiet behavior Failure detail
Bun package cache actions/cache/restore + save only on miss + success; key bun-v3-$OS-$bunVer-$lockHash digest-mismatch is non-fatal; next successful install re-saves a clean archive
oxfmt / oxlint ::group:: collapsed logs; oxlint --quiet --format=github full tool exit + annotations on fail
Unit (vitest) reporters: [dot, github-actions], silent: "passed-only" failed test logs + annotations
Integration (run-integration.ts) bun test --only-failures; server stdout buffered failure list, summary box, preview log tail on fail
E2E (playwright) dot + github + HTML/JSON artifacts expanded failures, ci-report-playwright.ts step summary

Local defaults stay verbose. Force quiet locally with CI_QUIET=1 or CI=true.

Integration / E2E build harness (not Docker alone)

Docker DBs (docker compose … up) are necessary for multi-DB matrix runs, but not sufficient. The production preview must include /api/testing (seed/reset). A normal bun run build strips that handler.

Command Behavior
bun run test:integration Always builds with COMPILE_ALL_ADAPTERS=true
… --no-build (local) Reuses build/ if harness present; auto-rebuilds if deploy-stripped
… --strict-no-build / CI Fail if harness missing (no silent rebuild)

Markers checked: Unauthorized: Testing endpoints are disabled, [TestingHandler] (same as verify-prod-build-backdoor --mode=bench).

Directory Structure

The scripts/ directory is partitioned into structured domain folders to maintain an enterprise-grade validation and orchestration pipeline:

scripts/
├── benchmark-matrix/   # Multi-database micro-benchmark and regression matrix
├── check/              # Static safety & invariant gates + the fast-check registry/runner (DB safety, bundle size, flake budget, seams, lockfile, source lints)
├── ci/                 # CI reporting dashboards and Playwright result analyzers
├── lint/               # Specialized AST and token linters (design tokens, shades, widgets, tenant isolation, locale format, CSS tokens, click-away)
├── probe/              # Runtime probes & network readiness (deploy backdoor, cgroup hardware, wait-for-ready)
├── runs/               # Test runners & harness orchestrators (run-integration, run-e2e, matrix, bench)
├── security/           # Dynamic & static security scanners, fuzzers, SBOM, backdoor verification
├── test/               # Developer test tools & orchestrators (test-doctor, test-smart, test-contract)
└── [root]              # CLI scaffolding, versioning, release wrappers, and system lifecycle tools

Git Hooks

Important

Local hooks are enforced (owner decision 2026-10-24). A commit only lands when format/lint/typecheck, the unit suite and the component interaction suite pass; a push re-runs the CI Unit job (coverage + components + mutation), the build, SQLite integration, DB parity when adapter code changed, and the browser gate. There is no opt-out environment variable.

bun run git commit -m "…"   # ~2 min
bun run git push            # ~5–6 min

The earlier opt-in policy (2026-10-23) was reverted after two green-local/red-CI Unit runs; the hooks now catch what the CI reporter caught.

.githooks/pre-commit (Stage 1) — Safety → Lint-Staged → Check → Risk → Unit (~2–3 min warm)

Runs before every commit. Steps:

  1. Database & live-config safety — scripts/check/check-test-db-safety.ts
  2. Lint-staged — bun run gate:fast (formats staged files before check runs)
  3. Quality Gate (check) — bun run check (oxfmt --check + oxlint + custom guards + svelte-kit sync + tsc + svelte-check)
  4. Risk audit — bun run risk:audit (skipped for docs-only changes)
  5. Unit tests — node ./node_modules/vitest/vitest.mjs run (skipped for docs-only changes)
  6. Component interactions (conditional) — bun run test:unit:components (runs when .svelte or UI/component/route/widget/store files are staged)
  7. SBOM sync — when bun.lock / package.json changed

.githooks/pre-push (Stage 2) — Smart Build → CI Unit Parity → Integration → Browser → Changed Mutations (~10–15 min warm)

Runs before every push, in this order:

  1. Database & live-config safety — scripts/check/check-test-db-safety.ts
  2. Production build (smart reuse) — scripts/runs/integration-harness.ts --ensure-build (reuses build/ if fresh and /api/testing-enabled; rebuilds with COMPILE_ALL_ADAPTERS=true when stale)
  3. Bundle size gate — scripts/check/check-bundle-size.ts
  4. Build & security probes (parallel) — scripts/runs/run-probe-group.ts runs prod-backdoor, secret-misuse, hardware-tiers and tenant-isolation concurrently (~13 s measured instead of ~30 s serial)
  5. Quality Gate — bun run check (includes version:verify and security:assurance); skipped when this exact tree already passed it at commit time
  6. CI Unit parity — test:coverage (test:unit:coverage + test:coverage:budget) + test:unit:components; coverage is skipped when the push changes no src/, tests/ or coverage config
  7. CVE audit — bun audit --severity=high (informational)
  8. SQLite integration — run-integration.ts --no-build --diff (full suite when no diff mapping or when harness/helpers changed)
  9. DB parity — only when adapter/service code changed (plus a non-UTC clock run)
  10. Browser gate — smoke.spec.ts plus the changed-path accessibility, visual, behavioural and media-server specs (identical mapping on next and main); then check-flake-budget.ts --max-flaky=0
  11. Deploy backdoor probe — scripts/probe/probe-deploy-testing-api.ts runs after the browser gate because it rebuilds build/ without the testing harness
  12. Mutation — scripts/test/mutate-core.ts --changed runs last (FULL_MUTATION=true runs all 31 seams); it dynamically queries --list-targets, rewrites affected source files, restores them atomically, and the hook restores any dirty target from HEAD as a second line of defence

Tree-scoped cache. scripts/runs/gate-cache.ts records each passing gate in .git/svelty-gate-cache.json (tree hash + manifest/lock/test-config hashes + runtime + DB mode; diff-scoped gates also include the diff base). Pre-commit records check/unit/components against the index tree; pre-push reuses them. A dirty or untracked worktree never records or hits — every gate reads the filesystem. bun run scripts/runs/gate-cache.ts clear forces a full run.

Full DB Matrix (Local Pre-CI) — ~8 min

For 1:1 CI parity, run all 4 databases locally before pushing:

bun run test:matrix          # SQLite + MongoDB + MariaDB + PostgreSQL

Requires Docker containers running (docker compose -f tests/docker-compose.yml --profile '*' up -d). Covers the same adapter matrix CI runs.


Core Testing Scripts

scripts/check/check-route-behaviour.ts — Behavioural route contract

Scores every route on four contracts (load-contract, failure-path, persistence, concurrency) using test evidence that names the route module or a unique URL. Applicability is per route, so redirect stubs are not scored for writing data.

bun run check:routes                     # table + score
bun run check:routes -- --json          # machine-readable, with evidence per cell
bun run check:routes -- --check --min=99 # CI gate (floor)

The gate runs inside bun run check. Each cell names its evidence file, so a low score is a work list, not a mystery. Adding a route without tests drops the score below the floor.

scripts/lint/lint-trivially-true-assertions.ts — Ban unfailable assertions

Static analysis over tests/** for four shapes that can never fail: literal tautologies, complementary arms, one-of status unions with no negative case, and assertions swallowed by try/catch. Runs in bun run check.

bun run lint:trivial-assertions           # add --check in CI (already wired)

A deliberate exception needs // trivial-assert-ok: <reason> on the assertion line.

scripts/runs/run-e2e.ts — E2E Test Runner

Unified E2E runner with CI and dev modes.

bun run test:e2e                        # CI mode (production build, :4173)
bun run test:e2e:dev                    # Dev mode (Vite dev server, :5173)
bun run test:e2e:quick                  # CI mode, reuse existing build
bun run test:e2e --dev --grep=login     # Dev mode + filter

CI mode: Builds with COMPILE_ALL_ADAPTERS=true, starts production preview, runs wizard → auth-setup → chromium. Dev mode: Starts Vite dev server, runs Playwright directly. Faster but not CI-identical.

scripts/test/test-doctor.ts — Local Health Check

Prints the real local vs CI gate map, then runs unit + SQLite integration.

bun run test:doctor                 # unit + SQLite integration
bun run test:doctor --list          # gate map only
bun run test:doctor --unit-only     # skip integration
bun run test:doctor --with-e2e      # also Playwright (CI-parity, reuses build)

Used by: Manual developer workflow (not in hooks/CI). Prefer this over outdated ci:local / verify:* names (those scripts do not exist).

scripts/test/test-smart.ts — Smart Test Orchestrator

Git-diff-aware test selector. Analyzes changed files and selects the optimal subset of tests.

bun run test:smart                     # Auto-detect from git diff
bun run test:smart --all               # Run everything
bun run test:smart --list              # Dry-run
bun run test:smart --suite=auth        # Filter by suite label

Used by: Manual developer workflow (not in hooks/CI). Unit suites use Vitest; integration uses bun test + harness.

Security unit suite (package script)

Focused hooks security regression (not a separate security-regression.ts file):

bun run test:security
# equivalent: vitest run defense-in-depth + authentication + authorization + file-server-tenant

Used by: Manual; covered by full unit suite on pre-commit.

Vitest 5 Developer Workflows (package scripts + raw Vitest)

Vitest 5 introduces high-performance developer ergonomics and smart change execution:

bun x vitest --watch                   # Interactive TDD watch mode with instant HMR
bun x vitest --ui                      # Vitest Web UI with visual trace viewer (@vitest/ui)
bun run test:unit:changed              # Smart: evaluates git diff and runs only impacted suites
bun run test:unit:area                 # Scoped run on the real Vitest runner (no `svelte-kit sync` step)
bun x vitest run --coverage            # Enterprise P0 coverage gate (outputs to .vitest/coverage)

Features enabled:

  • fsModuleCache: true: Filesystem caching of transformed modules for sub-second test turnaround.
  • Top-level forks: { execArgv: ["--enable-source-maps"] }: Accurate TypeScript stack traces across forks.
  • Isolated output directory: Reports and coverage stored in .vitest/ (ignored by git).

Security Scripts

scripts/security/security-audit.ts — Unified Security Audit

Master runner that dispatches to engines in scripts/security/ plus the static scanners:

bun run security                        # Scanner against localhost:4173
bun run security --auth                 # Build + start server + seed + authenticated scan
bun run security --ci                   # CI mode (exit 1 on findings)
bun run security --base=http://localhost:3000
bun run security --risk                 # Also run global security risk + tenant API scanners
bun run security --secret-scan          # Also run secret misuse scanner (--full)
bun run security --slop                 # Also run code quality slop scanner
bun run security --cve                  # Also run dependency CVE audit (SBOM refresh + bun audit + OSV.dev)
bun run security --full                 # Run ALL scanners (auth + risk + secret + slop + cve + fuzz)

Engines:

  • scripts/security/auth.ts — Authenticated audit (builds, starts production server, seeds admin, runs scanner with --auth)
  • scripts/security/scanner.ts — OWASP A01-A07 probes (auth bypass, injection, headers, rate limiting, info leakage)
  • bun audit + scripts/security/scan-osv.ts (via --cve/--full) — dependency CVE check across GitHub Advisory DB and OSV.dev (20+ feeds), after refreshing sbom.json

scripts/security/scan-secret-misuse.ts — Secret Misuse Scanner

Static analysis scanner that detects hardcoded credentials, API keys, and secret exposure in non-server files. Uses a single pre-compiled forbidden-key regex and 32-way parallel file batching. 6 detection rules including comparison-based backdoor detection (Rule 6: catches password === "hardcoded" patterns that assignment-based scanners miss) and console.*/logger.* secret exposure checks. Known key formats cover AWS, GitHub, Stripe, Google, OpenAI/Anthropic (sk-), Slack (xox*-), Hugging Face (hf_), JWTs, and private key blocks. Full scans cover src/, scripts/, config/collections/, .github/ and root build configs; generated config/private*.ts is excluded.

bun run scripts/security/scan-secret-misuse.ts               # incremental scan (changed files)
bun run scripts/security/scan-secret-misuse.ts --full        # scan all files
bun run scripts/security/scan-secret-misuse.ts --strict      # CI mode (exit 1 on medium/high findings)

scripts/security/scan-security-risk.ts — Global Security Risk Scanner (entire src/)

Static + AST scanner for vulnerability classes in OUR code — the layer no external database can cover. Scans all files under src/ (vendored src/types/, node_modules, generated src/paraglide/ excluded):

Rule Severity Detects
SQL value interpolation error '${value}' inside SQL strings — the author__not_in SQLi class; line-scoped identifier guard (assertSafeSqlIdentifier)
SQL string concatenation error "..." + value + "..." SQL assembly
MongoDB JS execution error $where / $function / $accumulator — server-side JS (RCE class)
Dynamic code execution error eval( / new Function( (RCE sinks)
SvelteKit CSRF disabled error csrf: { checkOrigin: false } / csrf: false
Non-httpOnly cookie error httpOnly: false (double-submit CSRF cookie exempted by design)
Loopback prefix bypass error .startsWith("localhost") / .startsWith("127.0.0.1") without : port boundary (matches localhost.evil.com)
Tenant header spoofing error Raw headers.get("x-tenant-id" \| "x-test-tenant-id") outside request-tenant.ts — must use resolveRequestTenant()
Bare NODE_ENV === "test" error Security/auth hooks gating test bypasses on bare NODE_ENV === "test" instead of TEST_MODE / PLAYWRIGHT_TEST
Reverse-proxy IP spoofing error Raw headers.get("x-forwarded-for") in server routes/hooks — must use getClientIp(event)
Blocking redis.keys() error Synchronous redis.keys(...) calls — must use redis.scanIterator()
Unbounded batch size (AST) error API batch handlers iterating request arrays without an explicit upper-bound (<= 100) guard
Privilege field / escalation error updateUserAttributes without sanitizeClientUserAttributePatch / stripPrivilegeEscalationFields
Setup API / complete gating error /api/setup public classification or handleCompleteSetup missing isSetupComplete() lock
Shell command interpolation warning exec(\…${…}`) — use execFile/spawn with an args array (.exec()` DB methods, WAF regex literals excluded)
Path interpolation warning fs.* with member-access ${x.y} paths or quote-concat — path-traversal class; guarded files + bare locals pass
SSRF warning fetch() with request-derived URL (configured endpoints like ollamaUrl/this.baseUrl pass; remote upload requires guard)
XSS sinks warning innerHTML=, outerHTML=, insertAdjacentHTML(, document.write(
Regex interpolation warning new RegExp(\…${x}…`)without escaping (escape helpers,\$&idiom, constants,\${` pass)
SQL identifier interpolation warning Unescaped identifiers (skipped in files with assertSafeSqlIdentifier-style guards)
bun run scripts/security/scan-security-risk.ts          # scan (warnings tolerated)
bun run scripts/security/scan-security-risk.ts --strict # exit 1 on errors (pre-commit)

scripts/security/scan-osv.ts — Global Vulnerability Check (OSV.dev)

Queries OSV.dev — the global aggregator that merges GitHub Advisory DB (GHSA), NVD, and 20+ other feeds — with the purls from sbom.json (CycloneDX, kept in lockstep by pre-commit). One batch request covers the whole dependency tree, including SvelteKit/Svelte/Vite advisories. Results cached 24h under node_modules/.cache/osv-cache.json.

bun run scripts/security/scan-osv.ts          # check (24h cache)
bun run scripts/security/scan-osv.ts --strict # exit 1 on any vulnerability
bun run scripts/security/scan-osv.ts --fresh  # ignore cache

scripts/security/risk-audit.ts — Full Commit Risk Audit (Parallel 6-Gate Runner)

Runs all 6 fast, stateless security checks in parallel in one gate (wired into .githooks/pre-commit) with deterministic buffered output and per-step timing:

  1. scan-security-risk --strict — global scan: DB (4 adapters) + loopback/tenant/test-mode/IP-spoof/AST batch guards + command injection, eval, paths, SSRF, XSS + SvelteKit config
  2. scan-secret-misuse --strict — hardcoded credentials, comparison backdoors, and console/logger secret leaks
  3. slop-scanner --strict — XSS/RTL/security architecture
  4. lint-tenant-api — AST tenant-isolation API hygiene, systemScope brands, and bypassTenantCheck allowlist
  5. bun audit — GitHub Advisory DB (npm tree)
  6. scan-osv --strict — OSV.dev global database
bun run risk:audit          # parallel commit gate
bun run risk:audit --full   # force full non-incremental scan on all gates

scripts/security/slop-scanner.ts — Code Quality + Security Architecture Scanner

Svelte 5 + Accessibility + RTL + Quality + Security scanner. Catches issues oxlint doesn’t cover.

Suppression entries in .slop-suppress.json are validated on load and matched by exact path or directory prefix only (never a substring), so one file cannot silently silence a sibling.

Code quality checks: XSS ({@html}), RTL compatibility, button variant validation, file naming, duplicate content, stale-placeholder tracking.

Security architecture checks (6 rules):

Rule Detects
CORS reflection Access-Control-Allow-Origin reflecting arbitrary Origin header with credentials
Broad MIME types File upload allowlist accepting application/* without specific subtypes
Fast hash for secrets createHash("sha256") used on API keys/tokens — should use HMAC
System user backdoor user._id === "system" && password === "hardcoded" patterns
Request body clone request.clone() without size limits — OOM risk

Client/security consistency checks:

Check Detects
Raw SQL identifiers SQL DML/DDL template literals interpolating identifiers without validation (skips Drizzle sql.raw/sql.identifier and files that already guard identifiers)
Mutating fetch + CSRF fetch("/api/...", { method: POST/PATCH/PUT/DELETE }) without X-CSRF-Token — prefer fetchApi/clientJsonHeaders
RegExp interpolation new RegExp(\…${input}…`)` without escaping — regex injection / ReDoS footgun

Use slop:suppress in a comment to skip a file.

bun run slop                              # Check all files
bun run slop --strict                     # CI mode (fail on findings)
bun run scripts/security/slop-scanner.ts --fix     # Check + autofix
bun run scripts/security/slop-scanner.ts --surface # List the advisory inventory

Unused exports are classified into dead-code candidates (unused-export — referenced nowhere in src/scripts/root/tests/docs; actionable) and two advisory inventories: export-surface (referenced by tests/docs only — test-only reset helpers and documented public API) and duplicate-export-name (the same distinctive name exported by several modules — usually a legitimate re-export bridge or remote/server contract symmetry).

The two advisory categories are not findings: they are summarised on a separate 🗂️ Inventory: line, never counted in the errors / warnings / infos total, and never affect --strict. A clean tree therefore reports 0 errors, 0 warnings, 0 infos while still tracking the public/test surface. Use --surface / --verbose (or SLOP_PRINT_CAP) to print the inventory.

scripts/security/verify-prod-build-backdoor.ts — Build Backdoor Verification

Scans build output to confirm /api/testing handler is present (bench builds) or stripped (deploy builds).

bun run scripts/security/verify-prod-build-backdoor.ts         # deploy mode
bun run scripts/security/verify-prod-build-backdoor.ts --mode=bench

scripts/probe/probe-deploy-testing-api.ts — Deploy Backdoor Probe (A01)

Full end-to-end probe: builds deploy-safe artifact, scans chunks, starts preview server, live-probes /api/testing.

bun run scripts/probe/probe-deploy-testing-api.ts
bun run scripts/probe/probe-deploy-testing-api.ts --skip-build

Used by: CI whitebox job (07-deploy-backdoor).


Safety & Invariant Checks (scripts/check/)

scripts/check/check-test-db-safety.ts — Production DB Guard

Blocks unsafe config/private.test.ts before any tests run. DB names must contain test, bench, e2e, or end in _functional.

bun run scripts/check/check-test-db-safety.ts

Used by: Pre-commit hook.

scripts/check/check-bundle-size.ts — CI Bundle Gate

The gate scans every emitted client chunk under .svelte-kit/output/client/_app/immutable (the build/ layouts are not inspected) and fails the build on four kinds of violation:

Gate Value Applies to
MAX_ENTRY_KB 80 entry chunks (entry.*.js)
MAX_ROOT_LAYOUT_KB 25 the root layout, matched as 0.<hash>.js in nodes/
MAX_LAYOUT_KB 150 layout chunks plus the (app) admin shell node (identified by the floating-nav / command-palette / left-sidebar markers, because SvelteKit compiles it to nodes/N.js)
BANNED_CLIENT_MARKERS json-render-svelte every client chunk — the pattern was replaced by native Svelte 5 + Valibot and must never return to the browser bundle

Two additional checks run across all chunks, not just the size-gated ones:

  • Static node: imports (from "node:fs" / import "node:path"): the browser cannot fetch a node: URL, so the whole route chunk dies silently. Dynamic import("node:fs") behind a server guard and require() stay legal.
  • TipTap/prosemirror markers in an entry or layout chunk fail the gate (rich text must arrive through a dynamic import in the rich-text widget). @better-svelte-email, ollama and node:events only warn.
bun run build
bun run scripts/check/check-bundle-size.ts

Used by: CI build job.

Verified baseline (2026-11-01, bun run build): root layout node 0.*.js = 18,565 B — under the 25 KB ceiling.

bun run build:fast — Local build without source maps

A local bun run build emits source maps (sourcemap: !process.env.CI in vite.config.ts). They are the dominant output cost, not the wall-time cost: the full build writes ~72 MB of .map files across ~1,098 files (the 1.6 MB client chunk alone produces a 16 MB map), while a measured run takes ~29 s with or without them on the dev Windows host. build:fast sets BUILD_SOURCEMAP=false, which vite.config.ts honours; the emitted .js is the same build minus the //# sourceMappingURL= comments (chunk file names can differ because the comment participates in the content hash), so the bundle gate and a runnable build/ are unaffected. The output drops from ~96 MB to ~22 MB. CI (CI=true) already builds without maps, so no release semantics change.

bun run build:fast
bun run scripts/check/check-bundle-size.ts

Use it when a local step only needs a runnable build/ (integration preview, E2E, bundle gate). Use bun run build when you need stack traces mapped back to the original sources.

scripts/check/run-fast-checks.ts — Parallel static-gate runner

Schedules the read-only policy/AST/assurance gates declared in scripts/check/rule-registry.ts (the single owner of each check’s id, script, args, kind and owner) across up to 8 workers and fails closed on any non-zero exit. bun run check calls it instead of chaining every script with &&.

The suite is 18 entries, grouped by owning subsystem:

  • design-system — consolidate-shades
  • widgets — lint-widgets
  • tests — lint-e2e-hydration, lint-trivial-assertions, lint-e2e-actionability, check-route-behaviour, check-route-manifest, check-integration-isolation, check-seam-assertions
  • marketplace — marketplace-conformance
  • release — check-lockfile-sync, version-verify
  • security — security-assurance
  • architecture — check-ast-gates, check-route-efficiency, check-source-lints
  • i18n — check-translations, check-hardcoded-copy

Two entries aggregate several rules: check-source-lints runs thirteen rules over one tree read (below) and check-ast-gates runs the module-graph linkmap plus the tenant-scope analysis in one process. The registry is asserted before any spawn: a duplicate id, a missing script, or an ast rule without an exported pure function fails the run.

  • Measured on a 24-thread machine: ~2–3 s warm, ~10 s cold, against ~20 s for the sequential chain.
  • Output is buffered per gate, so a failure prints that gate’s own log and the gate id.

scripts/check/run-source-lints.ts — thirteen source rules, one tree read

The check-source-lints registry entry. It reads the workspace once (the inclusive view, so Paraglide output and .d.ts mirrors are present for the budget ratchet) and derives the filtered view every other rule scans, then reports one deterministic list with a per-rule prefix (date-helpers file:line — …). The budget ratchet receives the inclusive list because it must count exactly what readSourceFiles() counts.

Rule Rejects Escape hatch
date-helpers a direct new Date().toISOString() instead of nowISODateString() lint-date-helpers: allow
locale-format toLocaleDateString() / toLocaleTimeString() / toLocaleString() outside src/utils/format-date.ts and src/utils/date.ts lint-locale-format: allow <reason>
css-tokens a @theme block that declares a --color-* ramp without static; a literal var(--color-…) no stylesheet or same-file definition declares —
click-away a document.addEventListener("click", …) in a .svelte file whose handler never calls closest()/contains(), or guards on data-testid lint-click-away: allow <reason>
silent-catch an empty catch block catch-allow: <reason>
live-paths a live path constant (paths.collections, DEFAULT_DATABASE_DIR, …) outside the resolvers lint-live-paths: allow
transient-classification a collection/config delete inside a catch handler that is not classified lint-transient: allow
global-timers a module-scope timer without a globalThis guard and .unref() lint-global-timers: allow
duplicate-testids a data-testid on a component that already renders the same id, or the same id twice on one component in one file testid-allow
remote-transport a SvelteKit query() (GET) that carries secret-shaped arguments or a mutating verb name remote-transport-allow: <reason>
anonymous-leaks an anonymously reachable handler that returns a sign-in link, token, hash or API key — (double opt-in gate only)
design dead/legacy classes, an undefined preset-*, variant/preset on AdminCard, a nested <style> block, a missing dynamic color recipe —
rule-budgets a per-file or per-rule increase in any / direct throw new AppError against scripts/lint/rule-budgets.json --update ratchets down

The standalone scripts stay runnable for debugging; this module is the gate bun run check executes. A missing budget baseline fails closed with the --update command in the message.

scripts/check/run-typecheck.ts — Parallel type gates

Runs tsc --noEmit and scripts/check/check-svelte-diagnostics.ts at the same time, after svelte-kit sync has generated the route types. Both are independent readers of the same sources; the old serial chain cost ~100 s, the parallel run ~50 s on a warm tree. The svelte-check warning gate is unchanged — it is still the authority on warnings as well as errors.

scripts/runs/gate-cache.ts — Tree-scoped gate cache

Records which gates already passed for an exact tree and lets pre-push reuse them. The key is the Git tree hash plus hashes of package.json, bun.lock, the Vitest/Playwright configs and the coverage budget, the Node/Bun runtime, and the DB mode; diff-scoped gates add the diff base. A dirty or untracked working tree can never record or hit, because every gate reads the filesystem.

bun run scripts/runs/gate-cache.ts key              # show the current key
bun run scripts/runs/gate-cache.ts clear            # force a full gate run

Cache file: .git/svelty-gate-cache.json (never committed).

scripts/runs/run-probe-group.ts — Parallel pre-push probes

Runs prod-backdoor, secret-misuse, hardware-tiers and tenant-isolation concurrently. They share nothing but the completed build/ and none binds a port. check-bundle-size stays separate (it reads .svelte-kit/output, which any concurrent build rewrites) and the deploy probe stays last (it rebuilds build/ without the testing harness).

scripts/check/check-flake-budget.ts — Flake Budget Enforcement

Enforces retried-test limits per E2E shard. --max-flaky governs a single retried pass; the percentage check only applies when more than one test retried and at least 20 tests executed, so one retry in a 25-test shard does not contradict --max-flaky=2.

Used by: CI E2E summary job and .githooks/pre-push (--max-flaky=0).

scripts/check/check-seam-assertions.ts — Component Seam Assertion Guard

Scans integration and component test files to verify that interaction boundaries and critical state transitions have explicit assertions.

bun run check:seams

Used by: Quality gate (bun run check).

scripts/check/check-lockfile-sync.ts — Lockfile Parity Guard

Ensures bun.lock dependencies are strictly in sync with package.json catalog definitions.

bun run check:lockfile

Used by: Quality gate (bun run check).

scripts/check/check-route-efficiency.ts — route-load efficiency scan

Scans .server.ts and +server.ts files under src/routes/ for two patterns: a direct dbAdapter.crud.* / .content / .collection / .system / .auth call that bypasses LocalCMS (and with it the shared cache, tracing and tenant guards), and a sequential-await waterfall — four or more consecutive const/let statements that each await with no Promise.all. src/routes/api/[...path]/+server.ts and src/routes/api/testing/+server.ts are the whitelisted raw-DB routes; any path containing testing is exempt from the bypass rule.

--check exits 1 only when a critical violation exists. Both current rules emit advisory, so the gate reports rather than blocks until a rule is promoted.

bun run scripts/check/check-route-efficiency.ts --check

Used by: Quality gate (bun run check, registry id check-route-efficiency).

scripts/check/check-hardcoded-copy.ts — unlocalized-copy ratchet

Scans .svelte files under src/routes/(app) with the Svelte 5 AST for raw text nodes and user-facing attributes (placeholder, aria-label, title, alt), plus wildcard paraglide/messages imports. Suppression is <!-- copy:ignore --> per node and <!-- copy:ignore-file --> per file.

--check is a ratchet, not a zero-tolerance scan: it compares path::snippet fingerprints against scripts/check/hardcoded-copy-baseline.json (199 entries as of 2026-11-13). A string that is not recorded fails; a baseline entry the scan no longer produces is reported as stale. --update re-records the full set after a reviewed change.

bun run check:copy           # advisory report, exit 0
bun run check:copy:ratchet   # the gate (--check)

Used by: Quality gate (bun run check, registry id check-hardcoded-copy).

scripts/check/check-translations.ts — locale catalog integrity

Validates every JSON catalog in src/messages/, using en as the reference: missing keys are errors, extra keys and empty values are warnings. It does not read the (app) routes at all, so it complements the copy ratchet rather than duplicating it.

bun run scripts/check/check-translations.ts

Used by: Quality gate (bun run check, registry id check-translations). There is no package script — the registry invokes the file directly. Both localization gates were previously reachable only by running the script by hand.


Specialized Lint Scripts (scripts/lint/)

scripts/lint/lint-design.ts — Design Token & Class Linter

Enforces Tailwind v4 token usage, scans for forbidden legacy utility classes, and guards against non-token color allocations.

bun run lint:design

scripts/lint/consolidate-shades.ts — Status-Shade Contract Guard

Enforces the status-shade contract (500 fills, 500/400 text, single shade per ramp role).

bun run scripts/lint/consolidate-shades.ts --check
bun run scripts/lint/consolidate-shades.ts         # autofix

scripts/lint/lint-widgets.ts — Widget Architecture Linter

Validates widget naming, contracts, a11y attributes, and directory layout across all custom and core widgets.

bun run lint:widgets

scripts/lint/lint-tenant-api.ts — Tenant Isolation AST Linter

Static AST analyzer that verifies every /api route handler applies tenant scoping (tenantId).

bun run lint:tenant              # incremental (git diff)
bun run lint:tenant -- --full    # full scan

scripts/lint/lint-benchmark-mdx.ts — Benchmark MDX Parity

Ensures benchmark documentation tables and metrics stay synchronized with measured run results.

bun run lint:benchmark-mdx

scripts/lint/lint-locale-format.ts — pinned locale formatting

Bans toLocaleDateString(), toLocaleTimeString() and the overloaded toLocaleString() everywhere except the formatter implementations (src/utils/format-date.ts, src/utils/date.ts). Those methods resolve the locale from the runtime, so server render and client hydration can disagree; the helpers (formatDate, formatDateTime, formatTime, formatNumber) resolve systemLanguage deterministically and memoize their Intl instances. Constructing Intl.DateTimeFormat / Intl.NumberFormat directly is not flagged. Escape hatch: // lint-locale-format: allow <reason>.

bun run lint:locale-format

scripts/lint/lint-css-tokens.ts — tokens that can actually exist at runtime

Two failures tsc and snapshots cannot see:

  1. Unemitted palette — Tailwind v4 only emits the theme variables a generated utility references, so a @theme { --color-… } block drops every shade reached only through var() indirection. Any block declaring a --color-* ramp must be @theme static.
  2. Undefined token — a literal var(--color-…) that no stylesheet declares (and that the same file does not define) falls back silently to an inherited colour.

The token definitions are read from src/app.css and src/utilities.css; dynamic references (var(--color-${shade}-500), a name ending in -) are skipped because there is no literal to resolve.

bun run lint:css-tokens

scripts/lint/lint-click-away.ts — containment guards on document clicks

A document.addEventListener("click", …) in a .svelte file must prove it tests containment (closest() or contains()) in its handler, and must not build its ignore-list from data-testid: a testid deny-list is always one trigger short, because testids are fixtures, not a behavioural contract. src/components/ui/popover.svelte is the shared primitive and is allowlisted. Escape hatch: // lint-click-away: allow <reason>.

bun run lint:click-away

Hardware & Environment Probes (scripts/probe/)

scripts/probe/probe-hardware-tiers.ts — Hardware Tier Probe (cgroup)

Self-bundles the real src/utils/hardware-profile.ts and runs it inside memory/CPU-limited containers (--memory=256m --cpus=1, --memory=512m --cpus=2, plus an unconstrained case), asserting the derived budgets exactly: heap, RSS target, L1 caches, body limit, DB pool, workers, threadpool, and the ≤ 70 % invariant. The unit suite injects limits; this gate proves the runtime actually reads the cgroup.

bun run scripts/probe/probe-hardware-tiers.ts          # needs a reachable Docker daemon

Used by: CI whitebox job (08-hardware-tiers).

scripts/probe/wait-for-ready.ts — Readiness Gate Probe

Zero-dependency TCP and HTTP readiness probe with PID monitoring for preview servers and database ports.

bun run scripts/probe/wait-for-ready.ts tcp:127.0.0.1:5432 --timeout=90000 --interval=2000
bun run scripts/probe/wait-for-ready.ts http://127.0.0.1:4173/api/system/health --pid=1234

scripts/probe/probe-adaptive-update-lane.ts — UPDATE Lane Micro-Benchmark

Measures an idle single update through NetworkDbQueueGate twice: coalesced (SVELTY_WRITE_COALESCING=1) vs adaptive (SVELTY_WRITE_COALESCE_UPDATE=1). Local runs on 2026-10-18 (5 000 samples, 500 warm-up, no database): coalesced p50 ≈2–3 µs / p95 ≈6 µs / max 2.3–2.5 ms; adaptive p50 ≈0.3–0.4 µs / p95 ≈0.5–0.6 µs / max 11–13 µs. The adaptive lane removes the scheduler hop only when nothing else is queued or in flight.

bun run scripts/probe/probe-adaptive-update-lane.ts

scripts/bundle-stats.ts — Bundle Analytics

Detailed bundle report with gzip/brotli sizes, history tracking.

bun run build:stats

Benchmark Scripts (scripts/runs/ & scripts/benchmark-matrix/)

scripts/runs/run-core-benchmarks.ts — CI-Core Benchmarks

Runs the 8 core benchmarks for one or all adapters, then enforces the performance gate.

bun run scripts/runs/run-core-benchmarks.ts              # All adapters
bun run scripts/runs/run-core-benchmarks.ts --db=sqlite  # Single adapter

The gate (scripts/benchmark-matrix/ci-regression-gate.ts) compares the current run against PERFORMANCE_BUDGET and a rolling per-adapter baseline. Drift warns at ≥25 % + ≥0.25 ms and fails at ≥100 % + ≥1.5 ms, but a severe drift must repeat on the next run (the first observation freezes the baseline and reports pending confirmation). BENCHMARK_GATE_POLICY=fail|warn overrides the default: relative drift fails on main and merge_group and warns on next and PRs; absolute SLA budgets fail on every branch and event.

Used by: CI bench-core job.

scripts/benchmark-matrix/ci-regression-gate.ts — Performance Gate

Reads tests/benchmarks/results/history.jsonl + <db>/matrix_metrics.json, evaluates budgets and drift, writes gate-baseline-<db>.json / gate-report-<db>.json, and emits GitHub annotations + a step-summary table. Severe drift is confirmed across two runs before it fails; the baseline is frozen in between so one noisy runner cannot re-baseline the metric.

bun run benchmark:gate --db=sqlite --policy=warn
# or directly:
bun run scripts/benchmark-matrix/ci-regression-gate.ts --db=sqlite --policy=warn

scripts/verify-benchmark-local.ts — Local Benchmark Preflight

Blocks local benchmarks when live config uses test DB names.

bun run verify:benchmark-local

Other Scripts

Script Purpose
create-app.js Scaffolds new SveltyCMS project (npx create-sveltycms)
scripts/security/generate-sbom.ts Generates software bill of materials
git-safe.ts Hardened git wrapper (blocks --no-verify)
setup-system.ts One-time system initialization
upgrade.ts Full SveltyCMS version upgrade (bun run upgrade)
scripts/ci/ci-report-all-green.ts CI dashboard for all-green gate (ci.yml)
scripts/ci/ci-report-playwright.ts CI reporter for Playwright results (ci.yml)

Git Hook Flow

git commit
  └─ pre-commit
       ├─ scripts/check/check-test-db-safety.ts
       ├─ bun run check (format + lint)
       ├─ lint-staged
       └─ test:unit

git push
  └─ pre-push
       ├─ COMPILE_ALL_ADAPTERS=true bun run build
       └─ bun test tests/integration/

Related

testingscriptscigit-hooks
Was this page helpful?