Get Started
DocsTrack 3rules
/llms.txt
129 Rules Reference6 min readbrevio-core v0.11.1

The 129-Rule Encyclopedia & Fix Reference

Plain-English Summary (For Anyone)

A fixed catalogue of 129 rules for mistakes that coding agents repeat

brevio-core documents 129 rules, from R1 (UI and mobile performance) to R20 (test custody). Each has a page with what it catches, why, a bad and a good example, and how it is checked. 14 are checked by `scan`, 9 more by `scan --surface`, 5 by `check`, and the rest are documented for review and for agents.

Why this matters:
A fixed rule gives the same finding for the same line on any machine, so it can fail a required check.
The rules are line-level pattern checks, not AST or dataflow analysis, and they are TypeScript and React first. A mistake that needs the whole file, the types or the call graph is a job for your linter, type checker or code scanner.
Measured precision is published per rule, with its limits (see the tiers section below).
When to use:Browse this encyclopedia to read a rule's specification, see before and after examples, and load them into the sandbox.
Technical Contract (For Engineers)
Line-level rules
CLI Invocation Signature:
brevio-core rules [--json] [-q QUERY] [--scanned] | brevio-core explain <rule_id>
Latency / Execution
Not measured for 0.11.1
Token Cost
No model call. No API key.
Exit Codes
0 = success; 1 = findings (scan); 2 = usage error (for example an unknown rule ID)
Artifacts & Files Generated:
brevio-core.toml.brevio/baseline.json
Visual Execution Pipeline
5-Stage Progressive Flow
0120 Categories
Categorize
Rules are grouped in 20 categories, R1 to R20
0214 scanned
Match
Fixed line patterns on the lines a change adds
03Offline
Explain
brevio-core explain R9.1 prints the rule page
04R5.4 R9.2 R10.1 R18.2
Fix
Four rules have one correct rewrite that --fix applies

The Rule Catalogue by Category

In Plain English:Rules are written as R<category>.<number>. The category tells you the area, from security to accessibility.
The categories are: - **R1**: UI and mobile performance - **R2**: Security and tenancy - **R3**: Billing and money - **R4**: Database and migrations - **R5**: Reliability and fallbacks - **R6**: Testing and hermeticity - **R7**: Architecture and contracts - **R8**: Marketing and attribution - **R9**: Type safety - **R10**: API and network robustness - **R11**: State and concurrency - **R12**: Memory and resource leaks - **R13**: Observability and logging - **R14**: Auth and sessions - **R15**: Error boundaries and fallback rendering - **R16**: Supply chain - **R17**: React and Next.js patterns - **R18**: Accessibility (WCAG 2.1 AA) - **R19**: Clean code - **R20**: Test custody (preview)

Which Command Checks Which Rule

In Plain English:Different commands check different rules, and many rules are documented for people and agents to apply.
- **scan (14 rules)**: R2.8, R5.4, R5.5, R6.3, R9.1, R9.2, R10.1, R10.9, R13.1, R16.2, R17.2, R18.1, R18.2 and R18.5, on the lines a change adds. `brevio-core rules --scanned` lists them. - **scan --surface (9 more)**: surface-scoped rules (UI blur, SSR reveal, GTM deferral, webhook HMAC, integer cents, self-mocking tests, weak assertions, contract purity, package imports). - **check (5)**: the test-custody rules R20.1 to R20.5, which are a preview. - **brief**: 23 more come with a one-line reminder from `brevio-core brief`. - **Documented**: the rest are standing rules for authors and reviewers. A rule marked preview (R6.3, R10.9 and R20.1 to R20.5) reports and does not fail a scan.

Measured Precision, and Its Limits

In Plain English:brevio-core publishes how often its rules were right on real code, and says where that stops.
The published run is of 2026-11-06 on 10 pinned TypeScript and JavaScript repositories (19,126 files, 3,350,731 lines). The scanner reported 1,606 hits; 115 were sampled and judged, 94 were real and 21 were not. The corpus is human-written code, so the figures say nothing about code an agent wrote. Python is not measured. R6.3 was below 70% in the sample and is a preview rule. `brevio-core explain <rule>` shows a rule's own figure.

