Engineering Paradigms & Standards Bible
The engineering standard for production systems: strict typing, security boundaries, resilience patterns, and observability, each tied to a named rule.
Who it is for
Technical buyers evaluating engineering quality, and developers who want a working reference for production-grade standards.
After reading it
You will be able to check a vendor, contractor, or your own team’s code against a concrete, named set of engineering standards instead of a general impression.
Status: Canonical, project-agnostic. v1.0 — 2026-07-05. Provenance: Every rule traces to (a) the adversarially-consensed paradigm verdicts of 2026-07 (P1–P39, R1–R10; paradigm-consensus-2026-07.md) or (b) a file in the nx-monorepo .cursor/rules/ corpus (cited as corpus:<name>). No invented rules. Known-stale corpus items are corrected here (see §1.3).
1. Purpose & Scope
This document is the source of truth for engineering standards across all projects. It contains only stack-agnostic rules. Stack specifics live in supplements.
1.1 How supplements attach
- Supplements (
10-*.md,11-*.md, …) reference core sections by number; they never restate core rules. A supplement rule reads: "Per §4.2, wrap the third-party client once — for this stack, that wrapper is X." - A project adopts the bible by: (1) classifying itself (see
20-INDEX.md), (2) attaching the matching supplements, (3) adding a pointer block to itsCLAUDE.md. Projects never fork the bible; they file deltas as ADRs or upstream corrections.
1.2 Rule tagging
- [CORE] — binding on every project, including solo-operator.
- [SCALE: …] — binding only when the trigger holds (
team>3,regulated(PHI/PII/financial),multi-tenant,public-api). Solo-operator projects may defer these consciously — record the deferral, don't ignore it silently.
1.3 Corpus corrections carried in (do not reintroduce)
- Zod: root import (
import { z } from 'zod') — thezod/v4subpath is stale guidance for apps. eslint-plugin-nodeis deprecated — useeslint-plugin-nwhere a Node lint plugin is needed.- Test-runner wording is tool-agnostic (the pyramid holds whether the runner is node:test, Vitest, or Jest).
- Enterprise incident-command / PagerDuty / SLO-error-budget ceremony (corpus:incident-management, alert-definitions) is scaled to operator reality: see §6.6.
2. Agnostic Core Principles
(corpus: separation-of-concerns, single-responsibility, simplicity, ts-standards-and-strictness; consensus P15, R4)
- [CORE] Separate presentation, business logic, and data access into distinct layers; no layer reaches through another. Independent testing, replacement, and parallel work depend on it. Anti-pattern: a UI component that queries the database or calls a third-party API directly.
- [CORE] One responsibility per function, class, or module — one reason to change. God-modules are where bugs hide and refactors die (consensus ground truth: a 4,935-line component and a 290-line god-context were the finding behind P15's ADOPT).
- [CORE] Favor the simplest solution that works; add abstraction only when a second concrete use exists. Premature platforms are the standing failure mode. Anti-pattern: introducing a plugin architecture for one plugin.
- [CORE] Strict types always:
strict: trueplusnoUncheckedIndexedAccess,exactOptionalPropertyTypes,noImplicitOverride,verbatimModuleSyntax(or the stack's equivalent maximum). Never disable strictness in a project config; a waiver requires an ADR. - [CORE] No
any. Preferunknown+ type guards;asassertions only at external boundaries. Enforce with lint, not discipline (R4: add the no-any lint rule even where the compiler flags are already on). - [CORE] Expose libraries through a single public surface (barrel/index); internal files are not importable across packages. Keeps public APIs minimal and refactors safe (R4).
- [CORE] Wrap third-party errors once at the module boundary; rethrow as domain errors. Callers branch on domain semantics, not vendor error shapes (corpus: error-handling-and-reliability; composes with §4).
3. State & Data Architecture
(consensus P17/P24, P18, P21, P27, P30; corpus: api-standards, configuration-standards)
- [CORE] Split server-state from client-state; use a dedicated async-cache layer for server reads, a store/context for genuine client state. Hand-rolled fetch-into-state reimplements caching, dedupe, and invalidation badly (P17/P24 — as a read layer; see §4.5 for the mutation boundary).
- [CORE] One target state architecture per app. Two overlapping state (or styling) systems means every change is made twice or drifts (P39's finding class). Consolidate or write the ADR that says why not.
- [CORE] Schema-validate at every trust boundary: API responses, persisted blobs on load, user input, env config.
JSON.parse+ cast is not validation; unvalidated loads were a verified defect class (P30 — jsonb load, scrape parsing). Fail loud on invalid, never silently drop. - [CORE] Persisted blobs carry a schema version; loading includes an explicit migration path per version and a visible error for unknown versions. Silently discarding
version != currentdata is data loss (P30 ground truth:v!=3silently dropped). Anti-pattern:if (data.v !== 3) return null; - [CORE] Parse env/config once at boot into a validated, typed object; never scatter raw
process.env.Xreads. Startup fails fast on bad config instead of failing weirdly at runtime (corpus: configuration-standards). - [CORE] Undo/redo for user-built artifacts is a first-class state concern — snapshot-based, covering all user-meaningful mutations, not just the easy subset (P21's finding: undo covering only canvas geometry).
- [SCALE: data>~5MB or offline] Use IndexedDB (or platform equivalent) instead of localStorage for large or structured client persistence (P27, adapted: large blobs only).
4. Network Resilience & Idempotency
(consensus R3 verdict incl. the idempotency-gate defect, P25; corpus: error-handling-and-reliability, api-standards)
- [CORE] Retry only transient failures (timeouts, 429, 5xx), with capped exponential backoff + jitter. Retrying 4xx logic errors burns quota and hides bugs.
- [CORE] Never retry a non-idempotent operation unless the server verifiably honors an idempotency key. The retry wrapper must take an explicit
idempotentflag and default non-idempotent mutations to zero retries — a client-generated key the server ignores is a duplicate-charge machine (R3 consensus defect: retrying mutations against key-blind servers). - [CORE] Every network call has a timeout; user-triggered superseded requests are aborted. Debounce + AbortController on live lookups is a correctness rule, not a performance nicety — a stale response landing late overwrites fresh state (P25: stale-price race).
- [CORE] Wrap each third-party service exactly once, in a typed adapter that owns retry, timeout, error-mapping, and logging. Business logic never calls raw
fetch; scattered call sites mean scattered (i.e., missing) resilience (corpus: api-standards adapter pattern). Anti-pattern: a second code path that bypasses the wrapper "just for this endpoint" — bypass routes were a verified audit-hole in the consensus ground truth. - [SCALE: unstable dependency] Add a circuit breaker in the adapter for dependencies with a history of sustained failure (R3/corpus).
- [CORE] Design APIs for backward compatibility: add optional fields; never remove/rename without a version bump; deprecate with a migration path (corpus: api-standards).
5. Security & Trust Boundaries
(consensus P29, R1, R2; corpus: security-and-secrets-policy, authorization-rbac, authentication-patterns, audit-logging)
- [CORE] No secrets in client bundles, ever. Build-time-inlined env prefixes (
VITE_,NEXT_PUBLIC_, …) ship to every visitor — only truly public values may use them (P29/R1: aVITE_secret was a verified live leak). Server-only config modules must be structurally unimportable from client code (e.g.,server-onlyguard or build-flag dead-code elimination). - [CORE] Every internet-facing app ships a CSP: roll out
Content-Security-Policy-Report-Onlyfirst, confirm zero violations, then enforce. Plus the baseline set: HSTS,nosniff,Referrer-Policy,Permissions-Policy, frame-ancestors. One source of truth for headers — never split CSP across edge and app config (R1; corpus: security-and-secrets-policy). - [CORE] Identity comes only from verified credentials (validated JWT claim, server session) — never from user-supplied headers, body fields, or path params. Forgeable identity is privilege escalation (R2; the RLS null-owner hole class).
- [SCALE: multi-tenant or credential-holding server] Three independent auth layers — network (edge policy), transport (per-request token validation), context (identity derived exclusively from the verified token). Losing any one layer must still leave protection (R2; corpus: authorization-rbac). Load credentials lazily per-request; no in-memory credential store between requests.
- [CORE] Least privilege everywhere: minimum scopes, row-level security default-deny (zero client-facing policies until one is explicitly designed), roles defined in one shared module. Anti-pattern: a table shipped with a permissive "temporary" policy.
- [CORE] Never roll your own auth; store tokens server-side or HttpOnly — never localStorage. Use constant-time comparison for shared-secret checks (corpus: authentication-patterns).
- [CORE] Every externally significant mutation writes an append-only audit row (timestamp, actor, correlationId, outcome). Purge by TTL only; never edit entries (corpus: audit-logging). Bypass paths that skip the audited wrapper are defects (§4.4).
- [CORE] No secrets in source control;
.env.examplewith keys only; secrets live in the platform's secret store. Pre-commit secret scanning where available (corpus: configuration-standards, security-and-secrets-policy). - [SCALE: regulated] Attach the conditional compliance modules (encryption-at-rest, data-retention/TTL+purge, GDPR/HIPAA) as a supplement — they are corpus-maintained, not restated here.
6. Observability
(consensus R5, P28-adjacent; corpus: structured-logging, audit-logging, distributed-tracing — scaled per §1.3)
- [CORE] Emit structured (JSON) logs with a consistent schema: timestamp, level, service, correlationId, message, context. String-concatenated logs are unsearchable (corpus: structured-logging).
- [CORE] Propagate a correlationId across every request hop — client → function → third-party call — so one user action is one traceable thread (R5: extend the pattern that already exists in the API wrapper to everything).
- [CORE] Redact PII/secrets in the logging layer by default (denylist paths: password, token, apiKey, secret), not at call sites (R5 ADAPT: the missing half of existing correlation logging).
- [CORE] Production frontends are console-silent but never evidence-silent: errors go to a persistent sink (function endpoint, ring buffer + export) instead of vanishing. A silent prod frontend with no sink makes field bugs unreproducible.
- [CORE] Every mutation leaves evidence — an audit row (§5.7), a structured log line, or both. If an operation fails and nothing recorded it, the observability design is wrong (P28's 38-empty-catches finding is also an observability defect).
- [CORE, scaled] Operator-scale alerting: a health endpoint per service, an uptime/deploy-health check with automated rollback where live traffic exists, and error-sink review as routine — not SLO error budgets, on-call rotations, or incident-command roles. [SCALE: team>3 or contractual SLA] adopt the full corpus alerting/incident apparatus (corpus: alert-definitions, incident-management — scaled per consensus correction).
- [SCALE: multi-service] OpenTelemetry tracing with parent-based sampling; always sample errors and slow spans (corpus: distributed-tracing).
7. Performance Budgets
(consensus P31 ADOPT, P36 ADAPT, P34/P37 principles; corpus: performance-and-bundling)
- [CORE] Core Web Vitals are the standard: LCP < 2.5s, INP < 200ms, CLS < 0.1 (P31 — contestation refuted; thresholds confirmed current). Measure on real pages, not lab-only.
- [CORE] Bundle budgets are directional and ratcheting: set the budget just below current reality, fail CI on regression, tighten after each win. A fixed heroic number (the 2018-era 170KB) is a demoralizing fiction against a multi-MB reality (P36 ADAPT). Code-split routes and heavy dialogs first — it is the highest-leverage cut (P35).
- [CORE] Measure before optimizing; thresholds in advice (node counts, row counts) are heuristics, not laws. Profile the actual hot path, then apply the named remedy (P34's "measure-first"; P37's virtualization trigger is
list > ~200 rows, not "always virtualize"). - [CORE] Keep heavy work off the interaction path: defer non-critical JS, lazy-load below-the-fold, dimension all media to prevent layout shift (corpus: performance-and-bundling).
8. Testing & Verification
(consensus R6 ADOPT, R8 ADAPT; corpus: comprehensive-testing-strategy, runtime-verification, code-review, spec-review-catalog)
- [CORE] Layered pyramid, tool-agnostic: unit (pure logic, no I/O) → integration (module boundaries, real adapters against a test env) → E2E (critical user journeys). The layer definitions bind; the runner (node:test, Vitest, Playwright, …) is the supplement's choice (R8 correction).
- [CORE] Test behavior and output, never internals. No spying on private methods, no snapshot tests for business logic, no real network in unit tests — inject fakes via DI (corpus anti-patterns).
- [CORE] Coverage gates apply to changed files in the PR/commit, not as a global 80/80/75 wall (R8 ADAPT). New logic ships with tests; legacy backfill is scheduled work, not a merge blocker.
- [CORE] Runtime verification: critical integrations get boot-time preflight checks (env present, endpoints reachable, wiring intact) that fail fast and loud. Type-checks and unit tests cannot catch a miswired integration; a preflight can (corpus: runtime-verification).
- [CORE] Adversarial spec review, always — before planning, on every spec. Challenge load-bearing assumptions, blast radius, worst-case-silent-bug. Then run the applicable subset of the 12-lens catalog (security, architecture, paradigm, scope, dependency, schema-migration, API-surface, observability, performance, migration, conversion) by risk profile (R6 ADOPT; corpus: spec-review-catalog). Anti-pattern: review that confirms shape without verifying wiring — sample a real end-to-end path.
- [CORE] Verification before completion: no claim of "done/fixed/passing" without a run command's output, a file:line, or an artifact as evidence. UI changes additionally require a real rendered screenshot (visual confirmation gate).
- [SCALE: team>3] CODEOWNERS-routed human review, ≤400-LOC PRs, review checklist (correctness, tests, security, boundaries, docs/ADR) (corpus: dev-workflow-and-git, code-review). Solo-operator: an automated/agent adversarial pass substitutes, evidence rules unchanged.
9. Delivery & Deploy Gates
(consensus R7 ADAPT, R10 ADAPT; corpus: deployment-workflow, ci-cd-and-releases, ui-feature-flags, dev-workflow-and-git)
- [CORE] Flag-first vertical slice: risky features ship behind a flag (default OFF) with a kill switch, integrated early and often (R10). Roll out staged where audiences exist.
- [CORE] Flags that strip features from production must be statically analyzable so the build dead-code-eliminates them — a runtime-only hide ships the code to everyone.
- [CORE] Progressive tiers: dev → staging → production. Nothing reaches prod without passing the staging gate; promotion is by immutable tag/artifact, not rebuild. Health checks gate each promotion (R7, aligned to the tier model; enterprise auto-rollback ceremony dropped for operator scale — but any live automated deploy still needs a health gate with automatic rollback).
- [CORE] Server-side counterparts of gated features fail closed: absent their secret/env, they return 503-inert, never open (tier-model rule; composes with §5).
- [CORE] Conventional Commits (
type(scope): subject), short-lived branches, automated pre-commit/pre-push gates (format, lint, typecheck, affected tests). CI runs affected lint/test/build on every PR; releases are versioned and changelogged automatically (corpus: dev-workflow-and-git, ci-cd-and-releases). - [CORE] Reproducible installs: lockfile is source of truth; frozen-lockfile in CI.
- [SCALE: public-api or team>3] SBOM generation + CVE gates on PRs; block critical CVEs (corpus: ci-cd-and-releases, security-and-secrets-policy).
10. Decision & Documentation Hygiene
(consensus R9 ADOPT, R10 ADAPT; corpus: documentation-standards)
- [CORE] Comment the why, never the what: hidden constraints, subtle invariants, workarounds for known bugs. Self-describing code needs no comment; a workaround without a comment is a landmine (R9).
- [CORE] Write an ADR when a decision is hard to reverse or crosses module/team boundaries: technology choice, breaking API change, security posture, performance trade-off, strictness waiver. Format: context → decision → consequences, in
docs/adr/NNN-title.md(R9; corpus: documentation-standards). - [CORE] JSDoc/doc-comments on the public surface only (exported API of each package: purpose, params, throws); internal files stay lean.
- [CORE] Lightweight DoR/DoD, not ceremony: Ready = problem + acceptance criteria + test plan sketch; Done = criteria met + tests green + evidence recorded + docs/ADR updated if triggered (R10 ADAPT: the checklist, minus formal sign-off theater). Every package/app carries a minimum README: purpose, quick start, key targets, env-var table.
11. Reversibility & User Feedback
(consensus P28 ADOPT, P21; corpus: error-handling-and-reliability, ux packet lineage)
- [CORE] No silent failure — ever. Every catch block either handles the error meaningfully (recover + inform) or rethrows; it never swallows. Empty catches are lint-banned (P28: 38 empty catches, silent auto-save loss was the verified harm).
- [CORE] Failures the user caused or can remedy get a visible error with a retry affordance; background failures (auto-save) get a persistent, non-blocking indicator — not a toast that expires unseen. Anti-pattern: a single-slot toast queue where the second error deletes the first.
- [CORE] Destructive operations are reversible: undo for single-item destruction, explicit confirmation (with consequence summary) for cascading destruction. Confirmation is for irreversibility; undo is better than confirmation where feasible (P21/P28).
- [CORE] Optimistic updates always carry a rollback path; on failure the UI reverts and says so (P28).
- [CORE] Every async operation the user is waiting on shows a pending state; every terminal state (success/failure) is communicated. In-flight ambiguity causes double-submits — pair with idempotency (§4.2).
Supplements: 10-supplement-react-ts-vite.md · 11-supplement-node-serverless.md. Adoption: 20-INDEX.md.