Handling Legitimate Exceptions & Baseline Files

In Plain English:If code has a valid reason to break a rule, a person can silence that one finding and state the reason.
A person silences a finding with an ignore comment that gives a reason, on the line or the line above: `// brevio-core: ignore R9.2 -- the generated client has no type for this field`. Without `-- reason` it does not count. The agent hook and the MCP server do not honour ignore comments (`--forbid-ignores`), so an agent cannot silence its own finding. A diff scan reports the ignore comments, baseline entries and brevio-core.toml changes that a change adds as new suppressions, and the check stays red until a reviewer allows them with `--allow-new-suppressions`.
A Silenced Finding With a Stated Reason
Fixed (After)Exit 0
// brevio-core: ignore R9.2 -- the generated client has no type for this field
// @ts-ignore
const street = response.data.shipping_address.street;

Using the Interactive Rule Explorer Below

In Plain English:Filter by category, search by ID, or click any rule to load its bad and good code into the example panel.
The explorer below lists the rules of this site's catalogue with an example for each. The release's own list is `brevio-core rules`, and each rule's page is in the brevio-core repository under docs/rules. Selecting a rule loads its example into the panel on the right; the panel is an illustration, not a running scanner.

Interactive Rule Explorer

Explore the brevio-core rules and load their examples into the panel on the right.

129 / 129 rules
R1.1
Surface
Mobile GPU budget
Mobile GPU budget: scope blur >=40px to md:/lg: desktop viewports
R1.2
Surface
SSR visibility resilience
SSR visibility resilience: leave no [data-reveal] at opacity:0 without a CSS animation fallback
R1.3
Surface
Third-party script deferral
Third-party script deferral: load GTM/GA4 with lazyOnload after hydration
R1.4
Flash-free theme bootstrap
Flash-free theme bootstrap: paired semantic tokens across light and dark modes
R1.5
No dead controls
No dead controls: an interactive element wires a handler and loading and error feedback
R1.6
Accessible switch geometry
Accessible switch geometry: inline-flex items-center shrink-0 on toggle tracks
R1.7
LCP asset priority
LCP asset priority: priority/fetchpriority=high on hero LCP image, lazy below fold
R1.8
Async polling hygiene
Async polling hygiene: clear intervals on unmount and stop polling on terminal states
R2.1
Tenant context derivation
Tenant context derivation: derive tenant context from the verified session, not the client payload
R2.2
Tenant-scoped data access
Tenant-scoped data access: a DB read or write filters by the authenticated workspace scope
R2.3
Dual-key entity resolution
Dual-key entity resolution: discriminate UUID/CUID vs domain/slug before database query
R2.4
Surface
Raw-body webhook verification
Raw-body webhook verification: verify HMAC against raw request text before JSON parse
R2.5
Outbound SSRF & timeout guard
Outbound SSRF & timeout guard: validate URL host and set AbortSignal.timeout()
R2.6
Constant-time secret comparison
Constant-time secret comparison: use timingSafeEqual / compare_digest
R2.7
Secure cookie & CORS hygiene
Secure cookie & CORS hygiene: HttpOnly, Secure, SameSite, no wildcard CORS with credentials
R2.8
Scanned
No unsafe code or HTML sinks
No unsafe code or HTML sinks: eval or exec on a non-literal, new Function, unsanitised dangerouslySetInnerHTML, interpolated SQL strings and hidden control characters
R3.1
Idempotent webhook processing
Idempotent webhook processing: deduplicate event_id with monotonic state transitions
R3.2
Surface
Monetary integer representation
Monetary integer representation: store money as integer minor units (cents) + currency
R3.3
Gateway ID discrimination
Gateway ID discrimination: validate customer/subscription/checkout prefix before API call
R3.4
Pre-execution quota enforcement
Pre-execution quota enforcement: verify tier entitlement before paid LLM/API calls
R3.5
Transactional outbox
Transactional outbox: persist DB state before enqueuing external side effects
R4.1
Expand-contract migrations
Expand-contract migrations: additive nullable/default columns; no single-step drop/rename
R4.2
Foreign-key & tenant composite indexing
Foreign-key & tenant composite indexing: index FKs and (tenant_id, created_at)
R4.3
N+1 query prevention
N+1 query prevention: batch queries with IN / joins instead of per-row loop queries
R4.4
Ingestion FK pre-resolution
Ingestion FK pre-resolution: upsert or verify parent workspace before child rows
R4.5
Bounded pagination
Bounded pagination: enforce a hard LIMIT (<=100) on list queries
R5.1
Deterministic graceful fallbacks
Deterministic graceful fallbacks: return an explicit degraded status, not fabricated metrics
R5.2
HTTP empty-body hygiene
HTTP empty-body hygiene: 204 returns empty body; 200 JSON sets Content-Type
R5.3
Bounded retry with jitter
Bounded retry with jitter: retry only transient 429/502/503/504 with backoff + jitter
R5.4
ScannedFix
No silent exception swallowing
No silent exception swallowing: log or surface errors; empty catch blocks, bare except and except Exception: pass are flagged
R5.5
Scanned
Process safety
Process safety: no subprocess call with shell=True and no os.system call built from an f-string
R6.1
Surface
Real production import gate
Real production import gate: tests must import and invoke real production code
R6.2
Surface
Mutation side-effect assertions
Mutation side-effect assertions: assert persisted state or DOM changes, not just HTTP 200
R6.3
ScannedPreview
No fixed-length waitForTimeout in tests
No fixed-length waitForTimeout in tests: wait for a condition instead
R6.4
Hermetic test state isolation
Hermetic test state isolation: isolate DB/state paths per test in setUp/addCleanup
R6.5
Post-incident regression crystallization
Post-incident regression crystallization: a bug fix comes with a failing-first test
R7.1
Contract-first monorepo changes
Contract-first monorepo changes: update shared Zod/OpenAPI schema before consumers
R7.2
Granular field validation
Granular field validation: return field-level errors and preserve user form inputs
R7.3
Single canonical route per path
Single canonical route per path: no duplicate route group paths
R7.4
Acyclic module layering
Acyclic module layering: domain -> application -> adapters; no circular imports
R7.5
Surface
Universal contracts purity
Universal contracts purity: contracts barrels must not import Node built-ins (node:fs, node:path)
R8.1
Anti-cloaking & markdown parity
Anti-cloaking & markdown parity: serve identical facts to crawlers and browsers
R8.2
Honest telemetry attribution
Honest telemetry attribution: label synthetic or demo data and keep it apart from live metrics
R8.3
Consent Mode v2 ordering
Consent Mode v2 ordering: initialize default denied consent before analytics tags
R9.1
Scanned
No untyped escape hatches
No untyped escape hatches: no `as any` casts or `z.any()` schemas in production source
R9.2
ScannedFix
No silenced type errors
No silenced type errors: @ts-ignore is flagged; use @ts-expect-error and say why
R9.3
Surface
Package-name imports
Package-name imports: import workspace packages by name, not via ../../packages/ paths
R10.1
ScannedFix
Explicit HTTP request timeouts
Explicit HTTP request timeouts: Python requests calls pass timeout=
R10.2
Idempotency key transmission
Idempotency key transmission: mutating external POST/PUT requests send Idempotency-Key
R10.3
Rate-limit header handling
Rate-limit header handling: parse 429 Retry-After and respect backoff deadlines
R10.4
Structured error envelope
Structured error envelope: error responses adhere to standard JSON error schema
R10.5
Response size bounding
Response size bounding: clamp response body reads to avoid unbounded buffer allocation
R10.6
Content-Type negotiation
Content-Type negotiation: validate incoming request Accept / Content-Type headers
R10.7
No unauthenticated admin endpoints
No unauthenticated admin endpoints: route middleware protects management routes
R10.8
Strict HTTP verb mapping
Strict HTTP verb mapping: GET requests are read-only and free of side effects
R10.9
ScannedPreview
Timeouts on fetch and axios
Timeouts on fetch and axios: a call with no options argument sets no timeout and no AbortSignal
R11.1
Atomic read-modify-write
Atomic read-modify-write: concurrent mutations use compare-and-swap or row locks
R11.2
No dangling unawaited promises
No dangling unawaited promises: promise chains either return or await explicitly
R11.3
Race condition prevention
Race condition prevention: UI mutations abort pending conflicting requests via AbortController
R11.4
Deterministic reducer purity
Deterministic reducer purity: state reducers remain pure functions without side effects
R11.5
Cache key stability
Cache key stability: cache keys use sorted/normalized parameters to avoid fragmentation
R11.6
Optimistic UI rollback
Optimistic UI rollback: optimistic state updates retain rollback snapshot on failure
R11.7
Bounded in-memory queues
Bounded in-memory queues: memory queues specify max length and overflow policy
R11.8
Thread-safe singleton initialization
Thread-safe singleton initialization: singletons use atomic locks or double-checked init
R12.1
Event listener teardown
Event listener teardown: addEventListener in useEffect/components pairs with removeEventListener
R12.2
Timer lifecycle cleanup
Timer lifecycle cleanup: setTimeout and setInterval handle IDs cleaned on component unmount
R12.3
Stream disposal hygiene
Stream disposal hygiene: open readable/writable streams explicitly call close() or pipe safely
R12.4
WebSocket cleanup
WebSocket cleanup: client socket connections explicitly disconnect on navigation/unmount
R12.5
Database connection pool hygiene
Database connection pool hygiene: acquired pool clients release in finally blocks
R12.6
Worker thread termination
Worker thread termination: spawn worker instances call terminate() upon task completion
R12.7
Temp file deterministic deletion
Temp file deterministic deletion: scratch files in /tmp register unlink in finalizer
R12.8
No unbounded collection growth
No unbounded collection growth: caches and registries specify TTL or LRU eviction
R13.1
Scanned
No hardcoded secrets
No hardcoded secrets: credentials stay out of source code and out of browser bundles
R13.2
Structured JSON logging
Structured JSON logging: application logs emit valid JSON key-value pairs with timestamps
R13.3
Trace context propagation
Trace context propagation: distributed calls forward traceparent / correlation IDs
R13.4
Metric label cardinality bounding
Metric label cardinality bounding: avoid dynamic user IDs or timestamps in metric labels
R13.5
Standard log severity
Standard log severity: use debug/info/warn/error appropriately without log spam
R13.6
Audit event journaling
Audit event journaling: security-critical actions append an immutable audit record
R13.7
Health check hermeticity
Health check hermeticity: /healthz endpoints execute lightweight non-allocating probes
R13.8
Exception traceback containment
Exception traceback containment: sanitize public error responses to avoid leaking paths
R14.1
Session token entropy
Session token entropy: session identifiers contain at least 128 bits of cryptosecure random
R14.2
Password hash modern algorithms
Password hash modern algorithms: use Argon2id or bcrypt with appropriate work factor
R14.3
Token expiration bounding
Token expiration bounding: short-lived access tokens paired with rotating refresh tokens
R14.4
CSRF token validation
CSRF token validation: state-changing forms and endpoints validate anti-CSRF token
R14.5
No credentials in URLs
No credentials in URLs: pass tokens, API keys and passwords outside query strings
R14.6
Strict redirect URL allowlist
Strict redirect URL allowlist: OAuth / login return URLs validated against domain allowlist
R14.7
Brute-force throttle
Brute-force throttle: login and reset-password routes rate-limited by IP and username
R14.8
Role-based access control
Role-based access control: enforce authorization check at controller/handler boundary
R15.1
React error boundary protection
React error boundary protection: major route segments wrapped in error boundaries
R15.2
Non-blocking third-party failures
Non-blocking third-party failures: external widgets render graceful placeholder on failure
R15.3
Form submit recovery
Form submit recovery: failed form submission preserves user input for retry
R15.4
Image broken state fallback
Image broken state fallback: img / Image tags provide alt and error state fallback
R15.5
Network offline banner
Network offline banner: offline connectivity state indicated with non-blocking alert
R15.6
Empty state affordance
Empty state affordance: data tables and lists display actionable empty state message
R15.7
Skeleton loader transition
Skeleton loader transition: loading states use layout-preserving skeletons to avoid CLS
R15.8
Recoverable 404 navigation
Recoverable 404 navigation: not-found pages provide search and home navigation links
R16.1
Lockfile integrity enforcement
Lockfile integrity enforcement: CI installs from frozen lockfiles (pnpm --frozen)
R16.2
Scanned
No wildcard dependency versions
No wildcard dependency versions: package.json does not use '*' or 'latest'
R16.3
Scoped internal packages
Scoped internal packages: monorepo internal packages use scoped organization prefixes
R16.4
No install script execution
No install script execution: untrusted packages ignore postinstall lifecycle scripts
R16.5
Production bundle minimization
Production bundle minimization: devDependencies not imported in production runtime code
R16.6
License compliance
License compliance: no copyleft (GPL) dependencies imported into proprietary modules
R16.7
Single package manager
Single package manager: repo roots maintain exactly one package manager lockfile
R16.8
Deterministic engine constraints
Deterministic engine constraints: package.json specifies minimum node/pnpm engines
R17.1
Server Component default
Server Component default: components in app directory default to RSC unless 'use client'
R17.2
Scanned
No server-only code in client
No server-only code in client: 'server-only' imports barred from client-marked components
R17.3
Metadata API compliance
Metadata API compliance: route pages export static or generateMetadata for SEO
R17.4
Next/Image usage
Next/Image usage: production UI renders next/image for optimized srcset and layout stability
R17.5
Next/Font optimization
Next/Font optimization: load Google or local fonts via next/font to avoid layout shift
R17.6
Client boundary minimization
Client boundary minimization: push 'use client' directives down to leaf interactive nodes
R17.7
Server action security
Server action security: server actions validate session authentication before mutating
R17.8
Route handler return typing
Route handler return typing: route handlers return typed NextResponse with status
R18.1
Scanned
Image alternative text
Image alternative text: img elements carry an alt attribute
R18.2
ScannedFix
Form control labels
Form control labels: input, select and textarea elements have a label (not scanned); the scan checks target="_blank" links for rel="noopener noreferrer"
R18.3
Keyboard navigation accessibility
Keyboard navigation accessibility: interactive elements focusable via Tab and Enter/Space
R18.4
Contrast ratio minimum
Contrast ratio minimum: text satisfies 4.5:1 minimum contrast ratio against background
R18.5
Scanned
No click handlers on non-interactive elements
No click handlers on non-interactive elements: a div with onClick and no role is flagged
R18.6
Aria attributes validity
Aria attributes validity: aria-* attributes use valid names and permissible state values
R18.7
Visible focus rings
Visible focus rings: interactive elements retain visible focus outline for keyboard users
R18.8
Document language attribute
Document language attribute: html root element specifies valid lang='en' attribute
R19.1
Function length limit
Function length limit: functions remain under 100 lines; extract complex branches
R19.2
Cyclomatic complexity bounding
Cyclomatic complexity bounding: functions maintain cyclomatic complexity <= 20
R19.3
No dead commented-out code
No dead commented-out code: remove obsolete commented code blocks prior to PR merge
R19.4
Descriptive variable naming
Descriptive variable naming: avoid single-character variables outside trivial loops
R20.1
CheckPreview
Existing test files kept
Existing test files kept: a test file on the base is not deleted or renamed to a file that is no test
R20.2
CheckPreview
Existing tests and assertions kept
Existing tests and assertions kept: a changed test file does not hold fewer tests or assertions than its base
R20.3
CheckPreview
No test skip or focus marker added
No test skip or focus marker added: fix the failing test instead of silencing it
R20.4
CheckPreview
No tautological assertion added
No tautological assertion added: assert real output or state
R20.5
CheckPreview
No empty test block
No empty test block: a test whose body is empty, `pass` or `...` tests nothing